http://stackoverflow.com/comment/84634955
score: 0
type: Comment
type: QuestionComment
has text: Added, trace for Test 2. Actually, because this algorithm is recursive it has a lot of different values. I was using Debug but seems like the problem is in the algorithm itself.
comment on: http://stackoverflow.com/q/48814955

http://stackoverflow.com/q/48874556
tagged with: django
tagged with: python
has body: While Django doesn't completely support adding the through attribute to a M2M field (in order to add some extra fields), it can be migrated. The main issue is, Django will complain when any code tries to .add() models to the related set even if there are no required fields in the through model outside of the FKs of the linked models. So, I want to add a nullable field to the through model and still keep .add() and remove working like it was before (and implicitely using None as the nullable field value). Adding auto_created=True in the meta almost works, but it breaks migrations amongst other things. Is there any way to make it work outside of overriding the many2many descriptor (which isn't exactly included in the public API, though a lot of third-party Django packages use it)?
answer count: 0
has comment: http://stackoverflow.com/comment/84764401
tagged with: orm
type: Question
has comment: http://stackoverflow.com/comment/84772787
score: 0
has title: Is there any way to add through to M2M field with keeping the related manager's .add() working?
type: UnansweredQuestion

http://stackoverflow.com/comment/84726414
has text: you need to change your rates method accordingly
comment on: http://stackoverflow.com/a/48861475
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48960059
upvote count: 1
has comment: http://stackoverflow.com/comment/84926887
tagged with: python
has body: I am opening a URL and trying to click on the Search button described here below: &lt;td class="th-sa-tb-bt"&gt; &lt;span class="th-bt-up"&gt; &lt;a href="javascript:void(0)" class="th-bt th-bt-text-em" onclick="thBtMgr.click(this);return htmlbSL(this,2,'J22_MNQ_LOP_V1WR_SEARCH_BTN:SEARCH','0')" onmousedown="thBtMgr.press(this,event);" onfocusout="thBtMgr.unpress(this);" onfocus="thSaveKbFocus(this);" oncontextmenu="return false;" ondragstart="return false;" id="J22_MNQ_LOP_V1WR_SEARCH_BTN" title="Search"&gt; &lt;span class="th-bt-span"&gt; &lt;b class="th-bt-b"&gt;Search&lt;/b&gt; &lt;/span&gt; &lt;/a&gt; &lt;/span&gt; &lt;span class="th-bt-spacer"&gt; &lt;!-- --&gt; &lt;/span&gt;&amp;nbsp; &lt;span class="th-bt-up"&gt; &lt;a href="javascript:void(0)" class="th-bt th-bt-text" onclick="thBtMgr.click(this);return htmlbSL(this,2,'J22_MNQ_LOP_V1WR_CLEAR_BTN:\x23Exit\x23_CLEAR','0')" onmousedown="thBtMgr.press(this,event);" onfocusout="thBtMgr.unpress(this);" onfocus="thSaveKbFocus(this);" oncontextmenu="return false;" ondragstart="return false;" id="J22_MNQ_LOP_V1WR_CLEAR_BTN" title="Clear"&gt; &lt;span class="th-bt-span"&gt; &lt;b class="th-bt-b"&gt;Clear&lt;/b&gt; &lt;/span&gt; &lt;/a&gt; &lt;/span&gt; &lt;span class="th-bt-spacer"&gt; &lt;!-- --&gt; &lt;/span&gt;&amp;nbsp; &lt;span class="th-bt-up"&gt; &lt;a href="javascript:void(0)" class="th-bt th-bt-text" onclick="thBtMgr.click(this);return htmlbSL(this,2,'J22_MNQ_LOP_V1WR_BtnReset:RESET','0')" onmousedown="thBtMgr.press(this,event);" onfocusout="thBtMgr.unpress(this);" onfocus="thSaveKbFocus(this);" oncontextmenu="return false;" ondragstart="return false;" id="J22_MNQ_LOP_V1WR_BtnReset" title="Reset"&gt; &lt;span class="th-bt-span"&gt; &lt;b class="th-bt-b"&gt;Reset&lt;/b&gt; &lt;/span&gt; &lt;/a&gt; &lt;/span&gt; &lt;span class="th-bt-spacer"&gt; &lt;!-- --&gt; &lt;/span&gt; &lt;/td&gt; Here when I copy the xpath for the search button element J22_MNQ_LOP_V1WR_SEARCH_BTN it gives me timeout error. Here is the co…
has comment: http://stackoverflow.com/comment/84954854
has comment: http://stackoverflow.com/comment/84928355
has comment: http://stackoverflow.com/comment/84957303
tagged with: selenium-webdriver
has comment: http://stackoverflow.com/comment/84926781
has answer: http://stackoverflow.com/a/48960509
has comment: http://stackoverflow.com/comment/84926984
score: 1
tagged with: selenium
has answer: http://stackoverflow.com/a/48969382
has comment: http://stackoverflow.com/comment/84928290
has comment: http://stackoverflow.com/comment/84933869
has comment: http://stackoverflow.com/comment/84927490
type: Question
has comment: http://stackoverflow.com/comment/84928128
has comment: http://stackoverflow.com/comment/84937430
downvote count: 0
has answer: http://stackoverflow.com/a/48960665
has comment: http://stackoverflow.com/comment/84926810
has comment: http://stackoverflow.com/comment/84927805
has title: Clicking on a button using selenium [Python]
has answer: http://stackoverflow.com/a/49033911
linked to: http://stackoverflow.com/q/44187909
has comment: http://stackoverflow.com/comment/84926768
has comment: http://stackoverflow.com/comment/84928441
has comment: http://stackoverflow.com/comment/84928321
has comment: http://stackoverflow.com/comment/84927109
has comment: http://stackoverflow.com/comment/84928158
favorite count: 0
has answer: http://stackoverflow.com/a/49032749
has comment: http://stackoverflow.com/comment/84954682
has comment: http://stackoverflow.com/comment/85071038
tagged with: selenium-chromedriver
tagged with: python-3.x
answer count: 5
type: UnansweredQuestion

http://stackoverflow.com/a/48857842
upvote count: 2
answers question: http://stackoverflow.com/q/48857303
score: 2
has body: You can also specify the 2-level multi-indices explicitly. df.groupby([("B","c"), ("B", "d")])
downvote count: 0
type: Answer

http://stackoverflow.com/q/48814201
has title: Running python script inside a functional test in Django
has answer: http://stackoverflow.com/a/48814305
type: Question
tagged with: functional-testing
has body: The project that I'm recently working on load initial data by running a script: python manage.py shell &lt; add_initial_data.py I'm making functional tests now and have to call this command to load initial data in the test database. I'm trying to use subprocess.call and call_command to run that script but I can't find the option to redirect the script file to shell. Is there a way to do that? I've tried with subprocess.call(['python', 'manage.py', 'shell', '&lt;', 'add_initial_data.py']) and call_command('shell', '&lt;', 'add_initial_data.py') but gives error not recognizing &lt; add_initial_data.py
linked to: http://stackoverflow.com/q/16853649
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/48944107
downvote count: 0
has comment: http://stackoverflow.com/comment/84896577
type: Answer
upvote count: 7
has body: Try this: import pandas as pd def parse_nested_json(json_d): result = {} for key in json_d.keys(): if not isinstance(json_d[key], dict): result[key] = json_d[key] else: result.update(parse_nested_json(json_d[key])) return result json_data = pd.read_json("my_json_file.json") json_list = [j[1][0] for j in json_data.iterrows()] parsed_list = [parse_nested_json(j) for j in json_list] result = pd.DataFrame(parsed_list) result.to_csv("my_csv_file.csv", index=False) Update(12/3/2018): I read the docs, there is a convenient way: from pandas.io.json import json_normalize df = json_normalize(data["profile_set"]) df.to_csv(...) Update(11/7/2021): pandas.io.json.json_normalize is deprecated, use pandas.json_normalize instead from pandas import json_normalize df = json_normalize(data["profile_set"]) df.to_csv(...)
answers question: http://stackoverflow.com/q/48942801
score: 7
has comment: http://stackoverflow.com/comment/84895685
accepted answer of: http://stackoverflow.com/q/48942801
type: AcceptedAnswer

http://stackoverflow.com/comment/84729608
comment on: http://stackoverflow.com/a/48861955
score: 0
type: AnswerComment
type: Comment
has text: Great! Exactly what I was looking for. The overhead is acceptable. But something like a broadcasted, length squared temp array would be too much.

edit-distance
type: Tag
tag name: edit-distance
tags question: http://stackoverflow.com/q/48819439

http://stackoverflow.com/comment/84681272
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48838305
has text: I need to convert pdf English version to pdf French version

http://stackoverflow.com/q/48930663
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/6523791
accepted answer: http://stackoverflow.com/a/48930696
type: Question
tagged with: python-import
has comment: http://stackoverflow.com/comment/84868553
has title: How to prevent execution of main Python code when importing a function
possible better answer: http://stackoverflow.com/a/48930701
score: 0
has answer: http://stackoverflow.com/a/48930701
answer count: 2
has body: Consider the two following files: test.py: import sys def testfunction(string): print(string) sys.exit(0) test2.py: from test import testfunction testfunction("string") I would expect the import of testfunction not to execute statements outside of that function, e.g., sys.exit(0). Why is this happening, and how can I prevent it?
has answer: http://stackoverflow.com/a/48930696
tagged with: python
linked to: http://stackoverflow.com/q/419163

http://stackoverflow.com/a/48815307
has comment: http://stackoverflow.com/comment/84766350
type: Answer
has comment: http://stackoverflow.com/comment/84739408
has comment: http://stackoverflow.com/comment/84666301
has comment: http://stackoverflow.com/comment/84686856
upvote count: 2
has comment: http://stackoverflow.com/comment/84762435
has comment: http://stackoverflow.com/comment/84733114
has body: Yes, you can know the features and their contributions (weight is not the right term) that impacted the prediction of a specific observation. This actually constitutes the decision_path for how it made that decision of that particular observation. What you are looking for is TreeInterpreter. The second question is: Why are there always two values for each variable and instance (such as [0.12 -0.12] for the first feature and first instance) that seem to be positive and negative, rather than one value of that feature? So my answer is: Each of these lists (such as [0.12 -0.12]) just represents the contribution of a feature to the final probability of an instance being in class 1 and class 2. Remember, features never dictate what class an instance must be in, but instead, they increase or decrease the final class probabilities of an instance. So 0.12 means that Feature 1 added 0.12 to the probability of instance 0 being in class 1, and reduced its probability of being in class 2 by 0.12. These values are always symmetric, meaning that whatever makes an instance more likely to be in class 1 makes it less likely to be in class 2. Similarly, Feature 2 reduced probability of instance 1 being class 1 by 0.05, and increased its probability of being class 2 by 0.05. So each feature contributed (added or reduced) to instance 1 being in class 1 by: 0.12, -0.05, 0.22, 0.14, 0.07, 0.01. Now add these all up to the bias of being in class 1 (0.49854), you get 1, which is the final probability of that instance being in class 1, as shown by the model output. Similarly, add all of the second values of each list, and add the bias of being in class 2 (0.50146), you get 0, which is the final probability of that instance being in class 2, as shown by the model output above. Finally repeat the exact same exercise for instance 1, i.e. add -0.03, -0.11, 0.06, 0, -0.06, -0.04 to the bias of 0.49854, you get 0.32, which is the P{instance1 = class1}. And add 0.03, 0.11, -0.06, 0, 0.06, 0.04 to t…
score: 2
has comment: http://stackoverflow.com/comment/84729658
accepted answer of: http://stackoverflow.com/q/48808985
has comment: http://stackoverflow.com/comment/84658983
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84746545
has comment: http://stackoverflow.com/comment/84745710
answers question: http://stackoverflow.com/q/48808985
has comment: http://stackoverflow.com/comment/84746497
has comment: http://stackoverflow.com/comment/84728790

http://stackoverflow.com/a/48926889
type: Answer
accepted answer of: http://stackoverflow.com/q/48914528
score: 8
answers question: http://stackoverflow.com/q/48914528
has body: It's doesn't work because allure report as you seen is not a simple Webpage, you could not save it and send as file to you team. It's a local Jetty server instance, serves generated report and then you can open it in the browser. Here for your needs some solutions: One server(your local PC, remote or some CI environment), where you can generate report and share this for you team. (server should be running alltime) Share allure report folder as files({folder that contains the json files}) to teammates, setup them allure tool, and run command allure server on them local(which one). Hope, it helps.
upvote count: 8
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84994954

http://stackoverflow.com/a/48894267
type: Answer
has body: Have you considered using a profiler? $ echo "8" | python3 eightqueens.py YES 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1686133 function calls (1660190 primitive calls) in 6.467 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 6.467 6.467 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 codecs.py:318(decode) 1 0.000 0.000 0.000 0.000 eightqueens.py:1(Print) 25944/1 1.180 0.000 6.467 6.467 eightqueens.py:13(alg) 1 0.000 0.000 6.467 6.467 eightqueens.py:27(blaha) 8 0.000 0.000 0.000 0.000 eightqueens.py:29(&lt;listcomp&gt;) 1660100 5.286 0.000 5.286 0.000 eightqueens.py:6(is_attacked) 1 0.000 0.000 0.000 0.000 {built-in method _codecs.utf_8_decode} 1 0.000 0.000 6.467 6.467 {built-in method builtins.exec} 1 0.000 0.000 0.000 0.000 {built-in method builtins.input} 73 0.000 0.000 0.000 0.000 {built-in method builtins.print} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} Based on this, you can see that your is_attached() function is the most called function consuming by far most of the execution time. This is where you most likely want to focus your efforts if you want your code to run faster. I modified your code slightly to get the result you see above. The code I used follows. def Print(matrix): for row in matrix: for elem in row: print(elem, end=' ') print() def is_attacked(matrix,j,i,N): for a in range(N): for b in range(N): if matrix[a][b]: if j == a or i-j == b-a or b == i or i+j == b+a: return(True) return(False) def alg(matrix,N,number_of_queens): if number_of_queens == 0: return(True) for a in range(N): for b in range(N): if is_attacked(matrix,a,b,N): continue matrix[a][b] = 1 if alg(matrix,N,number_of_queens-1): return(True) else: matrix[a][b] = 0 return(False) def blaha(): N = int(input()) matrix = [[0 for x in range(N)] for y in range(N)] if alg(matrix,N,N): print("YES") Pr…
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48893231
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48893231

python
tags question: http://stackoverflow.com/q/48870383
tags question: http://stackoverflow.com/q/48945163
tags question: http://stackoverflow.com/q/48840025
tags question: http://stackoverflow.com/q/48902767
tags question: http://stackoverflow.com/q/48848357
tags question: http://stackoverflow.com/q/48828545
tags question: http://stackoverflow.com/q/48941548
tags question: http://stackoverflow.com/q/48831162
tags question: http://stackoverflow.com/q/48867625
tags question: http://stackoverflow.com/q/48917460
tags question: http://stackoverflow.com/q/48931842
tags question: http://stackoverflow.com/q/48893256
tags question: http://stackoverflow.com/q/48861657
tags question: http://stackoverflow.com/q/48835275
tags question: http://stackoverflow.com/q/48884766
tags question: http://stackoverflow.com/q/48852452
tags question: http://stackoverflow.com/q/48900858
tags question: http://stackoverflow.com/q/48844520
tags question: http://stackoverflow.com/q/48811352
tags question: http://stackoverflow.com/q/48942459
tags question: http://stackoverflow.com/q/48948769
tags question: http://stackoverflow.com/q/48954138
tags question: http://stackoverflow.com/q/48816136
tags question: http://stackoverflow.com/q/48836110
tags question: http://stackoverflow.com/q/48839626
tags question: http://stackoverflow.com/q/48873638
tags question: http://stackoverflow.com/q/48954446
tags question: http://stackoverflow.com/q/48951818
tags question: http://stackoverflow.com/q/48940734
tags question: http://stackoverflow.com/q/48805282
tags question: http://stackoverflow.com/q/48903470
tags question: http://stackoverflow.com/q/48840360
tags question: http://stackoverflow.com/q/48918231
tags question: http://stackoverflow.com/q/48869788
tags question: http://stackoverflow.com/q/48812665
tags question: http://stackoverflow.com/q/48817143
tags question: http://stackoverflow.com/q/48877844
tags question: http://stackoverflow.com/q/48852513
tags question: http://stackoverflow.com/q/48865970
tags question: http://stackoverflow.com/q/48831091
tags question: http://stackoverflow.com/q/48804934
tags question: http://stackoverflow.com/q/48870171
tags question: http://stackoverflow.com/q/48824516
tags question: http://stackoverflow.com/q/48842303
tags question: http://stackoverflow.com/q/48942663
tags question: http://stackoverflow.com/q/48948319
tags question: http://stackoverflow.com/q/48854439
tags question: http://stackoverflow.com/q/48842742
tags question: http://stackoverflow.com/q/48947754
tags question: http://stackoverflow.com/q/48911270
tags question: http://stackoverflow.com/q/48932685
tags question: http://stackoverflow.com/q/48952515
tags question: http://stackoverflow.com/q/48912695
tags question: http://stackoverflow.com/q/48873051
tags question: http://stackoverflow.com/q/48853316
tags question: http://stackoverflow.com/q/48941964
tags question: http://stackoverflow.com/q/48950800
tags question: http://stackoverflow.com/q/48820732
tags question: http://stackoverflow.com/q/48921965
tags question: http://stackoverflow.com/q/48891601
tags question: http://stackoverflow.com/q/48950745
tags question: http://stackoverflow.com/q/48814201
tags question: http://stackoverflow.com/q/48875609
tags question: http://stackoverflow.com/q/48944593
tags question: http://stackoverflow.com/q/48861533
tags question: http://stackoverflow.com/q/48891094
tags question: http://stackoverflow.com/q/48812979
tags question: http://stackoverflow.com/q/48898196
tags question: http://stackoverflow.com/q/48908102
tags question: http://stackoverflow.com/q/48903222
tags question: http://stackoverflow.com/q/48874285
tags question: http://stackoverflow.com/q/48843578
tags question: http://stackoverflow.com/q/48941504
tags question: http://stackoverflow.com/q/48864581
tags question: http://stackoverflow.com/q/48824842
tags question: http://stackoverflow.com/q/48883208
tags question: http://stackoverflow.com/q/48918009
tags question: http://stackoverflow.com/q/48886262
tags question: http://stackoverflow.com/q/48842926
tags question: http://stackoverflow.com/q/48812162

http://stackoverflow.com/a/48921985
score: 1
answers question: http://stackoverflow.com/q/48921736
upvote count: 1
type: Answer
downvote count: 0
has body: You need two separate while loops for that purpose. One for number and the other one for day. Here is the corrected code: number = "" day = "" while True: number = raw_input("Number: ") if not number.isdigit() or len(number) != 4: print "Error, Please enter a 4 digit number \n" else: break while True: day = raw_input("Day: ") if not day.isdigit(): print "\n Error, please enter day in digits \n" else: break print "Number: ", number print "Day: ", day

http://stackoverflow.com/q/48901279
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48901325
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/48901325
type: Question
has body: I have the following problem: There are four teams, which have each been assigned an ID number (1 to 4). They play each other just once and earn points. The results from the games is in a Pandas DataFrame as below: +----------------+----------------+-------------+-------------+ | Home Player ID | Away Player ID | Home Points | Away Points | +----------------+----------------+-------------+-------------+ | 1 | 2 | 3 | 0 | | 3 | 4 | 1 | 1 | | 2 | 3 | 3 | 0 | | 4 | 1 | 3 | 0 | | 2 | 4 | 1 | 1 | | 3 | 1 | 1 | 1 | +----------------+----------------+-------------+-------------+ The aim is to sum each player's points, based on their ID's, regardless of whether they played home or away. I have achieved this is in a very scrappy way by creating two new DataFrames firstly for the Home, and then for the Away, renaming column names so they are uniform, and then using pd.concat to combine them into two columns: Player ID and Player Points. However, this seems a very inefficient way of doing this and I am hoping to find a far more efficient method! The end result would look like this: | Player ID | Total Points | +-----------+--------------+ | 1 | 4 | | 2 | 4 | | 3 | 2 | | 4 | 5 | +-----------+--------------+ I would really appreciate any help/advice, and if anything is explained badly, please let me know!
downvote count: 0
answer count: 1
tagged with: pandas
has title: Summing based on IDs across multiple columns in Pandas

http://stackoverflow.com/q/48882468
upvote count: 8
tagged with: datetime
tagged with: python
tagged with: diff
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84769317
has answer: http://stackoverflow.com/a/48882705
has body: I have got into an issue or might quite possibly feature in turn! Not sure, wondering!! In python's datetime library, to get difference in time, as in below snippet. &gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.datetime.now() - datetime.datetime.now() datetime.timedelta(-1, 86399, 999958) &gt;&gt;&gt; tnow = datetime.datetime.now() &gt;&gt;&gt; datetime.datetime.now() - tnow datetime.timedelta(0, 4, 327859) I would like to understand why datetime.datetime.now() - datetime.datetime.now() is producing output as -1 days, 86399 seconds whereas assigning current time to some variable and computing difference gives desired output 0 days, 4 seconds. The results seems to be bit confusing, it would be helpful if someone could decode whats going behind Note: I'm using Python 2.7
has title: Python difference in datetime now against datetime now
type: Question
possible better answer: http://stackoverflow.com/a/48883028
accepted answer: http://stackoverflow.com/a/48882705
answer count: 2
score: 8
has answer: http://stackoverflow.com/a/48883028
has comment: http://stackoverflow.com/comment/84769222
has comment: http://stackoverflow.com/comment/84769375
linked to: http://stackoverflow.com/q/8408397
has comment: http://stackoverflow.com/comment/84769366
downvote count: 0
favorite count: 0

http://stackoverflow.com/a/48897105
score: 1
answers question: http://stackoverflow.com/q/48895991
type: Answer
upvote count: 1
has body: Try this, create a base test class and have all your test classes inherit it. Having said, i dont know if the webdriver will play along well (untested) import unittest class BaseTest(unittest.TestCase): def setUp(self): print('--- Setup ---') def tearDown(self): print('--- Tear Down ---') class Test1(BaseTest): def test_equal(self): self.assertEqual(1, 1) class Test2(BaseTest): def test_equal(self): self.assertEqual(2, 2) if __name__ == '__main__': unittest.main() Output: --- Setup --- .--- Tear Down --- --- Setup --- --- Tear Down --- . ---------------------------------------------------------------------- Ran 2 tests in 0.001s
downvote count: 0

http://stackoverflow.com/q/48947759
has comment: http://stackoverflow.com/comment/84901994
downvote count: 8
has comment: http://stackoverflow.com/comment/84905445
tagged with: datetime
has comment: http://stackoverflow.com/comment/84904287
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84904125
has comment: http://stackoverflow.com/comment/84905208
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48949664
has comment: http://stackoverflow.com/comment/84902605
has body: string1 = "2018-Feb-23-05-18-11" I would like to replace a particular pattern in a string. Output should be 2018-Feb-23-5-18-11. How can i do that by using re.sub ? Example: import re output = re.sub(r'10', r'20', "hello number 10, Agosto 19") #hello number 20, Agosto 19 Fetching the current_datetime from datetime module. i'm formatting the obtained datetime in a desired format. ts = time.time() st = datetime.datetime.fromtimestamp(ts).strftime("%Y-%b-%d-%I-%M-%S") I thought, re.sub is the best way to do that. ex1 : string1 = "2018-Feb-23-05-18-11" output : 2018-Feb-23-5-18-11 ex2 : string1 = "2018-Feb-23-05-8-11" output : 2018-Feb-23-5-08-11
has comment: http://stackoverflow.com/comment/84904330
has comment: http://stackoverflow.com/comment/84904621
upvote count: 1
possible better answer: http://stackoverflow.com/a/48948034
type: Question
has comment: http://stackoverflow.com/comment/84901734
has answer: http://stackoverflow.com/a/48949664
has comment: http://stackoverflow.com/comment/84901826
has comment: http://stackoverflow.com/comment/84901890
has title: How to replace a pattern using regular expression?
answer count: 2
has comment: http://stackoverflow.com/comment/84901884
has comment: http://stackoverflow.com/comment/84901853
score: -7
has answer: http://stackoverflow.com/a/48948034
favorite count: 0

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

http://stackoverflow.com/a/48931560
type: AcceptedAnswer
downvote count: 0
has body: Convert the string object to a JSON object. Ex: import json jData = json.loads('{"success":true,"key":"Syv77d","link":"https://file.io/Syv77d","expiry":"14 days"}') jData["link"]
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84869881
score: 1
accepted answer of: http://stackoverflow.com/q/48931479
has comment: http://stackoverflow.com/comment/84870527
answers question: http://stackoverflow.com/q/48931479

http://stackoverflow.com/a/48907310
type: Answer
downvote count: 0
score: 1
has body: The regex finds each of the strings afer ": " until a space is found. For this to work on the entire string a space should be added to the end of it. import re string = string + ' ' result = re.findall(': (.*?) ', string) print(' '.join(result))
answers question: http://stackoverflow.com/q/48907107
upvote count: 1

http://stackoverflow.com/q/48905957
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84820992
has title: Can't load workbook with openpyxl: during handling of the above exception, another exception occurred
accepted answer: http://stackoverflow.com/a/49030212
favorite count: 0
type: Question
tagged with: http://stackoverflow.com/tag/xlsx
tagged with: python
has body: I want to edit a xlsx file with openpyxl 2.5.0. This is my code and it works with an empty file: from openpyxl import load_workbook wb = load_workbook(filename="Untitled.xlsx") ws = wb.active ws["B5"] = "test" wb.save("Export.xlsx") However if I try to load this file, I get the following obscure error. Traceback (most recent call last): File "C:\Matteo\PyCharm\CMakeR\venv\lib\site-packages\openpyxl\descriptors\base.py", line 57, in _convert value = expected_type(value) ValueError: invalid literal for int() with base 10: 'l' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Matteo\PyCharm\CMakeR\XLSXEditor.py", line 3, in &lt;module&gt; wb = load_workbook(filename="Modulo CMR.xlsx") File "C:\Matteo\PyCharm\CMakeR\venv\lib\site-packages\openpyxl\reader\excel.py", line 274, in load_workbook for c in find_charts(archive, rel.target): File "C:\Matteo\PyCharm\CMakeR\venv\lib\site-packages\openpyxl\chart\reader.py", line 43, in find_charts drawing = SpreadsheetDrawing.from_tree(tree) File "C:\Matteo\PyCharm\CMakeR\venv\lib\site-packages\openpyxl\descriptors\serialisable.py", line 84, in from_tree obj = desc.expected_type.from_tree(el) File "C:\Matteo\PyCharm\CMakeR\venv\lib\site-packages\openpyxl\descriptors\serialisable.py", line 84, in from_tree obj = desc.expected_type.from_tree(el) File "C:\Matteo\PyCharm\CMakeR\venv\lib\site-packages\openpyxl\descriptors\serialisable.py", line 84, in from_tree obj = desc.expected_type.from_tree(el) [Previous line repeated 1 more times] File "C:\Matteo\PyCharm\CMakeR\venv\lib\site-packages\openpyxl\descriptors\serialisable.py", line 100, in from_tree return cls(**attrib) File "C:\Matteo\PyCharm\CMakeR\venv\lib\site-packages\openpyxl\drawing\shapes.py", line 349, in __init__ self.l = l File "C:\Matteo\PyCharm\CMakeR\venv\lib\site-packages\openpyxl\descriptors\base.py", line 69, in __set__ value = _convert(self.expected_type, value) File "C:\Matteo\PyCharm\CMakeR\venv\lib\site…
upvote count: 6
tagged with: openpyxl
answer count: 1
has answer: http://stackoverflow.com/a/49030212
score: 6
has comment: http://stackoverflow.com/comment/95896548
tagged with: drawingml

http://stackoverflow.com/a/48895707
answers question: http://stackoverflow.com/q/48856477
score: 0
has body: To filter your list you can use list comprehensions: input_list = [1,2.6,'hi',3,'blah',{},99] filtered_list = [x for x in input_list if type(x) is int] &gt;&gt;&gt; [1,3,99] Then you can reverse that list in whatever way you want according to your homework constraints. Normally you'd call .reverse() on the filtered_list but up to you. If list.reverse() is out, I don't know if list.instert() is allowed, but if it is, then you can do: reversed_filtered_list = [] for i in filtered_list: reversed_filtered_list.insert(0, i)
type: Answer

http://stackoverflow.com/q/48843380
downvote count: 0
has comment: http://stackoverflow.com/comment/84691123
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84691579
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48843815
has comment: http://stackoverflow.com/comment/84691054
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84691052
has comment: http://stackoverflow.com/comment/84691387
has body: I have an CSV file, which has the current format below. A two row example of this would be: first_Name last_Name test1 test2 test3 test4 Alex Brian 11 17 13 24 Pete Tong 19 14 12 30 Now my current code does not work, Simply put I am not sure if I am on the right track. My current code: def grader(test1, test2, test3, finalExam): first = test1 * .20 second = test2 * .20 third = test3 * .20 fourth = finalExam *.40 finalGrade = first + second + third + fourth return finalGrade def gradeScores(FinalGrade): if FinalGrade &gt;= 90 and FinalGrade &lt;= 100: return("You received an A") elif FinalGrade &gt;= 80 and FinalGrade &lt; 90: return("You received a B") elif FinalGrade &gt;= 70 and FinalGrade &lt; 80: return("You received a C") elif FinalGrade &gt;= 60 and FinalGrade &lt; 70: return("You received a D") else: return("Sorry, you received an F") I also have this line of code which is to read the CSV file, and displays in the output window. with open("studentGradeFrom.csv") as csvfile: readFile = csv.reader(csvfile, delimiter=",", quotechar="¦") for row in readFile: print(row) However since I am new to Python, I am looking for help to create a python script, that will look at the results and do a calculation which will tell me if the student has passed or failed. I would like this to be done in a separate file. So I am guessing that I will need to read and write to a different CSV file, to show if a student has failed or has an overall passing percentage. with open("studentGradeTo.csv", 'w') as avg: #used to write to after the calculation is complete loadeddata = open("studentGradeFrom.csv", 'r') #used to read the data from the CSV before calculation. writer=csv.writer(avg) readloaded=csv.reader(loadeddata) listloaded=list(readloaded) Now my question: How would I go about doing this, from looking at data from one file which roughly 50 different students. While not changing the read CSV with the student grades, and only changing the CSV file which shows passing or failing…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84691434
has title: CSV file for calculating passing of failing grade from a set of marks
has comment: http://stackoverflow.com/comment/84691961
has comment: http://stackoverflow.com/comment/84691566
type: Question
accepted answer: http://stackoverflow.com/a/48843815
answer count: 2
has comment: http://stackoverflow.com/comment/84691464
has comment: http://stackoverflow.com/comment/84691209
linked to: http://stackoverflow.com/q/19575456
possible better answer: http://stackoverflow.com/a/48844026
has answer: http://stackoverflow.com/a/48844026
tagged with: http://stackoverflow.com/tag/csv

django-models
tag name: django-models
tags question: http://stackoverflow.com/q/48877669
tags question: http://stackoverflow.com/q/48896000
tags question: http://stackoverflow.com/q/48884058
tags question: http://stackoverflow.com/q/48918452
tags question: http://stackoverflow.com/q/48935296
tags question: http://stackoverflow.com/q/48842022
tags question: http://stackoverflow.com/q/48944520
tags question: http://stackoverflow.com/q/48849928
tags question: http://stackoverflow.com/q/48914518
tags question: http://stackoverflow.com/q/48919241
tags question: http://stackoverflow.com/q/48905517
tags question: http://stackoverflow.com/q/48853052
tags question: http://stackoverflow.com/q/48863201
tags question: http://stackoverflow.com/q/48836694
tags question: http://stackoverflow.com/q/48849954
tags question: http://stackoverflow.com/q/48911345
tags question: http://stackoverflow.com/q/48817253
tags question: http://stackoverflow.com/q/48908156
tags question: http://stackoverflow.com/q/48884821
tags question: http://stackoverflow.com/q/48834945
tags question: http://stackoverflow.com/q/48949974
tags question: http://stackoverflow.com/q/48900409
tags question: http://stackoverflow.com/q/48840076
tags question: http://stackoverflow.com/q/48924366
type: Tag
tags question: http://stackoverflow.com/q/48887001
tags question: http://stackoverflow.com/q/48848703
tags question: http://stackoverflow.com/q/48920949
tags question: http://stackoverflow.com/q/48886029
tags question: http://stackoverflow.com/q/48863514
tags question: http://stackoverflow.com/q/48829574
tags question: http://stackoverflow.com/q/48844665
tags question: http://stackoverflow.com/q/48943292
tags question: http://stackoverflow.com/q/48811082
tags question: http://stackoverflow.com/q/48948219
tags question: http://stackoverflow.com/q/48912441
tags question: http://stackoverflow.com/q/48905283
tags question: http://stackoverflow.com/q/48811381
tags question: http://stackoverflow.com/q/48850438
tags question: http://stackoverflow.com/q/48889756
tags question: http://stackoverflow.com/q/48805703
tags question: http://stackoverflow.com/q/48936463
tags question: http://stackoverflow.com/q/48861220
tags question: http://stackoverflow.com/q/48908102
tags question: http://stackoverflow.com/q/48812162
tags question: http://stackoverflow.com/q/48886332
tags question: http://stackoverflow.com/q/48808282
tags question: http://stackoverflow.com/q/48832188
tags question: http://stackoverflow.com/q/48832327
tags question: http://stackoverflow.com/q/48828101

http://stackoverflow.com/q/48953899
tagged with: python
has title: Issue Updating Confluence Page with Python and API
type: AnsweredQuestion
downvote count: 0
tagged with: confluence
type: Question
score: 1
has body: I am working on updating a Confluence page via python and the Confluence API. I have found a function to write the data to the my page, unfortunately it creates a new page with my data and the old page becomes an archived version. I have been searching the reference material and cannot see the reason I am getting a new page instead of appending the data to the end of the page. The only solution I can think of is to copy the body and append the new data to it, then create the new page ... but I am thinking there should be a way to append. The write function code I found / am leveraging is as follows : def write_data(auth, html, pageid, title = None): info = get_page_info(auth, pageid) print ("after get page info") ver = int(info['version']['number']) + 1 ancestors = get_page_ancestors(auth, pageid) anc = ancestors[-1] del anc['_links'] del anc['_expandable'] del anc['extensions'] if title is not None: info['title'] = title data = { 'id' : str(pageid), 'type' : 'page', 'title' : info['title'], 'version' : {'number' : ver}, 'ancestors' : [anc], 'body' : { 'storage' : { 'representation' : 'storage', 'value' : str(html), } } } data = json.dumps(data) pprint (data) url = '{base}/{pageid}'.format(base = BASE_URL, pageid = pageid) r = requests.put( url, data = data, auth = auth, headers = { 'Content-Type' : 'application/json' } ) r.raise_for_status() I am starting to think copying / appending to the body is the option, but hope someone else has encountered this issue.
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48992467
accepted answer: http://stackoverflow.com/a/48992467
favorite count: 0
tagged with: confluence-rest-api

http://stackoverflow.com/q/48854809
upvote count: 1
has comment: http://stackoverflow.com/comment/84713226
linked to: http://stackoverflow.com/q/43824942
favorite count: 0
answer count: 1
tagged with: python
tagged with: pycharm
has body: I'm trying to create a browser using Python and the library PyQt5 I installed correctly the library but i don't know why components can't be found. Is there a reason why the components can't be found? Thank you in advance This is my code import PyQt5 from PyQt5.QtCore import QUrl from PyQt5.QtWidgets import QApplication, QWidget from PyQt5.QtWebKitWidgets import QWebView, QWebPage from PyQt5.QtWebKit import QWebSettings from PyQt5.QtNetwork import * import sys from optparse import OptionParser class MyBrowser(QWebPage): ''' Settings for the browser.''' def userAgentForUrl(self, url): ''' Returns a User Agent that will be seen by the website. ''' return "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36" class Browser(QWebView): def __init__(self): # QWebView self.view = QWebView.__init__(self) # self.view.setPage(MyBrowser()) self.setWindowTitle('Loading...') self.titleChanged.connect(self.adjustTitle) # super(Browser).connect(self.ui.webView,QtCore.SIGNAL("titleChanged (const QString&)"), self.adjustTitle) def load(self, url): self.setUrl(QUrl(url)) def adjustTitle(self): self.setWindowTitle(self.title()) def disableJS(self): settings = QWebSettings.globalSettings() settings.setAttribute(QWebSettings.JavascriptEnabled, False) app = QApplication(sys.argv) view = Browser() view.showMaximized() view.load("https://pythonspot.com") app.exec_() This is where i get the error "Unresolved reference"
tagged with: pyqt5
accepted answer: http://stackoverflow.com/a/48855153
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48855153
type: Question
has title: Error installing PyQt5 library: unresolved reference

http://stackoverflow.com/comment/84910533
comment on: http://stackoverflow.com/q/48951166
has text: No, I only have the two drives and don't want to reformat either at this point. The exFAT one works fine with Mac, though, shouldn't corrupted sectors cause trouble on any OS?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48915822
answer count: 1
has body: I'm trying to emulate the copy/paste functionality of my OS using a python application. What I want to have happen is that when I press the keys, say, "Alt-X", it would paste predefined text into the currently occupied text field. Basically copy and paste but creating my own. I've tried using pyautogui and other frameworks but I can't seem to figure out how get it to wait for key-press in the background, and then enter the text after that. Any ideas? Thanks.
downvote count: 0
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48916500
has comment: http://stackoverflow.com/comment/84838266
has comment: http://stackoverflow.com/comment/84838177
tagged with: python
has comment: http://stackoverflow.com/comment/84838163
has comment: http://stackoverflow.com/comment/84838123
tagged with: text
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84838231
accepted answer: http://stackoverflow.com/a/48916500
type: Question
tagged with: copy-paste
upvote count: 5
has title: Creating a hotkey to enter text using python, running in background waiting for key-press
score: 5
has comment: http://stackoverflow.com/comment/84838195

http://stackoverflow.com/comment/84882989
type: QuestionComment
type: Comment
score: 4
comment on: http://stackoverflow.com/q/48938024
has text: `return` returns from a function - you cannot execute multiple of them in a row

http://stackoverflow.com/comment/84658816
comment on: http://stackoverflow.com/q/48827412
score: 0
type: Comment
type: QuestionComment
has text: Where do you define `treat_ticket_callback` in your test code? It's not imported. What is the purpose of the `celery_app` fixture? Maybe it intefers with the celery_worker? There's also a `celery_app` provided by the pytest celery plugin. I would avoid defining your own fixture with the same name.

http://stackoverflow.com/q/48899022
downvote count: 0
tagged with: sublimetext3
favorite count: 0
has answer: http://stackoverflow.com/a/48901073
linked to: http://stackoverflow.com/q/21290224
tagged with: python
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/21115295
upvote count: 1
type: Question
has title: Error in SublimeREPL to debug python
has body: OS:Windows 10 software：Sublime Text 3 I am running Python with SublimeREPL and it return me the error as following: error: FileNotFoundError(2, 'The system cannot find the file specified.', None, 2) I have followed the steps SublimeREPL Unable to Find R there is another error: reloading settings Packages/User/SublimeREPL.sublime-settings error: Error trying to parse settings: Invalid escape in Packages\User\SublimeREPL.sublime-settings:2:32 how can I solve it and finally to finish setting up the packages????
accepted answer: http://stackoverflow.com/a/48901073
answer count: 1
tagged with: sublimerepl

http://stackoverflow.com/q/48821218
has title: tf.image.random_brightness giving negative values randomly in TensorFlow
has answer: http://stackoverflow.com/a/50775448
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/84646768
has comment: http://stackoverflow.com/comment/84724576
answer count: 1
downvote count: 0
favorite count: 0
has body: 'I am trying image data augmentation in TensorFlow using various methods like rotation, random brightness, random saturation. What I observe that the output of tf.image.random_brightness is not consistent - sometimes it produces negative values. I understand the randomness, but is it correct to produce negative values? When I try to plot the image using matplotlib.pyplot, it fails saying ValueError: Floating point image RGB values must be in the 0..1 range Below is some sample of the code:' # Function which reads file and converts to image array def read_images_from_file (input_queue): label = input_queue[1] file_content = tf.read_file(input_queue[0]) image = tf.image.decode_jpeg(file_content, channels=NUM_CHANNELS) image = tf.image.convert_image_dtype(image, dtype=tf.float32, saturate=True) image = tf.image.resize_images(image, [IMAGE_HEIGHT, IMAGE_WIDTH]) ..... #inside a function which applies various augmentations - code shown only for brightness X_init = tf.placeholder(tf.float32, shape=images.shape) X = tf.Variable(X_init) sess.run(tf.variables_initializer([X]), feed_dict={X_init: images}) aug_images, aug_labels = (sess.run(tf.map_fn(lambda params: (tf.image.random_brightness(params[0], 0.8, 1), params[1]), (X, labels)))) #inside a loop after calling above function - output of function is returned to aug_train_images print (aug_train_images[i]) 'Some sample output:' [[[-0.18852733 -0.27872342 -0.31009597] [-0.18059228 -0.2786315 -0.3060825 ] [-0.1765788 -0.27461803 -0.302069 ] ... [-0.20366213 -0.19974056 -0.18405429] [-0.22792684 -0.22437292 -0.20458125] [-0.24324547 -0.23166458 -0.21205674]] 'I am using Jupyter notebook with Python 3.5.3 and TensorFlow CPU version 1.5.0-rc0 on Ubuntu 16.10.'
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84755247
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/84645848
score: 6

http://stackoverflow.com/a/48944829
score: 0
answers question: http://stackoverflow.com/q/48860112
has body: Instead of using curdoc() go with components() function which resides in bokeh.embed and then make it live using ajax. `def bokeh(request): window_size = 100 window = np.ones(window_size) / float(window_size) #data_avg = np.convolve(data, window, 'same') TOOLS = "resize,pan,wheel_zoom,box_zoom,reset,save" p2 = figure(x_axis_type="datetime", title="abc", plot_width=1000) p2.grid.grid_line_alpha = 0 p2.xaxis.axis_label = 'Date' p2.yaxis.axis_label = 'Price' p2.ygrid.band_fill_color = "olive" p2.ygrid.band_fill_alpha = 0.1 p2.line(data_dates, data, legend='close', color='navy') # p2.line(data_dates, data2, legend='SMA-15', color='green') #p2.line(data_dates, data_avg, legend='avg', color='navy') p2.legend.location = "top_left" script, div = components(p2) return render_to_response( 'bindex.html', {'script' : script , 'div' : div} )` Ajax: Html: {% load staticfiles %} <! DOCTYPE html> {% csrf_token %}
type: Answer
has comment: http://stackoverflow.com/comment/84896326

http://stackoverflow.com/comment/84737411
has text: You can download packages as wheel files (`.whl`) then [install them locally](https://stackoverflow.com/questions/27885397/how-do-i-install-a-python-package-with-a-whl-file). I would also suggest to your IT that they whitelist the package server (https://pypi.python.org/pypi) so you can use the normal workflow.
comment on: http://stackoverflow.com/q/48867129
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48928026
possible better answer: http://stackoverflow.com/a/48928335
has comment: http://stackoverflow.com/comment/84863465
has answer: http://stackoverflow.com/a/48928335
has answer: http://stackoverflow.com/a/48928404
upvote count: 2
has comment: http://stackoverflow.com/comment/84863556
tagged with: pandas
has answer: http://stackoverflow.com/a/48928398
tagged with: nan
accepted answer: http://stackoverflow.com/a/48928288
favorite count: 0
answer count: 5
has answer: http://stackoverflow.com/a/48928390
has title: How to remove row containing array of NaN?
tagged with: python
has answer: http://stackoverflow.com/a/48928288
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84862450
type: Question
has comment: http://stackoverflow.com/comment/84863052
linked to: http://stackoverflow.com/q/7368789
has body: I have a df like this: num1 num2 0 [2.0] 10 1 [3.0] 20 2 [4.0] 30 3 [5.0] 40 4 [6.0] 50 5 [nan] 60 6 [nan] 70 7 [10.0] 80 8 [nan] 90 9 [15.0] 100 num1 column contains arrays of floats. [nan] is a numpy array containing a single np.NaN. I am converting this to integers via this: df['num1'] = list(map(int, df['num1'])) If I just use this df: num1 num2 0 [2.0] 10 1 [3.0] 20 2 [4.0] 30 3 [5.0] 40 4 [6.0] 50 This works when there are no [nan] and I get: num1 num2 0 2.0 10 1 3.0 20 2 4.0 30 3 5.0 40 4 6.0 50 But if I include the full df with [nan] I get the error: `ValueError: cannot convert float NaN to integer` I tried doing: df[df['num1'] != np.array(np.NaN)] But this gave the error: TypeError: len() of unsigned object How can I get the desired output: num1 num2 0 2.0 10 1 3.0 20 2 4.0 30 3 5.0 40 4 6.0 50 5 10.0 80 6 15.0 100

http://stackoverflow.com/a/48933137
downvote count: 0
type: Answer
score: 6
upvote count: 6
has body: since result of get_absolute_url is url string you dont need {% url %} in template to use it. Just replace it with: {{ cert.name }}
answers question: http://stackoverflow.com/q/48933069
has comment: http://stackoverflow.com/comment/84873074
accepted answer of: http://stackoverflow.com/q/48933069
type: AcceptedAnswer

http://stackoverflow.com/comment/84855927
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48924292
has text: Yep that was it, thanks for your help!

http://stackoverflow.com/q/48916479
tagged with: jenkins
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84839688
downvote count: 1
has comment: http://stackoverflow.com/comment/84839857
type: Question
has comment: http://stackoverflow.com/comment/84878922
has body: I have simple Python code inside a GitHub repo: print "hello world" How to create a Jenkins build to run this Python code directly from a GitHub?
has title: How to run a Jenkins build based Python code from GitHub?
score: 0
tagged with: github
favorite count: 0
has comment: http://stackoverflow.com/comment/84839919
answer count: 0

http://stackoverflow.com/comment/135014848
score: 0
type: Comment
has text: Binary is 0 or 1. You only need one node to represent 0 or 1
comment on: http://stackoverflow.com/a/71170687
type: AnswerComment

http://stackoverflow.com/comment/84916360
type: AnswerComment
has text: @ely thanks, I just tried that and got back "ValueError: need more than 1 value to unpack"
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48953392

http://stackoverflow.com/q/48820860
type: Question
has title: How to scraping the html text using selenium python
accepted answer: http://stackoverflow.com/a/48821027
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48822043
has answer: http://stackoverflow.com/a/48822043
has comment: http://stackoverflow.com/comment/84645391
has body: I'm trying to get text "General (8)" shown in below HTML code using selenium webdriver but kept running into issues. Any input is highly appreciated. Thanks. my code: test1 = driver.find_element_by_xpath("//input[@id = 'General'][@role = 'presentation']").text print(test1) returns null HTML: General (8)
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48821027
tagged with: selenium

pyqt
type: Tag
tags question: http://stackoverflow.com/q/48914098
tags question: http://stackoverflow.com/q/48827148
tags question: http://stackoverflow.com/q/48812195
tags question: http://stackoverflow.com/q/48861546
tags question: http://stackoverflow.com/q/48928640
tags question: http://stackoverflow.com/q/48913924
tags question: http://stackoverflow.com/q/48857367
tags question: http://stackoverflow.com/q/48862090
tags question: http://stackoverflow.com/q/48806594
tags question: http://stackoverflow.com/q/48832526
tags question: http://stackoverflow.com/q/48805590
tags question: http://stackoverflow.com/q/48907552
tags question: http://stackoverflow.com/q/48816961
tags question: http://stackoverflow.com/q/48850468
tags question: http://stackoverflow.com/q/48925555
tags question: http://stackoverflow.com/q/48807660
tags question: http://stackoverflow.com/q/48889154
tags question: http://stackoverflow.com/q/48847593
tags question: http://stackoverflow.com/q/48808940
tags question: http://stackoverflow.com/q/48845079
tags question: http://stackoverflow.com/q/48919092
tags question: http://stackoverflow.com/q/48892375
tags question: http://stackoverflow.com/q/48839658
tags question: http://stackoverflow.com/q/48885400
tags question: http://stackoverflow.com/q/48928080
tags question: http://stackoverflow.com/q/48901289
tags question: http://stackoverflow.com/q/48936548
tags question: http://stackoverflow.com/q/48883443
tags question: http://stackoverflow.com/q/48933553
tags question: http://stackoverflow.com/q/48846219
tags question: http://stackoverflow.com/q/48819694
tags question: http://stackoverflow.com/q/48935921
tags question: http://stackoverflow.com/q/48901854
tags question: http://stackoverflow.com/q/48860153
tags question: http://stackoverflow.com/q/48932612
tags question: http://stackoverflow.com/q/48830351
tags question: http://stackoverflow.com/q/48872430
tags question: http://stackoverflow.com/q/48915001
tags question: http://stackoverflow.com/q/48854020
tags question: http://stackoverflow.com/q/48876551
tags question: http://stackoverflow.com/q/48890003
tags question: http://stackoverflow.com/q/48824070
tags question: http://stackoverflow.com/q/48901369
tags question: http://stackoverflow.com/q/48908534
tag name: pyqt
tags question: http://stackoverflow.com/q/48864655
tags question: http://stackoverflow.com/q/48806568
tags question: http://stackoverflow.com/q/48839332
tags question: http://stackoverflow.com/q/48887163
tags question: http://stackoverflow.com/q/48873483
tags question: http://stackoverflow.com/q/48835586
tags question: http://stackoverflow.com/q/48962932

http://stackoverflow.com/comment/88653084
type: QuestionComment
has text: this appears to be resolved as per issue located here: https://github.com/conda/conda/issues/1329 , docs here: https://conda.io/docs/user-guide/configuration/admin-multi-user-install.html
comment on: http://stackoverflow.com/q/48871289
score: 0
type: Comment

http://stackoverflow.com/q/48918574
answer count: 1
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I answered my own question below. Sorry for wasting anyone's time. I created a custom password validator called 'NoUsername' which I put in the settings file under the 'AUTH_PASSWORD_VALIDATORS'. If I'm using validate_password() to validate the password the user entered, how do I exclude my custom 'NoUsername'? Thanks. https://docs.djangoproject.com/en/2.0/topics/auth/passwords/#django.contrib.auth.password_validation.validate_password The reason is because I want to use 'NoUserName' for registering but not for changing passwords.
has answer: http://stackoverflow.com/a/48918968
type: Question
has title: how to exclude a password validator
score: 0

http://stackoverflow.com/comment/84816386
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48903372
type: Comment
has text: could you please tell me, better way to activate the environment. instead of os.popen('/bin/bash --rcfile %s'%(venv_dir+'/bin/activate'))

http://stackoverflow.com/comment/84679089
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48837077
has text: Second one works but imports all the table in the app. First one doesn't work. I have create model as `class novel(models.Model):` and then run the first two command in shell.
type: AnswerComment

http://stackoverflow.com/q/48866592
has title: Heatmap on x-y plane with z as weighting
tagged with: plot
has answer: http://stackoverflow.com/a/48866725
type: AnsweredQuestion
score: 3
has body: I've gone through tens of answers regarding heatmaps on this forum but I am still running into problems, so I thought I'd ask myself. Bare in mind that until a month ago I had no idea what Python was. So, I have a large file of data in three columns. The first two are standard x-y coordinates. For each point, there is a third variable, z, that I want to use as weighting to build some sort of heatmap. I have seen several methods, e.g. using meshgrid or changing array size, but what I think the problem is is that my array is not regular or rectangular. It's just a mess of random points in the x-y plane, not evenly spaced with each other, each with a z value. Here is just a small snippet of the data I have in my spreadsheet: x y z 392 616 0.5 416 614 1 497 603 3 533 598 3.5 383 589 0.5 574 574 4 ... I tried several methods, e.g. reshaping the arrays, but I always get some kind of error. How can I plot this data as a heatmap with the weighting of each point given by z? Thank you. I'm aware that, since the data points are not regularly spaced out, there might be gaps where the heatmap would be zero, but I can sort those out later by extrapolating their weighting via a method I figured out, so that wouldn't be a problem. The closest I got to getting the graph I'm looking for is using this code: plt.hist2d(x, y, bins=8, weights=z, cmap="Greys") plt.colorbar() However, the problem with this is that, if there is more than one point in a given "bin", it computes the "aggregate" weighting -- e.g. if in a particular bin there are two data points with weightings of 1 and 2.5, respectively, the bin will be coloured as if its weighting was 1+2.5=3.5. Is there any way I can get it to display the colour corresponding to the weighting of the data point closest to the bin center? e.g. if the data point with weighting 2.5 was really close to the bin center while the one with weighting 1 was along one of the bin's edges, is there a way I can get the bin to have weighting 2.5? Thank you …
accepted answer: http://stackoverflow.com/a/48866725
type: Question
tagged with: numpy
tagged with: contour
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: heatmap
upvote count: 3

http://stackoverflow.com/comment/84884440
type: QuestionComment
has text: The label "text file" makes me think at "undefined size" this might hit some "max request size" limit, maybe you should try using POST instead of GET, but beside that ... what exactly is it that is not working ? What errors/problems have you encountered ?
comment on: http://stackoverflow.com/q/48938316
score: 0
type: Comment

http://stackoverflow.com/q/48860112
upvote count: 2
has comment: http://stackoverflow.com/comment/84723857
tagged with: django
has answer: http://stackoverflow.com/a/51296755
type: Question
has body: I am trying to implement bokeh live chart in django. I got some reference in one website. They used add_periodic_callbackfunction in curdoc() to refresh the chart. This is working fine by running bokeh serve filename.py. I tried this in django by using this code in my view.py def bokeh(request): import numpy as np from bokeh.layouts import column from bokeh.models import Button from bokeh.palettes import RdYlBu3 from bokeh.plotting import figure, curdoc import pandas as pd # create a plot and style its properties p = figure(x_axis_type="datetime", title="EUR USD", plot_width=1000) p.grid.grid_line_alpha = 0 p.xaxis.axis_label = 'Date' p.yaxis.axis_label = 'Price' p.ygrid.band_fill_color = "olive" p.ygrid.band_fill_alpha = 0.1 # add a text renderer to out plot (no data yet) r = p.line(x = [], y = [], legend='close', color='navy') i = 0 ds = r.data_source # create a callback that will add a number in a random location def callback(): global i a = fxdata()[0] ## this script will return EURUSD forex data as list ds.data['x'].append(np.datetime64(str(a[1]))) ds.data['y'].append(np.float(a[2])) ds.trigger('data', ds.data, ds.data) i = i + 1 # add a button widget and configure with the call back button = Button(label="Press Me") # button.on_click(callback) # put the button and plot in a layout and add to the document curdoc().add_root(column(button, p)) curdoc().add_periodic_callback(callback, 1000) script, div = components(curdoc()) return render_to_response( 'bokeh/index.html', {'script' : script , 'div' : div} ) when I try this code i'm getting empty bokeh chart frame as output. can we do this by using add_periodic_callbackfunction in Django? or any other similar way to refresh the chart. can anyone please help me. if you feel its not understandable please comment here. your help will be appreciated . Thanks in advance.
linked to: http://stackoverflow.com/q/36828483
tagged with: bokeh
has title: how to use bokeh add_periodic_callback function in Django
answer count: 2
has comment: http://stackoverflow.com/comment/84725063
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48944829
type: UnansweredQuestion
tagged with: python
score: 2

http://stackoverflow.com/comment/84665908
score: 0
type: Comment
has text: I thought that he wanted last five items _and_ all items such that `is_home=True`.
type: AnswerComment
comment on: http://stackoverflow.com/a/48830925

http://stackoverflow.com/comment/84889706
comment on: http://stackoverflow.com/a/48941181
score: 0
type: Comment
has text: Thank you for your help. No luck after I tried to remove the ' " ', and even tried to print one item, still receive an empty email..
type: AnswerComment

http://stackoverflow.com/a/48814321
has body: The easiest way is to loop over the list and use a dictionary to store your counts. files_list = ['pic1.jpg', 'pic2.jpg', 'pic3.jpg', 'movie1.mov', 'movie2.mov', 'doc1.pdf', 'doc2.pdf', 'doc3.pdf', 'doc4.pdf'] counts = {} for f in f: ext = f[-3:] if ext not in counts: counts[ext] = 0 counts[ext] += 1 print counts #{'pdf': 4, 'mov': 2, 'jpg': 3} No doubt, there are other fancy solutions, but I think this is easier to understand. If you can't assume that extension will always be 3 characters, then you can change the ext = line to: ext = f.split(".")[-1] As other posters have shown in their answers.
has comment: http://stackoverflow.com/comment/84632373
upvote count: 1
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84632308
score: 1
answers question: http://stackoverflow.com/q/48814286

http://stackoverflow.com/comment/84839948
type: AnswerComment
has text: @ScottBoston oh yes i see that. oops.
comment on: http://stackoverflow.com/a/48916339
type: Comment
score: 0

http://stackoverflow.com/q/48958961
has body: I am learning Object-oriented programming through python. I am trying to write a program to write three special methods for a Fraction class that overload operators to perform rich comparisons between a and b. (a &lt; b, a >b, a==b). A sample would be: &gt;&gt;&gt;a = Fraction(1, 2) &gt;&gt;&gt;b = Fraction(1, 3) &gt;&gt;&gt;a==b False &gt;&gt;&gt;a &gt; b True &gt;&gt;&gt;a &lt; b False &gt;&gt;&gt;a = Fraction(4, 8) &gt;&gt;&gt;b = Fraction(2, 4) &gt;&gt;&gt;a ==b True &gt;&gt;&gt;a &gt; b False &gt;&gt;&gt;a &lt; b False I really do not understand what it is asking to do. Any help on what to do to help get me started would be great. Thank you.
tagged with: overloading
downvote count: 0
score: 1
type: Question
has answer: http://stackoverflow.com/a/65354759
answer count: 2
has comment: http://stackoverflow.com/comment/84924980
has answer: http://stackoverflow.com/a/48959234
linked to: http://stackoverflow.com/q/2400635
tagged with: class
linked to: http://stackoverflow.com/q/15461574
has title: Python object oriented programming. Writing program to perform rich comparisons
has comment: http://stackoverflow.com/comment/84924668
upvote count: 1
has comment: http://stackoverflow.com/comment/84924975
favorite count: 0
has comment: http://stackoverflow.com/comment/84924671
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84924699
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84924808

http://stackoverflow.com/a/48955764
score: 2
has comment: http://stackoverflow.com/comment/85415953
has comment: http://stackoverflow.com/comment/85050733
has body: Try to understand the attached lines of python code and adjust them to your needs. It's not my code but I wrote a similar piece to test my models. The source is: https://www.cc.gatech.edu/~zk15/deep_learning/classify_test.py If you don't want to fine-tune a pre-trained model, it's obvious that you don't need a solver. The solver is what optimizes the model. If you want to predict the class probability for an image, you actually just have to do a forward pass. Keep in mind that your deploy.prototxt must have a proper last layer which uses either a softmax or sigmoid function (depending on the architecture). You can't use the loss function from the train_val.prototxt for this. import numpy as np import matplotlib.pyplot as plt # Make sure that caffe is on the python path: caffe_root = '../' # this file is expected to be in {caffe_root}/examples import sys sys.path.insert(0, caffe_root + 'python') import caffe # Set the right path to your model definition file, pretrained model weights, # and the image you would like to classify. MODEL_FILE = '../models/bvlc_reference_caffenet/deploy.prototxt' PRETRAINED = '../models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel' IMAGE_FILE = 'images/cat.jpg' caffe.set_mode_cpu() net = caffe.Classifier(MODEL_FILE, PRETRAINED, mean=np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy').mean(1).mean(1), channel_swap=(2,1,0), raw_scale=255, image_dims=(256, 256)) input_image = caffe.io.load_image(IMAGE_FILE) plt.imshow(input_image) prediction = net.predict([input_image]) # predict takes any number of images, and formats them for the Caffe net automatically print 'prediction shape:', prediction[0].shape plt.plot(prediction[0]) print 'predicted class:', prediction[0].argmax() plt.show()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84978144
downvote count: 0
has comment: http://stackoverflow.com/comment/85284411
accepted answer of: http://stackoverflow.com/q/48946706
answers question: http://stackoverflow.com/q/48946706
upvote count: 2
type: Answer

http://stackoverflow.com/q/48857584
possible better answer: http://stackoverflow.com/a/48857732
downvote count: 0
score: 1
type: Question
upvote count: 1
has answer: http://stackoverflow.com/a/48857741
favorite count: 0
tagged with: class
has answer: http://stackoverflow.com/a/48857732
has body: I want to define a class that has as super the pd.DataFrame object as follows: import pandas as pd class my_data_frame(pd.DataFrame): def __init__(self, index, columns): super(my_data_frame,self).__init__(index = index, columns = columns) self = self.fillna(0) print('init',self) df = my_data_frame([1,2,3],['a','b','c']) print('first', df) This will print the output init a b c 1 0 0 0 2 0 0 0 3 0 0 0 first a b c 1 NaN NaN NaN 2 NaN NaN NaN 3 NaN NaN NaN So the question is why does the fillna function on line 5 doesn't really work. Since printing it from the init function seems to work, but in the command line it doesn't.
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/84720473
has title: Using pandas fillna in the init function of a class python
tagged with: python
has answer: http://stackoverflow.com/a/48858556
accepted answer: http://stackoverflow.com/a/48858556
type: AnsweredQuestion

http://stackoverflow.com/comment/84925951
type: Comment
type: QuestionComment
has text: so in general you want the minimum element to always appear last? but everything else is ascending?
score: 0
comment on: http://stackoverflow.com/q/48959662

http://stackoverflow.com/q/48915073
score: -1
has comment: http://stackoverflow.com/comment/84837434
has answer: http://stackoverflow.com/a/49030391
answer count: 2
has title: Extended ping on Cisco Device
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48916402
type: UnansweredQuestion
tagged with: python
upvote count: 0
has body: I'm newbie in Python. I try make a script to perform automatic "extended ping". The manual cisco flow is: switch#**ping** Protocol [ip]: Target IP address: **X.X.X.X** Repeat count [5]: **1000** Datagram size [100]: **1500** Timeout in seconds [2]: Extended commands [n]: Sweep range of sizes [n]: ####################Command Start#################### I try to use the command: "net_connect.send_command" from Netmiko and doesn't work. Ping_Extended = [ 'ping','\n','X.X.X.X','1000','1500','\n','\n','\n' ] Ping_TASA = net_connect.send_command(Ping_Extended) Error: Traceback (most recent call last): File "VLAN1.py", line 124, in &lt;module&gt; Ping_Extended = Ping_Extended.rstrip() AttributeError: 'list' object has no attribute 'rstrip' can Someone help me?. if another method exist please shared me. Thanks a lot!
type: Question
tagged with: cisco

http://stackoverflow.com/comment/85107528
comment on: http://stackoverflow.com/q/48863201
score: 0
type: Comment
has text: The security issue can be in the clean method, which can be used to modify other fields or perform operations not directly related to the database, like generating some files. Its simpler doing this kind of operations just before data is saved (with `clean()`) than after its saved in the database. And again, it breaks the trust, uncleaned data should **never** be on the cleaned data array.
type: QuestionComment

http://stackoverflow.com/a/48936856
answers question: http://stackoverflow.com/q/48935712
downvote count: 0
type: Answer
upvote count: 1
has body: I think the code below captures what you are asking. Here I simulate two scripts running independently (by using threads), then show how you can use shelve to communicate between them. Note, there are likely much better ways to get to what you are after -- but if you absolutely must run the scripts independently, this will work for you. Incidentally, any persistent source would do (such as a database). import shelve import time import threading def script1(): while True: with shelve.open('my_store') as holder3: if holder3['flag'] is not None: break print('waiting') time.sleep(1) print("Done") def script2(): print("writing") with shelve.open('my_store') as holder2: holder2['flag'] = 1 if __name__ == "__main__": with shelve.open('my_store') as holder1: holder1['flag'] = None t = threading.Thread(target=script1) t.start() time.sleep(5) script2() t.join() Yields: waiting waiting waiting waiting waiting writing Done
score: 1

http://stackoverflow.com/a/48944048
type: Answer
has comment: http://stackoverflow.com/comment/84909902
accepted answer of: http://stackoverflow.com/q/48938552
has body: You can create a dictionary for each company and then append it to the list. # Get the &lt;ul&gt; tag which contains all the companies. results = soup.find('div', class_='marketing-directories-results').ul companies_info = [] # Iterate over the companies (all &lt;li&gt; tags that are direct children of results, # can be found by setting 'recursive=False'). for company in results.find_all('li', recursive=False): company_info = {} company_info['Name'] = company.find('h2').text.strip() company_info['Address'] = company.find('address').get_text(', ', strip=True) company_info['Website'] = company.find('a', href=True)['href'] try: li = company.find('ul', class_='result-info').find('li') if li.strong.text.strip() == 'Accepts Business From:': company_info['Accepts Business From'] = li.find('li').text.strip() except AttributeError: # If this error is caught, it means this info is not available. # You can use the below line to set it to 'None', or simply use 'pass' to do nothing. company_info['Accepts Business From'] = None companies_info.append(company_info) print(companies_info) Output: [ { 'Name': 'A I I Insurance Brokerage of Massachusetts Inc', 'Address': '183 Davis St, East Douglas, Massachusetts, U S A, MA 01516-113', 'Website': 'http://www.agencyint.com', 'Accepts Business From': 'U.S.A' }, { 'Name': 'ABCO Insurance Underwriters Inc', 'Address': 'ABCO Building, 350 Sevilla Avenue, Suite 201, Coral Gables, Florida, U S A, 33134', 'Website': 'http://www.abcoins.com', 'Accepts Business From': 'U.S.A' }, { 'Name': 'Acadian Managers, LLC', 'Address': '8550 United Plaza Boulevard, Suite 702, Baton Rouge, Louisiana, U.S.A, 70809', 'Website': 'http://www.acadianmanagers.com', 'Accepts Business From': None } ]
has comment: http://stackoverflow.com/comment/85042079
answers question: http://stackoverflow.com/q/48938552
has comment: http://stackoverflow.com/comment/84909698
has comment: http://stackoverflow.com/comment/85050087
has comment: http://stackoverflow.com/comment/85039252
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84909552

http://stackoverflow.com/comment/84671908
comment on: http://stackoverflow.com/a/48832225
has text: @DeepSpace Maybe he is "purist" or he is coming from a C or Assembly background.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48958725
tagged with: python-requests
type: Question
possible better answer: http://stackoverflow.com/a/48958885
has title: how BeautifulSoup get the content inside a span?
score: 0
answer count: 2
has body: I'm trying to parse fixture contents from a website I managed to parse Match column but facing difficulty in parsing date and time column. My program import re import pytz import requests import datetime from bs4 import BeautifulSoup from espncricinfo.exceptions import MatchNotFoundError, NoScorecardError from espncricinfo.match import Match bigbash_article_link = "http://www.espncricinfo.com/ci/content/series/1128817.html?template=fixtures" r = requests.get(bigbash_article_link) bigbash_article_html = r.text soup = BeautifulSoup(bigbash_article_html, "html.parser") bigbash1_items = soup.find_all("span",{"class": "fixture_date"}) bigbash_items = soup.find_all("span",{"class": "play_team"}) bigbash_article_dict = {} date_dict = {} for div in bigbash_items: a = div.find('a')['href'] bigbash_article_dict[div.find('a').string] = a print(bigbash_article_dict) for div in bigbash1_items: a = div.find('span').string date_dict[div.find('span').string] = a print(date_dict) When I execute this I get print(bigbash_article_dict) output, but print(date_dict) gives me error, how can I parse date and time content?
tagged with: parsing
tagged with: beautifulsoup
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48958870
accepted answer: http://stackoverflow.com/a/48958870
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48958885

http://stackoverflow.com/q/48864631
has comment: http://stackoverflow.com/comment/84742758
upvote count: 11
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84741391
has answer: http://stackoverflow.com/a/48868811
tagged with: cython
has title: What are the differences between a cpdef and a cdef wrapped in a def?
score: 11
has body: In the Cython docs there is an example where they give two ways of writing a C/Python hybrid method. An explicit one with a cdef for fast C access and a wrapper def for access from Python: cdef class Rectangle: cdef int x0, y0 cdef int x1, y1 def __init__(self, int x0, int y0, int x1, int y1): self.x0 = x0; self.y0 = y0; self.x1 = x1; self.y1 = y1 cdef int _area(self): cdef int area area = (self.x1 - self.x0) * (self.y1 - self.y0) if area &lt; 0: area = -area return area def area(self): return self._area() And one using cpdef: cdef class Rectangle: cdef int x0, y0 cdef int x1, y1 def __init__(self, int x0, int y0, int x1, int y1): self.x0 = x0; self.y0 = y0; self.x1 = x1; self.y1 = y1 cpdef int area(self): cdef int area area = (self.x1 - self.x0) * (self.y1 - self.y0) if area &lt; 0: area = -area return area I was wondering what the differences are in practical terms. For example, is either method faster/slower when called from C/Python? Also, when subclassing/overriding does cpdef offer anything that the other method lacks?
has answer: http://stackoverflow.com/a/48879057
has comment: http://stackoverflow.com/comment/84742179
type: Question
possible better answer: http://stackoverflow.com/a/48868811
answer count: 2
accepted answer: http://stackoverflow.com/a/48879057
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84741946
tagged with: python

http://stackoverflow.com/comment/84615013
comment on: http://stackoverflow.com/a/48806039
type: Comment
score: 0
type: AnswerComment
has text: I am wondering : how are you supposed to know these informations like "some sites do this, other this". Do you just learn these conventions by experience or is there an official site where it is documented ?

http://stackoverflow.com/q/48810910
upvote count: 1
answer count: 1
has body: My xaxis is formed out of a range (0,100). Instead of showing the numbers I would like to show a text, like "item1" every let's say 20 ticks. So instead of the first 20 ticks it should be "item1", instead of the following 20 - "item2" etc. x=range(0,100) y=[5 for i in x] p = figure() p.circle(x=x, y=y) show(p) What I would like is instead of 0,20,40 etc. to have the items of a list: categorical=["item1","item2","item3","item4","item5"] and do not show the numbers at all. I've tried with p = figure(x_range=categorical) but then not all the dots appear - only 1 per category appears. I've also tried with factors: factors = [("item1", 1), ("item1", 2) ....("item2", 21)... ] x_range = FactorRange(*factors) But then all the numbers appear and it ends up with something like this if you have more than 1000 numbers:
favorite count: 0
type: UnansweredQuestion
has title: Categorical xaxis without showing the numbers in bokeh
tagged with: python
downvote count: 0
score: 1
tagged with: bokeh
type: Question
has answer: http://stackoverflow.com/a/48828333

http://stackoverflow.com/a/73466583
score: 0
answers question: http://stackoverflow.com/q/48873751
type: Answer
has body: Define an Aggregate class from django.db.models import Aggregate class RawColumn(Aggregate): function = '' template = '%(function)s%(expressions)s' def __init__(self, expressions, **extra): super(RawColumn, self).__init__(expressions, **extra) post_list.values('website_id').annotate(Count('website_id'),RawColumn('id'),RawColumn('title'))

http://stackoverflow.com/q/48929508
has answer: http://stackoverflow.com/a/48930384
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84868798
tagged with: python
has answer: http://stackoverflow.com/a/48934291
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48929666
has comment: http://stackoverflow.com/comment/84865631
has comment: http://stackoverflow.com/comment/84874291
has comment: http://stackoverflow.com/comment/84865699
has title: numpy pad a sequence instead of constant values
has comment: http://stackoverflow.com/comment/84866865
has body: I am trying to pad a numpy array with a sequence [0, 1] along each row. So for example if I have an array as: x = np.random.rand(2, 4) array([[0.51352468, 0.4274193 , 0.11244252, 0.56787658], [0.37855923, 0.80976327, 0.0290558 , 0.87585656]]) After the padding operation, it becomes: array([[0.51352468, 0.4274193 , 0.11244252, 0.56787658], [0.37855923, 0.80976327, 0.0290558 , 0.87585656], [0. , 0. , 0. , 0. ], [1. , 1. , 1. , 1. ]]) Currently, the way I am doing this is: padded = np.asarray(x) padded = np.pad(padded, [(0, 4 - len(padded.shape[0])), (0, 0)], 'constant') padded[:, -1] = 1.0 This seems a bit cumbersome as I pad with zeros and then set the last row to 1. I was wondering if there is a way to do this with just one numpy.pad call? EDIT As you can see from the code above, the function will convert the input to a 4 dimensional object (the input dimension of the array is either 2 or 3 i.e. len(x) == 2 or 3). So, if the input is 2 dimensional, it will add two rows of zeros and then set the last one to 1. if the input is 3 dimensional, it will add a row of zeros and then overwrite to a row of ones.
type: Question
tagged with: numpy
downvote count: 0
has comment: http://stackoverflow.com/comment/84866905
accepted answer: http://stackoverflow.com/a/48929666
possible better answer: http://stackoverflow.com/a/48930384
answer count: 3

http://stackoverflow.com/q/48924045
has answer: http://stackoverflow.com/a/48932017
has comment: http://stackoverflow.com/comment/84855880
tagged with: iso
tagged with: smartcard
has comment: http://stackoverflow.com/comment/84869737
tagged with: pyscard
tagged with: python
has comment: http://stackoverflow.com/comment/84859304
accepted answer: http://stackoverflow.com/a/48932017
has body: I'm trying to figure out the file hierarchy within a contact smart card using pyScard and ISO 7816 commands. The first thing I do is selecting the master file (INS = 0xA4) using connection.execute([0x0, 0xA4, 0x0, 0x0, 0x0]) This returns ([ ], 0x61, 0x19) which means I have to run a GET_RESPONSE (INS = 0xC0) command in order to get the answer. To do so I run connection.execute([0x0, 0xC0, 0x0, 0x0, 0x19]) which returns a set of bytes (besides the 0x90 00). If I understand it correctly, by running the SELECT FILE I've selected the master file but I don't seem to find an interpretation for those bytes that I receive with GET RESPONSE, what does that mean? How do you interpretate them? Thanks!! :)
type: Question
has comment: http://stackoverflow.com/comment/84870646
has title: PyScard - What is the interpretation of the data obtained after executing GET RESPONSE?
type: AnsweredQuestion
score: 0
answer count: 1

http://stackoverflow.com/a/48921410
has body: You are not saving the result. for i, x in enumerate(D1_inv): D1_inv[i] = round(x, 4)
answers question: http://stackoverflow.com/q/48921374
type: Answer
has comment: http://stackoverflow.com/comment/84854019
has comment: http://stackoverflow.com/comment/84853724
score: 0

http://stackoverflow.com/a/48887403
upvote count: 7
has body: What you see are the ticklabels, which have size 0. Even zero sized ticks appear as a single dot because of antigraining. You probably want to set the label off completely ax.xaxis.set_tick_params(length=0,labelbottom=False) You find out about this by looking at the available arguments in the documentation.
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48887134
answers question: http://stackoverflow.com/q/48887134
score: 7

http://stackoverflow.com/q/48836549
upvote count: 1
favorite count: 0
tagged with: datetime
possible better answer: http://stackoverflow.com/a/48837142
tagged with: python
has comment: http://stackoverflow.com/comment/84678948
accepted answer: http://stackoverflow.com/a/48845903
has title: Filtering queryset by next 30 days and date passed
downvote count: 0
tagged with: django
has answer: http://stackoverflow.com/a/48845903
type: AnsweredQuestion
has body: I'm not sure if It's due to lack of sleep, but I cannot for the life of me figure out what's causing this issue. AttributeError: 'datetime.date' object has no attribute 'utcoffset' I'm trying to filter a queryset based on two conditions. If the date has already passed. If the date is within the next 30 days. Model class Member(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, blank=True, null=True) ... membership_expiry = models.DateField(null=True, blank=True) club_membership_expiry = models.DateField(null=True, blank=True) medical_expiry = models.DateField(null=True, blank=True) View get_context_data override def get_context_data(self, **kwargs): context = super(MembershipReport, self).get_context_data(**kwargs) members = Member.objects.all() now = date.today() thirty_days = now + timedelta(days=30) context['membership_overdue'] = members.filter(Q(membership_expiry__lte=now) | Q(membership_expiry__gte=now, membership_expiry__lte=thirty_days)) return context I've tried using date.today() datetime.now() and django's timezone.now() all three throw the same error.
score: 1
has answer: http://stackoverflow.com/a/48837142
type: Question
answer count: 2

http://stackoverflow.com/comment/84901890
type: Comment
score: 1
type: QuestionComment
has text: How about looking python regex module reference?
comment on: http://stackoverflow.com/q/48947759

multithreading
tags question: http://stackoverflow.com/q/48880508
tags question: http://stackoverflow.com/q/48808472
tags question: http://stackoverflow.com/q/48838346
tags question: http://stackoverflow.com/q/48932108
tags question: http://stackoverflow.com/q/48881833
tags question: http://stackoverflow.com/q/48838917
tags question: http://stackoverflow.com/q/48888738
tags question: http://stackoverflow.com/q/48862213
type: Tag
tags question: http://stackoverflow.com/q/48819561
tags question: http://stackoverflow.com/q/48817008
tags question: http://stackoverflow.com/q/48822771
tags question: http://stackoverflow.com/q/48890687
tags question: http://stackoverflow.com/q/48890967
tags question: http://stackoverflow.com/q/48898831
tags question: http://stackoverflow.com/q/48910235
tags question: http://stackoverflow.com/q/48882225
tags question: http://stackoverflow.com/q/48859664
tags question: http://stackoverflow.com/q/48807879
tags question: http://stackoverflow.com/q/48824663
tags question: http://stackoverflow.com/q/48899570
tags question: http://stackoverflow.com/q/48952411
tags question: http://stackoverflow.com/q/48879277
tags question: http://stackoverflow.com/q/48903647
tags question: http://stackoverflow.com/q/48866735
tag name: multithreading
tags question: http://stackoverflow.com/q/48858449
tags question: http://stackoverflow.com/q/48817005
tags question: http://stackoverflow.com/q/48826912

http://stackoverflow.com/a/48922804
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48918819
downvote count: 0
answers question: http://stackoverflow.com/q/48918819
type: AcceptedAnswer
has body: Most probably the size of your StuffPanel is (0,0).

join
tags question: http://stackoverflow.com/q/48896971
tags question: http://stackoverflow.com/q/48873499
tags question: http://stackoverflow.com/q/48866886
type: Tag
tag name: join
tags question: http://stackoverflow.com/q/48866661

http://stackoverflow.com/comment/84641925
type: Comment
has text: I guess without knowing what you are doing it's hard to suggest anything else. I think you basically have three ugly options: squirrel that checkbox value away somewhere for later use, access `request.POST` directly in your view, or do your stuff in the form class somewhere. Or rethink your approach altogether.
comment on: http://stackoverflow.com/a/48818718
type: AnswerComment
score: 0

http://stackoverflow.com/a/48835538
has body: I bunched two solutions from SO together in one to make a very simple coin toss. It has some similarities with your solution but everything is stripped. import random def int_input(text): """Makes sure that that user input is an int""" # source: https://stackoverflow.com/questions/22047671 while True: try: num = int(input(text)) except ValueError: print("You must enter an integer.") else: return num def main(): """Asks for amount of tosses and prints sum(heads) and sum(tails)""" # source: https://stackoverflow.com/questions/6486877/ tosses = int_input("How many times of flips do you want? ") heads = sum(random.randint(0, 1) for toss in range(tosses)) tails = tosses - heads print('The {} tosses resulted in:\n{} heads and {} tails.' .format(tosses,heads,tails)) main()
answers question: http://stackoverflow.com/q/48835297
score: -1
downvote count: 1
type: Answer
upvote count: 0

http://stackoverflow.com/comment/84871837
has text: @CronMerdek number of rows
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48932462
type: Comment

http://stackoverflow.com/comment/84905902
comment on: http://stackoverflow.com/a/48916402
type: AnswerComment
score: 0
type: Comment
has text: Hello Lohmar, Thanks for your time. The error appear is: Traceback (most recent call last): File "Extended.py", line 19, in <module> net_connect.send_command(cmd, expect_string='\] ?: ?') File "/home/claudio/.local/lib/python2.7/site-packages/netmiko/base_connection.py", line 967, in send_command search_pattern)) IOError: Search pattern never detected in send_command_expect: \] ?: ?

http://stackoverflow.com/q/48932596
tagged with: python
score: 1
has body: In phpstorm you just press cmd + N and there is an option to Generate PHPDoc blocks for all methods in the file and it automatically takes into account type hinting. so: function(param1:str): array { will automatically have in docstring @param1:str @return:array I cannot find how to do this in pycharm, instead I have to go through each method and do it individually and the docstring don't have the type automatically inserted.
type: Question
has title: In pycharm, how do you insert documentation comments for the whole file
upvote count: 1
favorite count: 0
tagged with: pycharm
answer count: 0
downvote count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84792015
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48893073
has text: Yeah, most math functions don't modify the argument that you pass into the function; most return the result. There are exceptions though. Keep learning Python. You will love it.
score: 0

http://stackoverflow.com/comment/84759270
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48855155
has text: Thank you Andersson. I'll try this out and share my results.
score: 0

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

http://stackoverflow.com/q/48897413
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84800706
linked to: http://stackoverflow.com/q/753190
score: 0
has body: 1.This becomes the interactive plot I am referring to. You will need to open the figure that appears at the bottom of the screen (if it does not display automatically) immediately after you start the program, in order to see the "animation". My question is: how do I record all of the updates in this interactive plot as a video? I do not want to record the screen. I also do not want to replace my current code fully with an animation object. Is there any way to create a video recording this interactive plot by supplementing the interactive plotting code rather than fully replacing it? import matplotlib.pyplot as plt plt.ion() plt.figure() for i in range(1000): plt.axis((0,10,0,100)) plt.plot([1,2,3,4,5,6,7,8,9],[i,i,i,i,i,i,i,i,i],'ro') plt.pause(.1) plt.cla() plt.clf()
has title: How to record an interactive plot?
tagged with: python
tagged with: video
has comment: http://stackoverflow.com/comment/84801258
tagged with: recording
has comment: http://stackoverflow.com/comment/84839545
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84800484

http://stackoverflow.com/comment/84712526
comment on: http://stackoverflow.com/q/48854393
score: 0
type: Comment
has text: Welcome to SO. To maximise the number and helpfulness of responses, you need to provide a **[mcve]**. The key word, in this case, seems to be minimal. It really helps to pinpoint the bit of logic that seems to be not working.
type: QuestionComment

http://stackoverflow.com/comment/84643141
type: Comment
has text: practically, just create a new image data generator object, maybe call one train_datagen and the other valid_datagen, call each one and save to different dirs
comment on: http://stackoverflow.com/a/48819422
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84838840
type: QuestionComment
has text: I am working on My problem is generating
comment on: http://stackoverflow.com/q/48904541
score: 0
type: Comment

http://stackoverflow.com/a/48963527
upvote count: 2
type: AcceptedAnswer
has body: Assuming your data is stored in d, there are several ways to do this: List Comprehension For every iterable you can use a list comprehension, so iterate over the items with [it for it in iterable] (you can use list comprehensions in dictionaries, too). In [6]: [{dic['answer_type']: dic['answer__count']} for dic in d] Out[6]: [{'Yes': 5}, {'No': 3}, {'Maybe': 2}] Functional Approach If you are more the functional programming guy, consider using a map, which applies a function to each element of an iterable (this is my preferred approach, if I have to do this again and again with a list, I only have to define the function once then): In [2]: map(lambda dic: {dic['answer_type']: dic['answer__count']}, d) Out[2]: [{'Yes': 5}, {'No': 3}, {'Maybe': 2}] For some people this is not as good to read as list comprehensions, for some it's better, depends on personal feelings. This will work with python2, in py3 it gives you an iterator, so you have to use list around the map to get the list.
accepted answer of: http://stackoverflow.com/q/48963461
answers question: http://stackoverflow.com/q/48963461
type: Answer
has comment: http://stackoverflow.com/comment/84936551
score: 2
downvote count: 0

http://stackoverflow.com/q/48852898
has title: Using ElementTree to parse XML results in empty csv file
answer count: 2
has body: I'm a complete beginner in Python, so I've had to rely on several tutorials to put this code together. It does produce a .csv file, but it turns out empty (0kb). I've found others with this question had forgotten to close the file, but that doesn't seem to be the problem here. I'm grateful for any hints. This is the xml if that helps: https://api.nextbike.net/maps/nextbike-live.xml?city=14 import xml.etree.ElementTree as ET import csv tree = ET.parse('nextbike-live.xml') root = tree.getroot() with open('Bike_pos.csv', 'w') as Bike_pos: csvwriter = csv.writer(Bike_pos) bike_head = [] count = 0 for member in root.findall('place'): bike = [] if count == 0: station = member.find('name').tag bike_head.append(station) lat = member.find('lat').tag bike_head.append(lat) lon = member.find('lng').tag bike_head.append(lon) bikeno = member.find('bike_numbers').tag bike_head.append(bikeno) count = count + 1 station = member.find('name').text bike.append(station) lat = member.find('lat').text bike.append(lat) lon = member.find('lng').text bike.append(lon) bikeno = member.find('bike_numbers').text csvwriter.writerow(bike) Bike_pos.close()
score: 0
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48853635
tagged with: elementtree
tagged with: parsing
tagged with: http://stackoverflow.com/tag/xml
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84710611
has answer: http://stackoverflow.com/a/48856211
type: Question

http://stackoverflow.com/q/48928973
has comment: http://stackoverflow.com/comment/84864476
has answer: http://stackoverflow.com/a/48929549
favorite count: 0
type: UnansweredQuestion
has body: I am new with python and need to implement an interface to an accounting tool. I received some XSD Files which describes the interface. What is the easiest way to generate the XML according to the XSD? Is there any module I can use? Do I have to create the XML all by myself and I can use the XSD just to verify it? How do I best proceed?
tagged with: python
tagged with: xsd
has title: Python create xml from xsd
tagged with: http://stackoverflow.com/tag/xml
score: 19
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/62910151
upvote count: 20
answer count: 2

http://stackoverflow.com/q/48843382
has body: enter image description here I have a template that displays a detail of a dorm with a list of "room_numbers". The problem: I am trying to make "room_numbers" as a link to each specific dorm room details page (see screenshot above). A dorm room details page has the following format: rooms/<int:pk> as specified in my urls.py I have scoured through the web and can't find where I need to start. Django and Python newbie here so please bear with me. URLs.py > urlpatterns = [ path('', views.index, name='index'), path('list/', views.DormsListView.as_view(), name='dorms'), path('list/<int:pk>', views.DormsDetailView.as_view(), name='dorm-detail'), path('rooms/', views.DormsRoomView.as_view(), name='rooms'), path('rooms/<int:pk>', views.DormsRoomsDetailView.as_view(), name='rooms-detail'), ] Views.py (DormsDetailView) > class DormsDetailView(LoginRequiredMixin, generic.DetailView): model = Dorm def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['room_numbers'] = ", ".join(self.object.dormroom_set.values_list('room_number', flat=True)) return context Views.py (DormRoomsDetailView) > class DormsRoomsDetailView(LoginRequiredMixin, generic.DetailView): model = DormRoom Dorm_Detail.html > Rooms: {{ room_numbers }}
possible better answer: http://stackoverflow.com/a/48843476
accepted answer: http://stackoverflow.com/a/48843502
tagged with: python
has answer: http://stackoverflow.com/a/48843502
has title: Link to a different view's template from one template Django
tagged with: django
has answer: http://stackoverflow.com/a/48843476
type: AnsweredQuestion
type: Question
score: 0
answer count: 2

http://stackoverflow.com/comment/84624206
type: QuestionComment
comment on: http://stackoverflow.com/q/48810339
has text: I don't want to set a default image, so don't see how this is a duplicate question.
score: 0
type: Comment

http://stackoverflow.com/comment/84726666
type: Comment
score: 0
type: QuestionComment
has text: i've just edited the code so that it runs and prints a "grid" although the grid isnt exactly what I got in my project. @Arount
comment on: http://stackoverflow.com/q/48861574

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

http://stackoverflow.com/a/48938685
has body: How can I convert 7/8 to a float number? a="7/8".split("/") a=int(a[0])/int(a[1]) Or if you don't care about safety: a=eval("7/8")
score: 0
answers question: http://stackoverflow.com/q/48938632
type: Answer

http://stackoverflow.com/a/48887920
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84808645
downvote count: 0
has body: The models.SlugField() does not support prepopulated_from or prepopulated_fields, so in your model you should use slug = models.SlugField(max_length=50) instead of slug = models.SlugField(prepopulated_from=album_name) or slug = models.SlugField(prepopulated_fields=album_name) Secondly, in your ModelAdmin class, you should use a tuple of strings with the prepopulated_fields option: class AlbumAdmin(admin.ModelAdmin): list_display = ('album_name', 'album_creation_date') prepopulated_fields = {'slug': ("album_name",)}
accepted answer of: http://stackoverflow.com/q/48887845
type: Answer
answers question: http://stackoverflow.com/q/48887845
upvote count: 2
score: 2
has comment: http://stackoverflow.com/comment/84800855

http://stackoverflow.com/a/48958161
answers question: http://stackoverflow.com/q/48958062
downvote count: 0
has body: If you're going to only supply values for some columns, you need to specify which columns. Otherwise the engine won't know where to put them. This line needs to be changed: c.execute('insert into mytable values(?, ?, ?, ?, ?)', \ (datetime.datetime(2018,4,23,23,00), 'Test', 'Test2', 2.1, 11.1)) To this: c.execute('insert into mytable (date, title, custom, x, y)values(?, ?, ?, ?, ?)', \ (datetime.datetime(2018,4,23,23,00), 'Test', 'Test2', 2.1, 11.1))
type: Answer
has comment: http://stackoverflow.com/comment/84923309
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84923344

http://stackoverflow.com/a/48851244
downvote count: 1
has comment: http://stackoverflow.com/comment/85969167
type: Answer
has comment: http://stackoverflow.com/comment/85033722
score: 2
has body: You could upload the file using a resumable media upload. This will send the file in chunks and should not max out your memory, which I assume is happening because your client is trying to send the whole file at once. To do this you need to pass a MediaFileUpload object to the create() method in which the resumable flag is set to True. Optionally you can also set the chunksize. metadata = {'name': filename} media = MediaFileUpload(filename, mimetype=mimetype, resumable=True) request = DRIVE.files().create(body=metadata, media_body=media) response = None while response is None: status, response = request.next_chunk() if status: print "Uploaded %d%%." % int(status.progress() * 100) print "Upload Complete!" Try reducing the chunksize if needed.
has comment: http://stackoverflow.com/comment/93048405
answers question: http://stackoverflow.com/q/48850726
upvote count: 3

args
tags question: http://stackoverflow.com/q/48833362
tag name: args
tags question: http://stackoverflow.com/q/48847018
type: Tag

http://stackoverflow.com/comment/84696583
comment on: http://stackoverflow.com/q/48846121
has text: If in instantiateClient, you just return client and comment out the image loading code, does the client actually authenticate against the API? Seems like that's the root of it, if I had to guess.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84922300
type: Comment
comment on: http://stackoverflow.com/a/48957412
has text: but main problem was `date` plot do not work with `datetime64[ns]` today [howto](https://matplotlib.org/faq/howto_faq.html?highlight=how#plot-numpy-datetime64-values). Or try pandas plotting it's very helpful. [pandas](https://pandas.pydata.org/pandas-docs/stable/visualization.html)
type: AnswerComment
score: 0

http://stackoverflow.com/a/48915715
has comment: http://stackoverflow.com/comment/84881430
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48858638
has comment: http://stackoverflow.com/comment/84892588
type: Answer
has body: I had the same problem with pyglet version 1.3.1, everything worked except the on_mouse_press() method, so i downgraded to version 1.3.0 and now everything works fine. You can specify the version you want to install with pip like so: pip install pyglet==1.3.0
answers question: http://stackoverflow.com/q/48858638
score: 3
upvote count: 3

http://stackoverflow.com/q/48921509
has comment: http://stackoverflow.com/comment/84851526
upvote count: 1
has comment: http://stackoverflow.com/comment/84851764
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84851185
tagged with: python
has title: Most efficient way to remove values whilst iterating over a list
has comment: http://stackoverflow.com/comment/84851884
type: AnsweredQuestion
tagged with: list
accepted answer: http://stackoverflow.com/a/48921719
downvote count: 0
has comment: http://stackoverflow.com/comment/84849681
has body: I have a dataset that contains X,Y Coordinates from several different subjects. So Subject 1 through to n with each having a separate XY. I append all the X and Y coordinates into separate lists of lists called plot. So one list is for the X's and one is for the Y's from each subject. Example Input (3 subjects): Subject 1_X Subject 1_Y Subject 2_X Subject 2_Y Subject 3_X Subject 3_Y 11 45 34 67 8 26 12 46 33 65 7 25 Example Output: plot[0] = [[11,34,8],[12,33,7]] #X's plot[1] = [[45,67,26],[46,65,25]] #Y's Before this, I want to remove both the X and corresponding Y when the X value is below a certain threshold (10 in this case). Example output below: (Subject 3 is removed) plot[0] = [[11,34],[12,33]] #X's plot[1] = [[45,67],[46,65]] #Y's This process is replicated here: data = [random.sample(range(80), 40) for _ in range(75000)] #Similar size and format plot = [[],[]] n = 0 for row in data : if n == 0 : n+=1 continue x_data = [] y_data = [] for (x,y) in [(0,1),(2,3), (4,5), (6,7), (8,9), (10,11), (12,13), (14,15), (16,17), (18,19), (20,21), (22,23), (24,25), (26,27), (28,29), (30,31), (32,33), (34,35), (36,37), (38,39)] : xcoord = float(row[x]) ycoord = float(row[y]) if xcoord &gt;= 10 : x_data.append(xcoord) y_data.append(ycoord) plot[0].append(x_data) plot[1].append(y_data) This does the job but I use these lists to create an animated scatter plot. Which is extremely slow. If I remove the function that eliminates the values &lt; 10 and refine the duplicates, it performs much faster. n=0 for row in data : if n == 0 : n+=1 continue plot[0].append(list(map(float, row[1:41][::2]))) plot[1].append(list(map(float, row[0:40][::2]))) Is there a quicker, more efficient method to iterate and remove specific values more quickly? I have tried to individually remove values from each source and then append at the end but this is more inefficient than I currently have. The scatter is called using the following: scatter = ax.scatter(plot[0][0], plot[1][0], c=['blue']) The animat…
score: 1
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/84849758
has answer: http://stackoverflow.com/a/48921719

http://stackoverflow.com/comment/84638754
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48816882
type: Comment
has text: that's the weird thing. The code outputs 1 correct digit in the wrong place even though the same number has been already compared

scipy
tags question: http://stackoverflow.com/q/48884655
tags question: http://stackoverflow.com/q/48826351
tags question: http://stackoverflow.com/q/48851764
tags question: http://stackoverflow.com/q/48926212
tags question: http://stackoverflow.com/q/48949580
tags question: http://stackoverflow.com/q/48842582
tags question: http://stackoverflow.com/q/48860471
tags question: http://stackoverflow.com/q/48898447
tags question: http://stackoverflow.com/q/48950424
tags question: http://stackoverflow.com/q/48857941
type: Tag
tags question: http://stackoverflow.com/q/48815767
tags question: http://stackoverflow.com/q/48897194
tag name: scipy
tags question: http://stackoverflow.com/q/48830734
tags question: http://stackoverflow.com/q/48843484
tags question: http://stackoverflow.com/q/48836873
tags question: http://stackoverflow.com/q/48931762
tags question: http://stackoverflow.com/q/48936510
tags question: http://stackoverflow.com/q/48915751
tags question: http://stackoverflow.com/q/48952140
tags question: http://stackoverflow.com/q/48926943
tags question: http://stackoverflow.com/q/48858104
tags question: http://stackoverflow.com/q/48881428
tags question: http://stackoverflow.com/q/48891382
tags question: http://stackoverflow.com/q/48899209
tags question: http://stackoverflow.com/q/48879587
tags question: http://stackoverflow.com/q/48938251
tags question: http://stackoverflow.com/q/48804936
tags question: http://stackoverflow.com/q/48854578
tags question: http://stackoverflow.com/q/48812073
tags question: http://stackoverflow.com/q/48853311
tags question: http://stackoverflow.com/q/48935472
tags question: http://stackoverflow.com/q/48850394
tags question: http://stackoverflow.com/q/48818373
tags question: http://stackoverflow.com/q/48895750
tags question: http://stackoverflow.com/q/48923943
tags question: http://stackoverflow.com/q/48807374
tags question: http://stackoverflow.com/q/48857635
tags question: http://stackoverflow.com/q/48816211
tags question: http://stackoverflow.com/q/48926093
tags question: http://stackoverflow.com/q/48889382
tags question: http://stackoverflow.com/q/48877227
tags question: http://stackoverflow.com/q/48946475

http://stackoverflow.com/comment/84897850
type: Comment
type: QuestionComment
score: 0
has text: Hint - this page is UTF8. View the source. No escape characters or escape sequences are used. Even if the text is clearly non-ANSI όπως αυτό εδώ
comment on: http://stackoverflow.com/q/48945594

http://stackoverflow.com/q/48958996
has title: How to use nested if statements within a pandas dataframe - Python
has comment: http://stackoverflow.com/comment/84949028
has answer: http://stackoverflow.com/a/59094937
type: Question
has comment: http://stackoverflow.com/comment/84981183
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84932333
score: 0
has comment: http://stackoverflow.com/comment/104423177
tagged with: pandas
has body: I have a dataframe that consists of the U.S. unemployment rate, a year long moving average for the unemployment rate, a monthly price of the S&amp;P 500 along with a 10 month moving average. start = "1950-01-01" end = "2017-12-31" fred_unemployment = quandl.get("FRED/UNRATE", start_date=start, end_date=end) fred_unemployment["UE 12MMA"] = fred_unemployment["Value"].rolling(12).mean() fred_unemployment["SPY"] = spy["Adj Close"] fred_unemployment["SPY 200d MA"] = spy["Adj Close"].rolling(10).mean() From this I'm looking to identify the rows where: fred_unemployment["Value"] > fred_unemployment["UE 12MMA"] Then have it check if fred_unemployment["SPY"] &lt; fred_unemployment["SPY 200d MA"] Ideally this would result in certain buy and sell decisions by using what I believe are called "nested if statements" ie: if this: if that: Sell Stock else: Buy Stock else: Buy Stock Here's where I'm stuck. I've created another column called fred_unemployment["Signals"] and am currently using np.where that sets the "Signal" columns values to either 1 or 0 depending on the conditions. fred_unemployment["Signal"] = np.where((fred_unemployment["Value"] &gt; fred_unemployment["UE 12MMA"]) &amp; (fred_unemployment["SPY"] &lt; fred_unemployment["SPY 200d MA"]), 0, 1) So while this works in some cases it wouldn't work in the case where the "Values" &lt; "UE 12MMA" and the "SPY" > "SPY 200d MA" because instead of the nested if statements it's using the if and statement. Here's a few lines from the dataframe In summary, how can I create the nested if statement result to sort through the pandas dataframe? Here's the head of the dataframe: Value UE 12MMA SPY SPY 200d MA Signal Date 1990-01-01 5.4 NaN 359.69 334.658 1 1990-02-01 5.3 NaN 328.79 337.898 1 1990-03-01 5.2 NaN 332.74 340.260 1 1990-04-01 5.4 NaN 338.70 341.933 1 1990-05-01 5.4 NaN 332.25 343.235 1 the tail: Value UE 12MMA SPY SPY 200d MA Signal Date 2010-08-01 9.5 9.741667 1125.86 1109.393 1 2010-09-01 9.5 9.716667 1080.29 1113.134 1…
has comment: http://stackoverflow.com/comment/84931367
tagged with: finance
answer count: 1
tagged with: data-analysis
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/84797206
has text: What question, exactly, are you answering?
type: AnswerComment
comment on: http://stackoverflow.com/a/48895679
score: 0
type: Comment

http://stackoverflow.com/a/48900480
answers question: http://stackoverflow.com/q/48900310
score: -1
has body: Manual approach: import math def to_radian(degree): return degree * math.pi/180 print(math.cos(to_radian(30))) Out[0]: 0.866025403784
type: Answer
downvote count: 1
upvote count: 0

http://stackoverflow.com/q/48896900
tagged with: python
tagged with: indexing
has body: I would like to be able to pull out an arbitrary row, such as the 4th row, and get an array so that I can send it through another function. What would be the easiest way to do this?
tagged with: numpy
has answer: http://stackoverflow.com/a/48896954
tagged with: arrays
has answer: http://stackoverflow.com/a/48896943
score: 11
possible better answer: http://stackoverflow.com/a/48896943
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
has title: Output a single row in pandas to an array
upvote count: 11
accepted answer: http://stackoverflow.com/a/48896954
favorite count: 0
type: Question
answer count: 2

http://stackoverflow.com/comment/84890633
type: QuestionComment
comment on: http://stackoverflow.com/q/48941928
has text: `def screenChanger(self, event=None, pageNum):` try like this, Actually why you add argument `event` here ?I couldn't see you used that one in your method.
score: 0
type: Comment

http://stackoverflow.com/comment/84721274
comment on: http://stackoverflow.com/a/48858913
type: AnswerComment
type: Comment
has text: Thanks, but that did not work either. I manually checked the files to verify it is not correctly masking.
score: 0

http://stackoverflow.com/comment/84750834
has text: Yeah, I think I saw about the same performance trying previously with 25 workers as I did with 125. Maybe I can reduce it further. I'll experiment. Out of curiosity, is there any point to specifying `--autoscaling_algorithm=NONE` if I'm already specifying `num_workers`? As long as `num_workers` is specified, I'm getting the performance gain, but I don't see further references to `autoscaling_algorithm` in the Beam codebase to verify the behavior myself (I assume it's handled somewhere in the Dataflow codebase).
type: Comment
comment on: http://stackoverflow.com/a/48848778
score: 0
type: AnswerComment

http://stackoverflow.com/a/48817973
score: 2
has comment: http://stackoverflow.com/comment/84643305
has comment: http://stackoverflow.com/comment/84640188
has comment: http://stackoverflow.com/comment/84643391
has comment: http://stackoverflow.com/comment/84640238
answers question: http://stackoverflow.com/q/48817935
has comment: http://stackoverflow.com/comment/84640491
downvote count: 0
has comment: http://stackoverflow.com/comment/84641135
upvote count: 2
type: Answer
has body: You can pass them as category and using value_counts df.c1.astype('category',categories=df.c2.tolist()).value_counts(sort=False) Out[572]: han solo 2 r2d2 1 finn 1 the emporer 0 c3po 0 leia organa 1 darth vader 1 Name: c1, dtype: int64 Or you can do pd.crosstab(df.c2,df.c1).sum().reindex(df.c2,fill_value=0) Out[592]: c2 han solo 2 r2d2 1 finn 1 the emporer 0 c3po 0 leia organa 1 darth vader 1

http://stackoverflow.com/comment/84676055
type: Comment
score: 1
has text: Write two files with the same name. Example: `echo 1 > test && echo 2 > TEST && cat test`
type: AnswerComment
comment on: http://stackoverflow.com/a/48835442

http://stackoverflow.com/a/48929359
answers question: http://stackoverflow.com/q/48929049
type: Answer
has comment: http://stackoverflow.com/comment/84866480
has body: I think you want something like this: patents.set_index('States').T.plot(kind='line') Output:
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48929049

http://stackoverflow.com/q/48862360
answer count: 0
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84728507
has title: More efficient way to import 100k+ .csv's into Pandas
score: 0
tagged with: pandas
has body: I have 225 folders that contain ~107,000 .csv's that I want to do some conversion on then import into an already created pandas dataframe. Main Folder | -------------------------------- | | | subfolder1 sub2 ... sub225 | | | 600 csv's 22 csv's 1400 csv's My current code does what's needed with a smaller number of files (10k). However with 100k files it slows down massively and eventually crashes my jupyter notebook/chrome roughly half way through which I think is from a memory error (the code is also slow). My machine has 16GB RAM. def data_loader(pair='XYZ'): df = get_df() path = r'D:\Sample\{}'.format(pair) all_files = glob.glob(os.path.join(path, "*.csv")) print(pair) df_from_each_file = (pd.read_csv(f) for f in all_files) dfnew = pd.concat(df_from_each_file, ignore_index=True) # Perform data pre-processing that turns the 80k rows into 5 columns. return df for i in range(len(pairs)): data_loader(pairs[i]) It outputs 5 columns for each subfolder and adds it to the current df so a total of 225x5 new columns added to the existing df. df original col1 | col2 | subfolder1 cols1|2|3|4|5 .. subfolder225 cols1|2|3|4|5 what would be a better way to implement this? Thanks.
has comment: http://stackoverflow.com/comment/84727814
tagged with: python

http://stackoverflow.com/q/48818691
has answer: http://stackoverflow.com/a/48818775
type: Question
has answer: http://stackoverflow.com/a/48818861
has answer: http://stackoverflow.com/a/48819201
accepted answer: http://stackoverflow.com/a/48818775
tagged with: pandas
has answer: http://stackoverflow.com/a/48818774
score: 3
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48818774
tagged with: python
answer count: 4
has title: selecting indexes with multiple years of observations
tagged with: indexing
type: AnsweredQuestion
upvote count: 3
has body: I wish to select only the rows that have observations across multiple years. For example, suppose mlIndx = pd.MultiIndex.from_tuples([('x', 0,),('x',1),('z', 0), ('y', 1),('t', 0),('t', 1)]) df = pd.DataFrame(np.random.randint(0,100,(6,2)), columns = ['a','b'], index=mlIndx) In [18]: df Out[18]: a b x 0 6 1 1 63 88 z 0 69 54 y 1 27 27 t 0 98 12 1 69 31 My desired output is Out[19]: a b x 0 6 1 1 63 88 t 0 98 12 1 69 31 My current solution is blunt so something that can scale up more easily would be great. You can assumed a sorted index. df.reset_index(level=0, inplace=True) df[df.level_0.duplicated() | df.level_0.duplicated(keep='last')] Out[30]: level_0 a b 0 x 6 1 1 x 63 88 0 t 98 12 1 t 69 31

http://stackoverflow.com/q/48873515
has comment: http://stackoverflow.com/comment/84751023
tagged with: python
has body: I have a dictionary that contains 6 dataframes stored as values. I'd like to convert these values into actual dataframes with the name of the dataframe being the key corresponding to the values. The dictionary structure is like this: Name: frames, Type: dict, Size: 6 '_20Nov2017_24Dec2017':[1220608 rows x 4 columns] '_25Dec2017_28Jan2018':[1931572 rows x 4 columns] ...etc The desired output is 6 dataframes, with the names _20Nov2017_24Dec2017, 25Dec2017_28Jan2018 and so on. Here is a snapshot of the dataframes if needed: UpdateDatetime Code SaleTime Status 05JAN18:12:37 BSNAS 03JAN18:19:55 N Any ideas how to go about this? Thanks!
has comment: http://stackoverflow.com/comment/84751108
has comment: http://stackoverflow.com/comment/84750998
duplicate of: http://stackoverflow.com/q/1373164
answer count: 0
score: 0
has comment: http://stackoverflow.com/comment/84750988
type: Question
has title: Convert each dictionary key-value into dataframe- Pandas
has comment: http://stackoverflow.com/comment/84751461
has comment: http://stackoverflow.com/comment/84751720
linked to: http://stackoverflow.com/q/11553721
duplicate of: http://stackoverflow.com/q/4010840
has comment: http://stackoverflow.com/comment/84751249
has comment: http://stackoverflow.com/comment/84751126
has comment: http://stackoverflow.com/comment/84750929
duplicate of: http://stackoverflow.com/q/11553721
tagged with: pandas
duplicate of: http://stackoverflow.com/q/14241133
has comment: http://stackoverflow.com/comment/84751753
has comment: http://stackoverflow.com/comment/84752058
has comment: http://stackoverflow.com/comment/84751339
has comment: http://stackoverflow.com/comment/84751423
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/1373164

http://stackoverflow.com/a/48902864
score: 0
has comment: http://stackoverflow.com/comment/84811284
type: Answer
answers question: http://stackoverflow.com/q/48902763
has body: Wrong usage of self is whats giving you the problem : https://pythontips.com/2013/08/07/the-self-variable-in-python-explained/ def scan(input): .... should solve it. The link is to understand why.

http://stackoverflow.com/comment/84887700
score: 3
has text: ( @AmitSingh ) it's possible in some Regex engines, e.g. in PowerShell / .Net it works to `$string -split '(?m)(?<=^[^:]+)\)'` but Python doesn't seem to support variable length lookbehind matches and that rules out this approach. I can't think of a way past that with just Regex.
comment on: http://stackoverflow.com/q/48940160
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48847606
upvote count: 4
answers question: http://stackoverflow.com/q/48847564
has comment: http://stackoverflow.com/comment/84699465
has body: You are converting your input into a string instead of an integer. Use int() to convert your input to an integer: personsAge = int(input("&lt;Enter your age&gt;")); Then you will be able to compare it to other integers. Don’t forget to convert your personsAge integer to a string with str() everytime you concatenate personsAge with a string. Example: print("My age is " + str(personsAge)); It is good practice to add error-handling where user input is not guaranteed to be of the required type. For example: while True: try: personsAge = int(input("&lt;Enter your age&gt;")) break except ValueError: print('Please input an integer.') continue
downvote count: 0
has comment: http://stackoverflow.com/comment/84699410
type: Answer
score: 4

http://stackoverflow.com/comment/84653585
score: 0
type: Comment
type: QuestionComment
has text: How about this: `indices = [i for j in range(1,5) for i in range(j)]` and then `df.iloc[indices]`. Is that what you want?
comment on: http://stackoverflow.com/q/48822715

http://stackoverflow.com/q/48959940
has title: run a task if something Worked Python3
has body: This is my script. What I want to do is that I want to run the print function if the call function worked. from subprocess import call from os import system as S Com1 = 'sudo xrandr --newmode "1368x768_60.00" 85.25 1368 1440 1576 1784 768 771 781 798 -hsync +vsync' Command1 = Com1.split() Com2 = 'sudo xrandr --addmode VGA1 "1368x768_60.00"' Command2 = Com2.split() COMMAND1 = call(Command1) COMMAND2 = call(Command2) print('\n\n\t\nscreen resolution successfully changed Script By : My name '.title()) print('\n\n') This is a pseudocode of this: if COMMAND1 and COMMAND2 worked: print('It WorkEd') else: print('IT DIDNT WORK') Can someone please help me. I am very new in Python.
upvote count: 0
score: -1
type: Question
has answer: http://stackoverflow.com/a/48960077
tagged with: python-3.6
answer count: 1
downvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48863926
type: Answer
score: 0
has comment: http://stackoverflow.com/comment/84743905
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48858104
answers question: http://stackoverflow.com/q/48858104
has body: You've made the classic mistake of assuming that the * operator is doing matrix multiplication. This is not true in Python/numpy (see http://www.scipy-lectures.org/intro/numpy/operations.html and https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html). I broke it down into intermediate steps and used the dot function import numpy as np def Mahalanobis(x, covariance_matrix, mean): x = np.array(x) mean = np.array(mean) covariance_matrix = np.array(covariance_matrix) t1 = (x-mean) print(f'Term 1 {t1}') icov = np.linalg.inv(covariance_matrix) print(f'Inverse covariance {icov}') t2 = (x.transpose()-mean.transpose()) print(f'Term 2 {t2}') mahal = t1.dot(icov.dot(t2)) #return (x-mean)*np.linalg.inv(covariance_matrix).dot(x.transpose()-mean.transpose()) return mahal #variables x and mean are 1xd arrays; covariance_matrix is a dxd matrix #the 1xd array passed to x should be multiplied by the (inverted) dxd array #that was passed into the second argument #the resulting 1xd matrix is to be multiplied by a dx1 matrix, the transpose of #[x-mean], which should result in a 1x1 array (a number) Mahalanobis([2,5], [[.5,0],[0,2]], [3,6]) produces Term 1 [-1 -1] Inverse covariance [[2. 0. ] [0. 0.5]] Term 2 [-1 -1] Out[9]: 2.5

http://stackoverflow.com/a/75833603
score: -1
has body: Is it because you spelled length wrong the second time so it's calling it wrong
type: Answer
answers question: http://stackoverflow.com/q/48808193
downvote count: 1
upvote count: 0

http://stackoverflow.com/comment/84827506
score: 0
type: AnswerComment
has text: @Jean-FrançoisFabre: you're right, it's my turn to get confused :)
type: Comment
comment on: http://stackoverflow.com/a/48910349

http://stackoverflow.com/a/48868124
upvote count: 1
answers question: http://stackoverflow.com/q/48867749
score: 1
downvote count: 0
has body: In your first commented line, you have oosdF instead of oosDF. In your second commented line, you're setting the column to be abs() applied to the whole dataframe. That should be oosDF['diff'].abs() Hope this helps!
type: Answer

http://stackoverflow.com/a/48911170
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48881463
type: Answer
answers question: http://stackoverflow.com/q/48881463
has body: The calculator alone working from tkinter import * def iCalc(source, side): storeObj = Frame(source, borderwidth=4, bd=4, bg="black") storeObj.pack(side=side, expand=YES, fill=BOTH) return storeObj def button(source, side, text, command=None): storeObj = Button(source, text=text, command=command) storeObj.pack(side=side, expand=YES, fill=BOTH) return storeObj class app(Frame): def __init__(self): Frame.__init__(self) self.option_add("*Font", "arial 20 bold") self.pack(expand=YES, fill=BOTH) self.master.title("Calculator") display = StringVar() # relief can be FLAT or RIDGE or RAISED or SUNKEN GROOVE Entry(self, relief=RIDGE, textvariable=display, justify='right', bd=30, bg='darkgray').pack(side=TOP, expand=YES, fill=BOTH) for clearBut in (["CE"], ["C"]): erase = iCalc(self, TOP) for ichar in clearBut: button(erase, LEFT, ichar, lambda storeObj=display, q=ichar: storeObj.set("")) for numBut in ("789/", "456*", "123-", "0.+"): functionNum = iCalc(self, TOP) for char in numBut: button(functionNum, LEFT, char, lambda storeObj=display, q=char: storeObj.set(storeObj.get() + q)) equalButton = iCalc(self, TOP) for iEqual in "=": if iEqual == "=": btniEqual = button(equalButton, LEFT, iEqual) btniEqual.bind("&lt;ButtonRelease-1&gt;", lambda e, s=self, storeObj=display: s.calc(storeObj), '+') else: btniEqual = button(equalButton, LEFT, iEqual, lambda storeObj=display, s='%s' % iEqual: storeObj.set(storeObj.get() + s)) def calc(self, display): try: display.set(eval(display.get())) except: display.set("ERROR") if __name__ == '__main__': app().mainloop() The calculator in the right frame... from tkinter import * import random import time root = Tk() root.geometry("1600x800+0+0") root.title("Cameron's Chocolate Machine") text_Input = StringVar() operator = "" Tops = Frame(root, width=1600, height=50, bg="powder blue", relief=SUNKEN) Tops.pack(side=TOP) f1 = Frame(root, width=1200, height=700, bg="powder blue", relief=SUNKEN) f1.pack(side=LEFT) localtime = time.asctime(time.localt…
has comment: http://stackoverflow.com/comment/85046602
score: 0

http://stackoverflow.com/q/48859444
has title: python, pelican, GitHub, netlify, failed deploy
tagged with: netlify
tagged with: pelican
has comment: http://stackoverflow.com/comment/84923600
downvote count: 0
answer count: 1
score: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: deployment
has body: I am getting a "failed deploy" when attempting to deploy my site to GitHub. here is the deploy log: 10:04:24 PM: Build ready to start 10:04:26 PM: Fetching cached dependencies 10:04:26 PM: Failed to fetch cache, continuing with build 10:04:26 PM: Starting to prepare the repo for build 10:04:26 PM: No cached dependencies found. Cloning fresh repo 10:04:26 PM: git clone git@github.com:chichihardcore/aboutthedata 10:04:28 PM: Preparing Git Reference refs/heads/master 10:04:30 PM: Starting build script 10:04:30 PM: Installing dependencies 10:04:31 PM: v8.9.4 is already installed. 10:04:31 PM: Now using node v8.9.4 (npm v5.6.0) 10:04:31 PM: Attempting ruby version 2.3.6, read from environment 10:04:33 PM: Using ruby version 2.3.6 10:04:33 PM: Using PHP version 5.6 10:04:33 PM: Installing pip dependencies 10:04:33 PM: Started restoring cached pip cache 10:04:33 PM: Finished restoring cached pip cache 10:04:33 PM: Collecting alabaster==0.7.10 (from -r requirements.txt (line 1)) 10:04:33 PM: /opt/buildhome/python2.7/local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:318: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#snimissingwarning. 10:04:34 PM: SNIMissingWarning 10:04:34 PM: /opt/buildhome/python2.7/local/lib/python2.7/site-packages/pip/_vendor/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.io/en/latest/security.html#insecurep…
has answer: http://stackoverflow.com/a/48861059
upvote count: 1
type: Question

http://stackoverflow.com/comment/84748787
type: AnswerComment
type: Comment
has text: Thanks a lot for your answer Vitor but I cannot accept it since it does not gives a straightforward way of figuring out my question. There are a lot of assumptions that have to be made and I'll end up with a bunch of code just to figure out if a dir is a Django one or not. Maybe I am asking an unanswered question... I'll leave it open, for future reference/edits, since there is not other similar in SO. Thanks again for your effort, really appreciate it :)
comment on: http://stackoverflow.com/a/48868860
score: 0

http://stackoverflow.com/a/48936392
has comment: http://stackoverflow.com/comment/84879793
answers question: http://stackoverflow.com/q/48935289
type: Answer
upvote count: 4
downvote count: 0
score: 4
has body: Ok, so the {% filter markdown %} needs to be in the same tab line as the markdown content. Easy fix but frustrating process. i.e. {% filter markdown %} # Title content List: * a * b * c {% endfilter %) vs. {% filter markdown %} # Title content List: * a * b * c {% endfilter %}

http://stackoverflow.com/q/48897910
favorite count: 0
tagged with: text-chunking
accepted answer: http://stackoverflow.com/a/48898103
possible better answer: http://stackoverflow.com/a/65057149
has answer: http://stackoverflow.com/a/65057149
has title: Parse NLTK tree output in a list of noun phrase
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
tagged with: nltk
has answer: http://stackoverflow.com/a/48898103
has body: I have a sentence text = '''If you're in construction or need to pass fire inspection, or just want fire resistant materials for peace of mind, this is the one to use. Check out 3rd party sellers as well Skylite''' I applied NLTK chunking on it and getting a tree as output. sentences = nltk.sent_tokenize(d) sentences = [nltk.word_tokenize(sent) for sent in sentences] sentences = [nltk.pos_tag(sent) for sent in sentences] grammar = """NP: {&lt;DT&gt;?&lt;JJ&gt;*&lt;NN.*&gt;+} RELATION: {&lt;V.*&gt;} {&lt;DT&gt;?&lt;JJ&gt;*&lt;NN.*&gt;+} ENTITY: {&lt;NN.*&gt;}""" cp = nltk.RegexpParser(grammar) for i in sentences: result = cp.parse(i) print(result) print(type(result)) result.draw() Output is as follows: (S If/IN you/PRP (RELATION 're/VBP) in/IN (NP construction/NN) or/CC (NP need/NN) to/TO (RELATION pass/VB) (NP fire/NN inspection/NN) ,/, or/CC just/RB (RELATION want/VB) (NP fire/NN) (NP resistant/JJ materials/NNS) for/IN (NP peace/NN) of/IN (NP mind/NN) ,/, this/DT (RELATION is/VBZ) (NP the/DT one/NN) to/TO (RELATION use/VB) ./.) HOw can I get noun phrase in format of list of a strings: [construction, need, fire inspection, fire, resistant materials, peace, mind, the one] Some suggestions please......?
has comment: http://stackoverflow.com/comment/84803252
answer count: 2
linked to: http://stackoverflow.com/q/33815401
downvote count: 0

http://stackoverflow.com/comment/84665231
comment on: http://stackoverflow.com/q/48817093
score: 0
has text: About if you need a single table for both: your current model is good as it is.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84643291
comment on: http://stackoverflow.com/a/48819633
has text: What do you mean, when there are multiple expressions on the same line?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84642642
type: Comment
comment on: http://stackoverflow.com/a/48818861
has text: @jp_data_analysis sorry, I also just noticed that within your and Wen's solution you index within the function. I think we can sort the index out of the functions since it is rather strange to have unsorted multi-level indexes anyway. Do you think it would be useful for benchmarking to move `df.sort_index()` out of the functions and place it under the `concat` operation?
score: 0
type: AnswerComment

http://stackoverflow.com/a/48817279
answers question: http://stackoverflow.com/q/48817143
type: Answer
has body: You can use re.sub like so: re.sub(r'([a-zA-Z])"([a-zA-Z])', r'\1\2', input); This will preserve any letter characters around the quote, so it won't target a double quote with a space, comma, or colon after it, for example. I see now that you tried something similar. The difference is the capture groups, and re-inserting them with r'\1\2'
score: 0

http://stackoverflow.com/a/57187024
upvote count: 1
score: 1
downvote count: 0
has body: In "another file" you need to import the two Enums you have defined: from &lt;enum_file&gt; import GradDescType, ActivationFunction
answers question: http://stackoverflow.com/q/48895218
type: Answer

rss
tags question: http://stackoverflow.com/q/48825587
tag name: rss
type: Tag

http://stackoverflow.com/comment/84728905
type: Comment
has text: @YuryFedorov Hmm, my bad, I didn't test it on python3.7, and assumed it would work as is. I've removed that part of my answer. :)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48862588

http://stackoverflow.com/a/48819829
has comment: http://stackoverflow.com/comment/84670722
score: 7
upvote count: 7
accepted answer of: http://stackoverflow.com/q/48818653
has body: The first part can be easily accomplished using the Pandas DatetimeIndex.dayofweek property, which starts counting weekdays with Monday as 0 and ending with Sunday as 6. df[df.index.dayofweek &lt; 5] will give you only the weekdays. For the second part you can use the datetime module. Below I will give an example for only one date, namely 2017-12-25. You can easily generalize it to a list of dates, for example by defining a helper function. from datetime import datetime, timedelta N = 3 df[abs(df.index.date - datetime.strptime("2017-12-25", '%Y-%m-%d').date()) &gt; timedelta(N)] This will give all dates that are more than N=3 days away from 2017-12-25. That is, it will exclude an interval of 7 days from 2017-12-22 to 2017-12-28. Lastly, you can combine the two criteria using the &amp; operator, as you probably know. df[ (df.index.dayofweek &lt; 5) &amp; (abs(df.index.date - datetime.strptime("2017-12-25", '%Y-%m-%d').date()) &gt; timedelta(N)) ]
has comment: http://stackoverflow.com/comment/84700016
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48818653
downvote count: 0
has comment: http://stackoverflow.com/comment/84697882
type: Answer

http://stackoverflow.com/q/48812097
possible better answer: http://stackoverflow.com/a/48854101
has answer: http://stackoverflow.com/a/48847105
has comment: http://stackoverflow.com/comment/84664497
has comment: http://stackoverflow.com/comment/84664907
has comment: http://stackoverflow.com/comment/102283386
downvote count: 2
has comment: http://stackoverflow.com/comment/84665068
has comment: http://stackoverflow.com/comment/84666701
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84683189
tagged with: magicmock
tagged with: pytest
score: 10
has body: I would like to test a email sending method I wrote. In file, format_email.py I import send_email. from cars.lib.email import send_email class CarEmails(object): def __init__(self, email_client, config): self.email_client = email_client self.config = config def send_cars_email(self, recipients, input_payload): After formatting the email content in send_cars_email() I send the email using the method I imported earlier. response_code = send_email(data, self.email_client) in my test file test_car_emails.py @pytest.mark.parametrize("test_input,expected_output", test_data) def test_email_payload_formatting(test_input, expected_output): emails = CarsEmails(email_client=MagicMock(), config=config()) emails.send_email = MagicMock() emails.send_cars_email(*test_input) emails.send_email.assert_called_with(*expected_output) When I run the test it fails on assertion not called. I believe The issue is where I am mocking the send_email function. Where should I be mocking this function?
has comment: http://stackoverflow.com/comment/84664786
has answer: http://stackoverflow.com/a/48854101
type: Question
has answer: http://stackoverflow.com/a/48850306
tagged with: mocking
duplicate of: http://stackoverflow.com/q/16134281
upvote count: 12
favorite count: 0
accepted answer: http://stackoverflow.com/a/48847105
answer count: 3
has title: Mocking an imported function with pytest
tagged with: python

http://stackoverflow.com/comment/84681404
has text: First case could start with empty tuple and have the range start with 1
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48837443

http://stackoverflow.com/q/48886332
has comment: http://stackoverflow.com/comment/84802334
has comment: http://stackoverflow.com/comment/84780208
answer count: 1
has comment: http://stackoverflow.com/comment/84815969
tagged with: django-oscar
score: 0
has title: django oscar commerce: Conflicting 'stockrecord' models in application
tagged with: python
has comment: http://stackoverflow.com/comment/84813203
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/84831171
type: Question
has body: I am using oscarcommerce for my django project. I want to extend the "StockRecord" model to include some more fields. So I forked the partner app as follows. (boscar is my app name) python manage.py oscar_fork_app partner boscar/ It successfully forked and new files were added to boscar/partner folder. I added 'boscar.partner' in my installed apps. Now I added new fields in StockRecord models as follows boscar/partner/models.py from django.db import models from oscar.apps.partner.abstract_models import AbstractStockRecord class StockRecord(AbstractStockRecord): effective_price = models.FloatField(default=0, null=True) is_instock_item = models.BooleanField(default=False, null=True) instock_quantity = models.IntegerField() from oscar.apps.partner.models import * # noqa Now when I try to make migrations it shows the following error. RuntimeError: Conflicting 'stockrecord' models in application 'partner': &lt;class 'oscar.apps.partner.models.StockRecord'&gt; and &lt;class 'boscar.partner.models.StockRecord'&gt;. I already successfully forked the catalogue and order models and that are working fine. Only this "StockRecord" models showing this error.
tagged with: django-models
has answer: http://stackoverflow.com/a/48915379

http://stackoverflow.com/q/48919333
has comment: http://stackoverflow.com/comment/84845017
upvote count: 0
score: -3
has answer: http://stackoverflow.com/a/48919545
has comment: http://stackoverflow.com/comment/84844924
answer count: 1
has title: Python 3 code while loop wrong output
favorite count: 0
has body: It's written in python 3. The code is trying to store all the input integers into a list and find the min, max and average. What causes the output average to be wrong here? from statistics import mean, median def main(): integers = [] integer = 0 while (1): input_str = input('Enter a value (0 to end): ') try: integer = int(input_str) except ValueError: print('Invalid input. Type a legit integer.') if integer == 0: if integers == []: print('No integer stored.') else: print('Min: {0}\nMax: {1}\nAvg: {2:.1f}\n'.format(min(integers),max(integers),sum(integers)/len(integers))) break elif integer &gt;= -65535 and integer &lt;= 65535: integers.append(integer) else: print('The integer is out of range.') main() The output is: Enter a value (0 to end): 110 Enter a value (0 to end): 60 Enter a value (0 to end): abc Invalid input. Type a legit integer. Enter a value (0 to end): 50 Enter a value (0 to end): 90 Enter a value (0 to end): 40 Enter a value (0 to end): hanbagui Invalid input. Type a legit integer. Enter a value (0 to end): 0 Min: 40 Max: 110 Avg: 64.3
accepted answer: http://stackoverflow.com/a/48919545
tagged with: python
has comment: http://stackoverflow.com/comment/84844911
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/84845125
type: Question

http://stackoverflow.com/comment/84838143
type: QuestionComment
has text: @DSM Yes, this is the answer I was looking for. If you write it as answer to this question (preferable including the networkx and scipy solution) I will except it as answer. The networkx solution worked great!
comment on: http://stackoverflow.com/q/48915248
score: 0
type: Comment

http://stackoverflow.com/comment/84806796
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48899242
type: Comment
has text: Note that `any()` will return on the first True match, not scan over all the elements like the question was trying to do

http://stackoverflow.com/comment/84684924
has text: it is given in this stackoverflow post ,pleas check and support /48838354/python-equivalent-function-logic-for-nonzero-value-calculation
type: Comment
comment on: http://stackoverflow.com/a/48840205
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84745162
has text: ... That said, it is much faster than what we did above (fractions of seconds at this point, but still). I'm going to leave @joaoavf's as the answer for now, because it perfectly retains the original data, but I will definitely be exploring this. Thank you for your help!
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48868661
type: Comment

http://stackoverflow.com/comment/84650427
comment on: http://stackoverflow.com/a/48823481
has text: @ivan_bilan I forgot the `json.loads` function. Just added it
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84891466
comment on: http://stackoverflow.com/q/48942393
score: 0
has text: try [djangorestframework](http://www.django-rest-framework.org/). SSL will be implemented besides rest apis. So what does ssl has to do with rest framework? Just a question in case if I am missing something.
type: Comment
type: QuestionComment

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

http://stackoverflow.com/a/48888180
upvote count: 1
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48887515
has body: Instead of re-implementing decimal rounding in SymPy, perhaps use decimal to do the rounding, but hide the calculation in a utility function: import sympy as sym import decimal from decimal import Decimal as D def dround(d, ndigits, rounding=decimal.ROUND_HALF_UP): result = D(str(d)).quantize(D('0.1')**ndigits, rounding=rounding) # result = sym.sympify(result) # if you want a SymPy Float return result for x in [0.0065, 1.0065, 10.0065, 100.0065]: print(dround(x, 3)) prints 0.007 1.007 10.007 100.007

http://stackoverflow.com/q/48884821
tagged with: django
tagged with: python
has body: I am building a blog with Django. This blog is made up by posts whose content would benefit a lot from using Markdown syntax. But some of this posts also include SageMath cells, which process some Python-Sage Code enclosed in some special divs, as in this tutorial. Now every Markdown engine parses the Python code, and both tools (Markdown and SageMath) come into conflict. Which would be smartest approach for implementing these posts?
has comment: http://stackoverflow.com/comment/84774420
answer count: 0
score: 1
upvote count: 1
has title: Django, Markdown and SageCell
has comment: http://stackoverflow.com/comment/84869638
type: Question
has comment: http://stackoverflow.com/comment/84866026
tagged with: django-models
tagged with: markdown
tagged with: sage
has comment: http://stackoverflow.com/comment/84774170
downvote count: 0
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84749172
comment on: http://stackoverflow.com/q/48851097
has text: @IljaEverilä Thank you. I posted my result. Would you mind to take a look at it?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84863205
has text: @DanielRoseman I have added in the traceback
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48926352

http://stackoverflow.com/a/48848123
has comment: http://stackoverflow.com/comment/84749508
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84700695
score: 1
has comment: http://stackoverflow.com/comment/84802613
answers question: http://stackoverflow.com/q/48847980
downvote count: 0
has body: Apparently I cant comment... but I am having this exact same issue! Tensorflow has conflicting requirements for install. Cuda Tookit V8.0 is the last supported version for cudnn V6.0

http://stackoverflow.com/comment/84832414
type: Comment
comment on: http://stackoverflow.com/a/48912587
score: 1
type: AnswerComment
has text: the slash '/' indicates that you are accessing/posting to this directory directly as it is there and not a file (which does not exist)

http://stackoverflow.com/comment/84732002
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48864407
has text: You can pass the variables as arguments to `callingValues` like `callingValues(hi, name, isTrue)` and then use them like normal variables.

http://stackoverflow.com/a/48906493
answers question: http://stackoverflow.com/q/48888713
type: Answer
has body: the problem is that url doesn't ends up with /
score: 0

http://stackoverflow.com/q/48952153
has title: What is the recommended way of running a web application?
has comment: http://stackoverflow.com/comment/84921608
tagged with: daemon
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/473620
tagged with: python
has comment: http://stackoverflow.com/comment/84911003
has comment: http://stackoverflow.com/comment/84910968
has comment: http://stackoverflow.com/comment/84910881
has comment: http://stackoverflow.com/comment/84914668
answer count: 0
type: Question
has body: I'm doing a Python webserver (e.g. using Flask or Bottle, etc.), and I would like to start it, and be able to close the SSH terminal and let it running. Which way would be the pythonic recommended way to do it? Create a daemon, and use python myapp.py start, python myapp.py stop. However the python-daemon module has nearly no doc, doesn't support triggering an action just before exiting (I added a few lines to it to support it), so it's a bit a hack of an undocumented/not-really-maintained module, so even if it works, I'm not 100% happy with it. Use nohup python myapp.py &amp;, but then the drawback is that you have to ps aux |grep py, then find the relevant PID and kill 12345 to stop it. Here again, it doesn't allow to do actions before stopping (e.g. save the database to disk, etc.), so it's not a very nice solution. screen -dmS myapp python myapp.py to start, then you can log out from SSH terminal. Then later you can connect to it again with screen -r myapp, and then CTRL+C can stop it (provided KeyboardInterrupt is well handled). That's what I would use currently. But I'm not sure if using screen to let a server run forever is a good idea (what happens if the logging is really verybose? also is there a risk that introducing the screen layer would make it bloated?) Another cleaner solution? I hope there's a cleaner solution than 1, 2, 3 that all have drawbacks. Note: I would like to avoid installing new managers (upstart or supervisor), and do it with the least number of tools possible, to avoid new layers of complexity.
has comment: http://stackoverflow.com/comment/84910993
tagged with: server
score: 0

http://stackoverflow.com/q/48953985
type: AnsweredQuestion
tagged with: keyword
type: Question
has answer: http://stackoverflow.com/a/48954081
has body: I have a string like this, my_str ='·in this match, dated may 1, 2013 (the "the match") is between brooklyn centenniel, resident of detroit, michigan ("champion") and kamil kubaru, the challenger from alexandria, virginia ("underdog").' Now, I want to extract the current champion and the underdog using keywords champion and underdog . What is really challenging here is both contender's names appear before the keyword inside parenthesis. I want to use regular expression and extract information. Following is what I did, champion = re.findall(r'("champion"[^.]*.)', my_str) print(champion) &gt;&gt; ['"champion") and kamil kubaru, the challenger from alexandria, virginia ("underdog").'] underdog = re.findall(r'("underdog"[^.]*.)', my_str) print(underdog) &gt;&gt;['"underdog").'] However, I need the results, champion as: brooklyn centenniel, resident of detroit, michigan and the underdog as: kamil kubaru, the challenger from alexandria, virginia How can I do this using regular expression? (I have been searching, if I could go back couple or words from the keyword to get the result I want, but no luck yet) Any help or suggestion would be appreciated.
tagged with: matching
has title: Extract words/sentence that occurs before a keyword from a string - Python
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48954081
has answer: http://stackoverflow.com/a/48954197
favorite count: 0
upvote count: 2
possible better answer: http://stackoverflow.com/a/48954197
tagged with: python
tagged with: regex
score: 2

http://stackoverflow.com/comment/84754915
has text: set is un-ordered so the index can change every time you run your code.
score: 0
comment on: http://stackoverflow.com/q/48875455
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84638659
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48817294
has text: but it has this error: `File "test.py", line 1 def p(st : str) -> bool: ^ SyntaxError: invalid syntax`
score: 0

http://stackoverflow.com/q/48827917
has comment: http://stackoverflow.com/comment/84666943
has comment: http://stackoverflow.com/comment/84668560
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84659723
has comment: http://stackoverflow.com/comment/84669987
has comment: http://stackoverflow.com/comment/84679300
score: 0
has body: Input File CSV data link. My Python code is as pasted beneath. The curve smoothing technique does not really seem to be working. As I plot the smoothed curve upon the parent data, they overlap exactly. Could someone please help me in resolving the issue please. The code uses the Savitzky_Golay algorithm.The code extracts the x,y axis data from a csv file and is formulated to suite the required data type needed for the Savitzky_Golay function call import numpy as np import csv from math import factorial import itertools import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter #from scipy.interpolate import spline #import openpyxl #import pandas as pd #from scipy.interpolate import interp1d def savitzky_golay(y, window_size, order, deriv=0, rate=1): r"""Smooth (and optionally differentiate) data with a Savitzky-Golay filter. The Savitzky-Golay filter removes high frequency noise from data. It has the advantage of preserving the original shape and features of the signal better than other types of filtering approaches, such as moving averages techniques. Parameters ---------- y : array_like, shape (N,) the values of the time history of the signal. window_size : int the length of the window. Must be an odd integer number. order : int the order of the polynomial used in the filtering. Must be less then `window_size` - 1. deriv: int the order of the derivative to compute (default = 0 means only smoothing) Returns ------- ys : ndarray, shape (N) the smoothed signal (or it's n-th derivative). Notes ----- The Savitzky-Golay is a type of low-pass filter, particularly suited for smoothing noisy data. The main idea behind this approach is to make for each point a least-square fit with a polynomial of high order over a odd-sized window centered at the point. Examples -------- t = np.linspace(-4, 4, 500) y = np.exp( -t**2 ) + np.random.normal(0, 0.05, t.shape) ysg = savitzky_golay(y, window_size=31, order=4) import matplotlib.pyplot as plt plt.plot(t, y, la…
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84671352
has title: Python Curve Smoothing using Savitzky_Golay - issue
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84670000
tagged with: curve-fitting
tagged with: python
has answer: http://stackoverflow.com/a/68016522

http://stackoverflow.com/comment/84656947
has text: How does this school system work? Did they actually ask you to create such regex? Seems so pointless. If not, what is so special about this line so that it's the only one allowed to be edited?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48826204

http://stackoverflow.com/comment/84649122
type: QuestionComment
comment on: http://stackoverflow.com/q/48822715
score: 0
has text: Do you mean you want the left side of the window to be fixed and the right side to move to the right?
type: Comment

http://stackoverflow.com/a/48896485
type: Answer
answers question: http://stackoverflow.com/q/48887515
upvote count: 1
score: 1
has body: The n of evalf gives the first n significant digits of x (measured from the left). If you use x.round(3) it will round x to the nth digit from the decimal point and can be positive (right of decimal pt) or negative (left of decimal pt). &gt;&gt;&gt; for x in '0.0065, 1.0065, 10.0065, 100.0065'.split(', '): ... print S(x).round(3) 0.006 1.006 10.007 100.007 &gt;&gt;&gt; int(S(12345).round(-2)) 12300
downvote count: 0

http://stackoverflow.com/comment/84779246
score: 1
comment on: http://stackoverflow.com/a/48872376
type: AnswerComment
has text: @ErroriSalvo, thanks, that was a typo when I copied my answer from the text editor to SO
type: Comment

http://stackoverflow.com/a/48956629
has body: You can add __init__.py to the folders where you import things. For instance, I did this: $ mkdir -p bucha/bucha $ touch bucha/bucha/Bucha.py $ subl . $ touch bucha/bucha/__init__.py $ touch bucha/__init__.py $ touch __init__.py $ python -c 'import bucha' bucha/bucha/__init__.py bucha/bucha/Bucha.py bucha/__init__.py These are the contents of the files: $ cat bucha/bucha/Bucha.py print(__file__) $ cat bucha/bucha/__init__.py print(__file__)$ $ cat bucha/__init__.py import bucha.Bucha as Bucha print(__file__) $ cat __init__.py from bucha import Bucha print(__file__)
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48956557
score: 1
answers question: http://stackoverflow.com/q/48956557
has comment: http://stackoverflow.com/comment/84920532
downvote count: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/84844424
comment on: http://stackoverflow.com/q/48917381
has text: Possible duplicate of [Extracting a region of interest from an image file without reading the entire image](https://stackoverflow.com/questions/48281086/extracting-a-region-of-interest-from-an-image-file-without-reading-the-entire-im)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/49094345
accepted answer of: http://stackoverflow.com/q/48816612
upvote count: 6
answers question: http://stackoverflow.com/q/48816612
type: AcceptedAnswer
has body: Firstly, you don’t need the colons after USER, PASS, SEND and END. Also, the challenge tells you you need to receive data after every send. Finally, you need to send the keywords and the data separately So: import socket clientsocket = ... clientsocket.connect(...) clientsocket.send(‘USER’) print(clientsocket.recv(1024)) clientsocket.send(‘aliensignal’) print(clientsocket.recv(1024)) #etc...
score: 6
type: Answer
downvote count: 0

http://stackoverflow.com/a/48915411
score: 0
accepted answer of: http://stackoverflow.com/q/48912747
type: Answer
answers question: http://stackoverflow.com/q/48912747
has body: input_arr = [ "New: Hello", "How are", "you", "New: I am", "fine" ] def merge_messages(input_arr): delimiter = "New" return [delimiter+x for x in " ".join(input_arr).split(delimiter) if x] print(merge_messages(input_arr)) However, I would highly recommend you take the advice given to you in the comments and read up on Python Strings. You can also view the Python string documentation here
type: AcceptedAnswer

http://stackoverflow.com/q/48963329
has comment: http://stackoverflow.com/comment/84945529
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/84932573
has comment: http://stackoverflow.com/comment/84986527
type: UnansweredQuestion
tagged with: python
has body: Code: #Importing the Keras libraries and packages from keras.models import Sequential from keras.layers import Conv2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense import keras.optimizers as optimizers #Initialising the CNN classifier = Sequential() #Convolution Layer classifier.add(Conv2D(32, (3, 3), input_shape = (32, 32, 3), activation = 'relu')) #Max Pooling classifier.add(MaxPooling2D(pool_size = (2, 2))) #Flattening classifier.add(Flatten()) #Full connection classifier.add(Dense(units = 128, activation = 'relu')) classifier.add(Dense(units = 1, activation = 'sigmoid')) # Compiling the CNN sgd = optimizers.SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True) classifier.compile(loss='mean_squared_error', optimizer=sgd, metrics = ['accuracy']) #Fitting the CNN to the images from keras.preprocessing.image import ImageDataGenerator train_datagen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True) test_datagen = ImageDataGenerator(rescale = 1./255) training_set = train_datagen.flow_from_directory('Oranges/training_set', target_size = (32, 32), batch_size = 32, class_mode = 'binary') test_set = test_datagen.flow_from_directory('Oranges/test_set', target_size = (32, 32), batch_size = 32, class_mode = 'binary') classifier.fit_generator(training_set, steps_per_epoch = 800, epochs = 25, validation_data = test_set, validation_steps = 62.5) classifier.save('my_model.h5') # creates a HDF5 file 'my_model.h5' The input is about 200 images belonging to 5 classes (vegetables). acc stays at around 18-19% although i let it train through the whole process (800 steps * 30 epochs with a batch size of 32). I tried messing with the optimizer settings(lr, decay), but nothing seems to really work for me. Any ideas what am I doing wrong?
score: 2
tagged with: conv-neural-network
has comment: http://stackoverflow.com/comment/84947130
answer count: 0
downvote count: 0
has title: Keras-based CNN acc stays at around 1/n% while training
tagged with: tensorflow
type: Question
tagged with: neural-network
has comment: http://stackoverflow.com/comment/84943495
upvote count: 2
has comment: http://stackoverflow.com/comment/84945444
has comment: http://stackoverflow.com/comment/84940182

http://stackoverflow.com/comment/84627671
has text: This is dramatically faster! Clever!
type: Comment
comment on: http://stackoverflow.com/a/48811778
score: 0
type: AnswerComment

http://stackoverflow.com/q/48829242
answer count: 2
has title: Checking the number of times a string occurs in another string
tagged with: python
has answer: http://stackoverflow.com/a/48829454
has answer: http://stackoverflow.com/a/48829373
has comment: http://stackoverflow.com/comment/84991944
downvote count: 4
upvote count: 0
type: UnansweredQuestion
score: -4
tagged with: iteration
has body: Currently, I have a code that tells me if a string is in another string. However, I do not want it to stop the moment it finds the string. Instead, I want it to continue and tell me the total number of time it duplicates. Eg. "110010","10" Expected answer: 2 Given answer: 1 Below is my code. def occurence(s1,s2): count == 0 if s2 in s1: count += 1 return count
favorite count: 0
type: Question

http://stackoverflow.com/q/48948200
has comment: http://stackoverflow.com/comment/84905555
has comment: http://stackoverflow.com/comment/84906309
type: Question
has comment: http://stackoverflow.com/comment/84903697
has body: I am new to Python/Flask.Here is my problem is, i did't use wt-forms for posting values to server.but, i am using wt-forms for editing the values.fortunately it's working.but problem is photo will not be displayed after editing the values.when i add the image in browser inspect elements that photo will be showed. it might be problem in template. can anyone help me.thanks for advanced. Here is the Template Code driver_edit.html name: photo: Aadhar: Here is the view.html code. name photo aadhar {% for values in driver %} {{values.name}} {{values.id}} **here it is working {{values.id}}** {{values.photo}} {{values.photo}} {% endfor %} Here is the Python code for posting values to database from web interface. def driver(request): file2=request.files['photo'] file3=request.files['aadhar'] if file2.filename and file3.filename == None: flash('No selected file') return redirect(request.url) filename='' if file2: filename = secure_filename(file2.filename) file2.save(os.path.join(app.config['UPLOAD_FOLDER'], file2.filename)) if file3: filename = secure_filename(file3.filename) file3.save(os.path.join(app.config['UPLOAD_FOLDER'], file3.filename)) newdriver=Driver(name=request.form['name'],photo=file2.filename,aadhar=file3.filename, status=request.form['status'],lastlogin=request.form['lastlogin']) sqlsession.add(newdriver) sqlsession.commit() @app.route('/static/driver') def driversearch(): if session['username']: return render_template('driversearching.html',user=session['username'],Truck_company=get_truckdetails().all()) else: flash('login first') return main() @app.route('/static/driverdetails') def driverdetails(): if session['username']: users=getdriver() if users.first()==None: return render_template('empty.html',user=session['username']) else: return render_template('driverdetails.html',user=session['username'],driver=users.all()) Here is the wtf forms code.py: class DriverForm(FlaskForm): name=StringField('name') photo=StringField('photo') aadhar=StringField('aadhar') @…
upvote count: 1
has comment: http://stackoverflow.com/comment/84904189
tagged with: flask
has comment: http://stackoverflow.com/comment/84904226
score: 0
downvote count: 1
has title: Image will not be displayed after editing the values with wt-forms in Flask
tagged with: python
favorite count: 0
answer count: 0
tagged with: flask-wtforms
type: UnansweredQuestion
tagged with: jinja2
has comment: http://stackoverflow.com/comment/84903393
has comment: http://stackoverflow.com/comment/84903857
has comment: http://stackoverflow.com/comment/84908114

http://stackoverflow.com/comment/84728234
type: Comment
has text: @l.b.dev in this case using a dict or a list or objects and `getattr` are the canonical solutions - "dynamic" variables are a terrible idea anyway.
type: AnswerComment
comment on: http://stackoverflow.com/a/48861909
score: 0

http://stackoverflow.com/comment/84749410
type: Comment
has text: @AbhishekGupta Basically you give df1 the same index as df2 (df2 has a longer index and thus df1 is filled with nans in the end).
comment on: http://stackoverflow.com/a/48872685
score: 0
type: AnswerComment

http://stackoverflow.com/q/48859118
answer count: 1
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84721694
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84721680
type: AnsweredQuestion
upvote count: 0
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84721727
type: Question
has comment: http://stackoverflow.com/comment/84721779
has body: I'm trying to return a HTTPResponse object that is prettified JSON. I know that the indent parameter for json only works when you're printing. And printing converts an argument to a string. So shouldn't the indent parameter work if I just str() on my JSON before returning it? def conversationview(request, convo_identification): data = InputInfo.objects.all() conversation_identification = convo_identification #conversation_id = {'conversation_id': []} header = {'conversation_id': '', 'messages': []} entry = {} output = {} for i in data: if str(i.conversation_id) == conversation_identification: header['conversation_id'] = i.conversation_id entry = {} entry['sender'] = i.name entry['message_body'] = i.message_body entry['date_created'] = str(i.created) header.get('messages').append(entry) #parsed = json.loads(header) convert_to_json = json.dumps(header, sort_keys=True, indent=4) output = str(convert_to_json) return HttpResponse(output)
accepted answer: http://stackoverflow.com/a/48860369
has comment: http://stackoverflow.com/comment/84721691
has comment: http://stackoverflow.com/comment/84721722
score: -1
has comment: http://stackoverflow.com/comment/84721704
has title: Using HTTPResponse to return prettified dictionary
has answer: http://stackoverflow.com/a/48860369
has comment: http://stackoverflow.com/comment/84721739

javascript
tags question: http://stackoverflow.com/q/48846504
tags question: http://stackoverflow.com/q/48832907
tags question: http://stackoverflow.com/q/48853555
tags question: http://stackoverflow.com/q/48869903
tags question: http://stackoverflow.com/q/48862708
tags question: http://stackoverflow.com/q/48917869
tags question: http://stackoverflow.com/q/48954359
tags question: http://stackoverflow.com/q/48891610
tag name: javascript
tags question: http://stackoverflow.com/q/48935398
tags question: http://stackoverflow.com/q/48897414
tags question: http://stackoverflow.com/q/48829089
tags question: http://stackoverflow.com/q/48912505
tags question: http://stackoverflow.com/q/48849430
tags question: http://stackoverflow.com/q/48956443
tags question: http://stackoverflow.com/q/48814810
tags question: http://stackoverflow.com/q/48853525
tags question: http://stackoverflow.com/q/48878292
tags question: http://stackoverflow.com/q/48845017
tags question: http://stackoverflow.com/q/48827166
type: Tag
tags question: http://stackoverflow.com/q/48939740
tags question: http://stackoverflow.com/q/48853088
tags question: http://stackoverflow.com/q/48806037
tags question: http://stackoverflow.com/q/48960931
tags question: http://stackoverflow.com/q/48918712
tags question: http://stackoverflow.com/q/48959547
tags question: http://stackoverflow.com/q/48896407
tags question: http://stackoverflow.com/q/48840810
tags question: http://stackoverflow.com/q/48819513
tags question: http://stackoverflow.com/q/48884346
tags question: http://stackoverflow.com/q/48912993
tags question: http://stackoverflow.com/q/48867072
tags question: http://stackoverflow.com/q/48852769
tags question: http://stackoverflow.com/q/48911754
tags question: http://stackoverflow.com/q/48877944
tags question: http://stackoverflow.com/q/48940054
tags question: http://stackoverflow.com/q/48860520
tags question: http://stackoverflow.com/q/48820483
tags question: http://stackoverflow.com/q/48879205
tags question: http://stackoverflow.com/q/48935719

http://stackoverflow.com/a/62038586
has comment: http://stackoverflow.com/comment/109737414
has comment: http://stackoverflow.com/comment/109724910
type: Answer
has comment: http://stackoverflow.com/comment/109725531
upvote count: 2
has body: df1 = df.groupby('lvl_1')['value'].agg(['min','max',("custom_quantile",lambda x: x.quantile(q))]) for q=0.22, the output is: min max custom_quantile lvl_1 di 0.275401 0.530000 0.294589 fi 0.054363 0.848818 0.136555 This is called named aggregation and is documented here.
downvote count: 1
answers question: http://stackoverflow.com/q/48843887
score: 1

http://stackoverflow.com/tag/json
tags question: http://stackoverflow.com/q/48839844
tags question: http://stackoverflow.com/q/48838207
tags question: http://stackoverflow.com/q/48955301
tags question: http://stackoverflow.com/q/48819474
tags question: http://stackoverflow.com/q/48952350
tags question: http://stackoverflow.com/q/48845256
tags question: http://stackoverflow.com/q/48883998
tags question: http://stackoverflow.com/q/48856275
tags question: http://stackoverflow.com/q/48918008
tags question: http://stackoverflow.com/q/48929787
tags question: http://stackoverflow.com/q/48953184
tags question: http://stackoverflow.com/q/48900647
tags question: http://stackoverflow.com/q/48853499
tags question: http://stackoverflow.com/q/48896070
tags question: http://stackoverflow.com/q/48938042
tags question: http://stackoverflow.com/q/48809126
tags question: http://stackoverflow.com/q/48931840
tags question: http://stackoverflow.com/q/48847036
tags question: http://stackoverflow.com/q/48827688
tags question: http://stackoverflow.com/q/48926974
tags question: http://stackoverflow.com/q/48871670
tags question: http://stackoverflow.com/q/48906246
tags question: http://stackoverflow.com/q/48853316
type: Tag
tags question: http://stackoverflow.com/q/48835776
tags question: http://stackoverflow.com/q/48844705
tags question: http://stackoverflow.com/q/48926576
tags question: http://stackoverflow.com/q/48841838
tags question: http://stackoverflow.com/q/48842893
tags question: http://stackoverflow.com/q/48945639
tags question: http://stackoverflow.com/q/48924123
tags question: http://stackoverflow.com/q/48840378
tags question: http://stackoverflow.com/q/48846091
tags question: http://stackoverflow.com/q/48934100
tags question: http://stackoverflow.com/q/48927600
tags question: http://stackoverflow.com/q/48917035
tags question: http://stackoverflow.com/q/48817143
tags question: http://stackoverflow.com/q/48849121
tags question: http://stackoverflow.com/q/48955821
tag name: json
tags question: http://stackoverflow.com/q/48845223
tags question: http://stackoverflow.com/q/48910302
tags question: http://stackoverflow.com/q/48906527
tags question: http://stackoverflow.com/q/48949526
tags question: http://stackoverflow.com/q/48853899
tags question: http://stackoverflow.com/q/48808839
tags question: http://stackoverflow.com/q/48859118
tags question: http://stackoverflow.com/q/48907061
tags question: http://stackoverflow.com/q/48865303
tags question: http://stackoverflow.com/q/48850130
tags question: http://stackoverflow.com/q/48897535
tags question: http://stackoverflow.com/q/48858167
tags question: http://stackoverflow.com/q/48896341
tags question: http://stackoverflow.com/q/48867296
tags question: http://stackoverflow.com/q/48868626
tags question: http://stackoverflow.com/q/48891603
tags question: http://stackoverflow.com/q/48836484
tags question: http://stackoverflow.com/q/48884116
tags question: http://stackoverflow.com/q/48837130
tags question: http://stackoverflow.com/q/48842543
tags question: http://stackoverflow.com/q/48932965
tags question: http://stackoverflow.com/q/48941147
tags question: http://stackoverflow.com/q/48836082
tags question: http://stackoverflow.com/q/48894501

http://stackoverflow.com/a/48849448
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84702883
has body: You need to decode the text that's in your file. Assuming your file is encoded as UTF-8: text=f.read().decode('utf-8')
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84702578
accepted answer of: http://stackoverflow.com/q/48849394
has comment: http://stackoverflow.com/comment/84702695
answers question: http://stackoverflow.com/q/48849394
upvote count: 1

http://stackoverflow.com/comment/84985205
score: 0
comment on: http://stackoverflow.com/q/48893403
has text: @matisetorm I solved the problem by splitting the string between (' '), making a float of the input and cutting it in 2 strings of 3 values.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84843464
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48918398
has text: in my `environ` instance, there is no such 'CONDA_DEFAULT_ENV' key
score: 0

http://stackoverflow.com/comment/84859858
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48925311
has text: I want to do text-classification into 3 classes (a1,a2,a3) and I want to get rid of data that do not fall into those 3 classes first. I have only 1 feature (text-content). So this is really my entire code. I havn't add my first classifier yet because I dont know how to add more to the pipeline.
score: 0

http://stackoverflow.com/q/48953184
type: Question
score: 0
tagged with: rest
has title: Python API Call: KeyError
has comment: http://stackoverflow.com/comment/84995020
tagged with: python
tagged with: keyerror
answer count: 0
has body: I'm working with a python script that performs a web API call to one system (ArchivesSpace), extracts JSON data from it, uses that data to search another system via its API (Archive-It), then extracts the result before pushing it into the original system. When I run the script, it seems to perform the initial API call just fine, but hangs either when performing the second or when hitting line 730 in aspace.py (I'm not sure which). I get the following error message: Traceback (most recent call last): File ".\describingWebArchives.py", line 81, in &lt;module&gt; for result in AS.withSubject(session, repo, aitSubject, aitSource, aspaceLogin): File "build\bdist.win32\egg\archives_tools\aspace.py", line 730, in withSubject if result["source_enum_s"][0].lower() == str(source).lower(): KeyError: 'source_enum_s' I think that the KeyError indicates that source_enum_s is an unrecognized library term, but that's as far as I've gotten. I'd really appreciate some help in either fixing or understanding this!
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84913479
has comment: http://stackoverflow.com/comment/85137229
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/comment/84742440
score: 0
has text: Reproduced the error. Tweets are saved to the db just fine. Maybe it's necessary to use a specific version of python and/or the used packages?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48868713

http://stackoverflow.com/comment/84793359
type: AnswerComment
has text: may be `x!='' and y!=''` will be more explicit (+1 though for zip + enumerate)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48893784

http://stackoverflow.com/q/48821582
has comment: http://stackoverflow.com/comment/84668329
score: 0
has comment: http://stackoverflow.com/comment/84665899
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/84649441
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has title: RMSE error doesn't converge towards the same value depending on the train/test ratio
has body: I am trying to find a reliable testing method to compute the error of my model / training parameters, but I am seeing weird results when I play with the train/test ratio. When I change the ratio of my train/test data, the RMSE converges towards different values, see below: You can see the test ratio on the top-right corner. Zoomed: After 50K iteration, it doesn't converge towards the same value. Here is the code: import time import sys import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.linear_model import Lasso from sklearn.model_selection import train_test_split from sklearn.utils import shuffle np.random.seed(int(time.time())) def seed(): np.random.randint(2**32-1) n_scores_per_test = 50000 test_ratios = [.1, .2, .4, .6, .8] model = Lasso(alpha=0.0005, random_state=seed(), tol=0.00001, copy_X=True) # load our training data train = pd.read_csv('train.csv') X = train'OverallCond'.values y = np.log(train['SalePrice'].values) # custom RMSE def rmse(y_predicted, y_actual): tmp = np.power(y_actual - y_predicted, 2) / y_actual.size return np.sqrt(np.sum(tmp, axis=0)) for test_ratio in test_ratios: print 'Testing test ratio:', test_ratio scores = [] avg_scores = [] for i in range(n_scores_per_test): if i % 200 == 0: print i, '/', n_scores_per_test X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=test_ratio, random_state=seed()) model.fit(X_train, y_train) y_pred = model.predict(X_test) scores.append(rmse(y_pred, y_test)) avg_scores.append(np.array(scores).mean()) plt.plot(avg_scores, label=str(test_ratio)) plt.legend(loc='upper right') plt.show() Any idea why they don't all converge nicely together? See https://github.com/benji/rmse_convergence/ UPDATE: Use selection=random for Lasso using random_state in Lasso using random_state train_test_split removed redundant shuffle() setting low tol on Lasso model
has comment: http://stackoverflow.com/comment/84667203
answer count: 0
has comment: http://stackoverflow.com/comment/84665873
has comment: http://stackoverflow.com/comment/84667741
has comment: http://stackoverflow.com/comment/84668288
type: Question
has comment: http://stackoverflow.com/comment/85046115
tagged with: lasso-regression
has comment: http://stackoverflow.com/comment/84653630
has comment: http://stackoverflow.com/comment/85046236

http://stackoverflow.com/comment/84729508
type: QuestionComment
has text: @RishatMuhametshin It's not what I want. Look what I've done, it's the same thing, but it doesn't return what I would like to get.
comment on: http://stackoverflow.com/q/48863186
score: 0
type: Comment

http://stackoverflow.com/q/48835270
has body: I am not familiarized with glob pattern style and based on this tutorial it says glob is case sensitive. However, when I use the glob module from Python, it seems glob.glob('./M*') and glob.glob('./m*') return the same results, that is, Python's glob is case-insensitive, see below (I print results together to ensure that they are executed in tandem), How do I differentiate between upper case and lower case? Do I have to resort to string methods for this sake?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84689919
has answer: http://stackoverflow.com/a/48835442
has comment: http://stackoverflow.com/comment/84689883
tagged with: glob
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84675477
has comment: http://stackoverflow.com/comment/84675299
tagged with: python
upvote count: 6
type: Question
score: 6
has comment: http://stackoverflow.com/comment/84675447
has title: Is Unix glob style pattern case sensitive in Python's glob module?
answer count: 1
downvote count: 0
tagged with: unix
favorite count: 0

http://stackoverflow.com/comment/84797153
comment on: http://stackoverflow.com/q/48887461
has text: @hpaulj Interesting... On my android phone `method2()` is a bit slower as well but both methods run about the same (within margin of error) if third dimension is decreased to 100 or 10.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84640592
comment on: http://stackoverflow.com/a/48818311
score: 0
type: AnswerComment
type: Comment
has text: Look at what `str(set1)` does.. it coverts your set into a string: "{'cat', ':dog', 'mouse'}". You then apply some re logic, but then you have to convert the resulting string back to a set again. This is expensive and not what you want.

http://stackoverflow.com/q/48849394
score: 0
answer count: 1
tagged with: arabic
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48849448
has body: i use python 2.7.8 , and i try to get the origin/root of the word using built in function called stem(param), but the list i use was in hex and when i run the program there is an error occurred. here is the code : from nltk.stem.isri import ISRIStemmer st = ISRIStemmer() f=open("Hassan.txt","rU") text=f.read() text1=text.split() for i in range(1,numOfWords): #numOfWords is var that contain the num of print st.stem(text1[i]) # words in list (text1) and the output was as here: Warning (from warnings module): File "C:\Python27\lib\site-packages\nltk\stem\isri.py", line 154 if token in self.stop_words: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal Traceback (most recent call last): File "C:\Python27\Lib\mycorpus.py", line 81, in &lt;module&gt; print st.stem(text1[i]) File "C:\Python27\lib\site-packages\nltk\stem\isri.py", line 156, in stem token = self.pre32(token) # remove length three and length two prefixes in this order File "C:\Python27\lib\site-packages\nltk\stem\isri.py", line 198, in pre32 if word.startswith(pre3): UnicodeDecodeError: 'ascii' codec can't decode byte 0xc8 in position 0: ordinal not in range(128) How can i solve this problem ?!
type: Question
tagged with: nltk
has title: How can i decode bytes in a list in python?
tagged with: python-unicode
accepted answer: http://stackoverflow.com/a/48849448
tagged with: decode

http://stackoverflow.com/comment/84985584
type: Comment
has text: Note that "complexity" is not the same as "wallclock runtime".
comment on: http://stackoverflow.com/a/48951650
type: AnswerComment
score: 0

http://stackoverflow.com/q/48835765
has body: I am asking for help in last resort, I have a problem with my code that is driving me crazy. I work with both Python 2.7.6 and Python 3.4.3 on Ubuntu 14.04 with the following very simple part of code that I took from there password generator urandom import os def random_password(length=20, symbols='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@$^_+&amp;'): password = [] for i in map(lambda x: int(len(symbols)*x/255.0), os.urandom(length)): password.append(symbols[i]) return ''.join(password) random_password() password = random_password() print(password) This part of code works with python 3.4.3. but randomly give the following error every 2 or 3 run: Traceback (most recent call last): File "/home/jsmith/Documents/PythonProjects/MainFile", line 12, in &lt;module&gt; IotaSeed = Gen_Seed() File "/home/jsmith/Documents/PythonProjects/MainFile", line 7, in Gen_Seed IotaSeed.append(symbols[i]) IndexError: string index out of range And with Python 2.7.6, it doesn't work at all and give the following error : Traceback (most recent call last): File "PWDGEN.py", line 10, in &lt;module&gt; random_password() File "PWDGEN.py", line 6, in random_password for i in map(lambda x: int(len(symbols)*x/255.0), os.urandom(length)): File "PWDGEN.py", line 6, in &lt;lambda&gt; for i in map(lambda x: int(len(symbols)*x/255.0), os.urandom(length)): TypeError: unsupported operand type(s) for /: 'str' and 'float' I understand how lambda and map works but I just can't find a solution and I can't switch to python 3.4.3 because I coded my main program with 2.7. What can I do to make it works under python 2.7 and avoid the "string index out of range" error seen in 3.4.3? Thanks, PGriffin.
score: 3
has answer: http://stackoverflow.com/a/48838018
has comment: http://stackoverflow.com/comment/84676421
has comment: http://stackoverflow.com/comment/84676798
type: Question
downvote count: 0
answer count: 1
has title: map() lambda() unsupported operand only with python 2.7.6
favorite count: 0
has comment: http://stackoverflow.com/comment/84676633
has comment: http://stackoverflow.com/comment/84676585
tagged with: python
has comment: http://stackoverflow.com/comment/84676528
tagged with: operand
has comment: http://stackoverflow.com/comment/84677050
has comment: http://stackoverflow.com/comment/84676680
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84676579
has comment: http://stackoverflow.com/comment/84676689
tagged with: dictionary
tagged with: lambda

http://stackoverflow.com/q/48928196
tagged with: opencv
has title: python opencv SVM train error
downvote count: 0
score: 1
tagged with: svm
type: Question
upvote count: 1
has body: I want to build a very simple SVM classifier. So i wrote code : import cv2 import numpy as np # Generate data and labels trainData = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=np.float32) trainLabels = np.array([0, 1, 0, 1], dtype=np.float32) # Create SVM svm = cv2.ml.SVM_create() svm.setType(cv2.ml.SVM_C_SVC) svm.setKernel(cv2.ml.SVM_RBF) svm.setC(2) svm.setGamma(2) # Train : error occurs here. svm.train(trainData, cv2.ml.ROW_SAMPLE, trainLabels) # Predict : I don't know if it is appropriate for printing output. print(svm.predict(np.array([0, 1]))) However, this error occurs when running. File "C:/.../.py", line 13, in &lt;module&gt; svm.train(trainData, cv2.ml.ROW_SAMPLE, trainLabels) cv2.error: C:\ci\opencv_1512688052760\work\modules\ml\src\svm.cpp:1624: error: (-5) in the case of classification problem the responses must be categorical; either specify varType when creating TrainData, or pass integer responses in function cv::ml::SVMImpl::train I referred to here : https://www.learnopencv.com/handwritten-digits-classification-an-opencv-c-python-tutorial/ What's the problem?
favorite count: 0
has comment: http://stackoverflow.com/comment/84863504
answer count: 0
has comment: http://stackoverflow.com/comment/84863011
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/84753678
has text: Just giving my 2 cents: I am using https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/gan. For the loss part, generator is just trying to minimize `min log (1-D)` which means the generator hopes to generate images that the discriminator will think they are true images.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48870598

http://stackoverflow.com/comment/84673652
type: Comment
score: 0
has text: @khelwood i cannot declare self in that method parameter (why it got removed). by adding it to `def context(self, func, *args, **kwargs):` we get: `TypeError: context() missing 1 required positional argument: 'func'`
type: QuestionComment
comment on: http://stackoverflow.com/q/48834392

http://stackoverflow.com/comment/84773791
type: Comment
comment on: http://stackoverflow.com/a/48884590
has text: Thanks Slam. I am using unigrams and bigrams but I need to add words which are not present in unigrams.txt and bigrams.txt.Can you suggest me any other method to add new words?
score: 0
type: AnswerComment

http://stackoverflow.com/a/48914602
upvote count: 1
has body: Consider using dictionary: filearrays = { '.csv':[],'.txt':[],'.jpg':[],'.png':[] } for root, dirs, files in os.walk(folderpath): for file in files: filename, fileext = os.path.splitext(file) if fileext in filearrays: filearrays[fileext].append(os.path.join(root, file))
answers question: http://stackoverflow.com/q/48914481
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/48920861
has comment: http://stackoverflow.com/comment/84847920
favorite count: 0
score: 0
tagged with: parsing
has title: How to parse Etherscan?
has comment: http://stackoverflow.com/comment/84847921
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48920862
accepted answer: http://stackoverflow.com/a/48920862
type: Question
has body: How can I parse every single page for eth addresses from https://etherscan.io/token/generic-tokenholders2?a=0x6425c6be902d692ae2db752b3c268afadb099d3b&amp;s=0&amp;p=1 ? Then add it to .txt .
has comment: http://stackoverflow.com/comment/84847922
answer count: 1

arrays
tags question: http://stackoverflow.com/q/48853179
tags question: http://stackoverflow.com/q/48953844
tags question: http://stackoverflow.com/q/48827725
tags question: http://stackoverflow.com/q/48867997
tags question: http://stackoverflow.com/q/48895892
tags question: http://stackoverflow.com/q/48842500
type: Tag
tags question: http://stackoverflow.com/q/48815767
tags question: http://stackoverflow.com/q/48876162
tags question: http://stackoverflow.com/q/48873896
tags question: http://stackoverflow.com/q/48825114
tags question: http://stackoverflow.com/q/48930505
tags question: http://stackoverflow.com/q/48909069
tags question: http://stackoverflow.com/q/48944185
tags question: http://stackoverflow.com/q/48845158
tags question: http://stackoverflow.com/q/48891675
tags question: http://stackoverflow.com/q/48836873
tags question: http://stackoverflow.com/q/48843120
tags question: http://stackoverflow.com/q/48889370
tags question: http://stackoverflow.com/q/48940905
tags question: http://stackoverflow.com/q/48948308
tags question: http://stackoverflow.com/q/48934811
tags question: http://stackoverflow.com/q/48962312
tags question: http://stackoverflow.com/q/48855788
tags question: http://stackoverflow.com/q/48942663
tags question: http://stackoverflow.com/q/48813291
tags question: http://stackoverflow.com/q/48865461
tags question: http://stackoverflow.com/q/48918739
tags question: http://stackoverflow.com/q/48804698
tags question: http://stackoverflow.com/q/48940039
tags question: http://stackoverflow.com/q/48872795
tags question: http://stackoverflow.com/q/48916582
tags question: http://stackoverflow.com/q/48846876
tags question: http://stackoverflow.com/q/48895906
tags question: http://stackoverflow.com/q/48847999
tags question: http://stackoverflow.com/q/48896964
tags question: http://stackoverflow.com/q/48948495
tags question: http://stackoverflow.com/q/48855272
tags question: http://stackoverflow.com/q/48881613
tags question: http://stackoverflow.com/q/48843749
tags question: http://stackoverflow.com/q/48952443
tags question: http://stackoverflow.com/q/48928944
tags question: http://stackoverflow.com/q/48864890
tag name: arrays
tags question: http://stackoverflow.com/q/48906527
tags question: http://stackoverflow.com/q/48844705
tags question: http://stackoverflow.com/q/48875590
tags question: http://stackoverflow.com/q/48876018
tags question: http://stackoverflow.com/q/48819547
tags question: http://stackoverflow.com/q/48932659
tags question: http://stackoverflow.com/q/48853311
tags question: http://stackoverflow.com/q/48847417
tags question: http://stackoverflow.com/q/48892178
tags question: http://stackoverflow.com/q/48842037
tags question: http://stackoverflow.com/q/48943285
tags question: http://stackoverflow.com/q/48807297
tags question: http://stackoverflow.com/q/48893403
tags question: http://stackoverflow.com/q/48880819
tags question: http://stackoverflow.com/q/48938086
tags question: http://stackoverflow.com/q/48816718
tags question: http://stackoverflow.com/q/48896441
tags question: http://stackoverflow.com/q/48933024
tags question: http://stackoverflow.com/q/48895802
tags question: http://stackoverflow.com/q/48923565
tags question: http://stackoverflow.com/q/48914481
tags question: http://stackoverflow.com/q/48858600
tags question: http://stackoverflow.com/q/48858377
tags question: http://stackoverflow.com/q/48887198
tags question: http://stackoverflow.com/q/48921374
tags question: http://stackoverflow.com/q/48872582
tags question: http://stackoverflow.com/q/48893893
tags question: http://stackoverflow.com/q/48921783
tags question: http://stackoverflow.com/q/48864197
tags question: http://stackoverflow.com/q/48884965
tags question: http://stackoverflow.com/q/48896900
tags question: http://stackoverflow.com/q/48868550
tags question: http://stackoverflow.com/q/48862244
tags question: http://stackoverflow.com/q/48891298
tags question: http://stackoverflow.com/q/48816854
tags question: http://stackoverflow.com/q/48900470

http://stackoverflow.com/comment/84713923
has text: I have updated my question with the problem I am facing with your suggestion. Could you see why is that happening? Thanks
comment on: http://stackoverflow.com/a/48853513
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84773765
has text: Sorry both, my code was wrong.. I fixed it and added more information.
comment on: http://stackoverflow.com/q/48883863
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84707191
type: QuestionComment
comment on: http://stackoverflow.com/q/48851845
score: 0
has text: You have a encoding problem at hand. Look at [unicodedecodeerror-when-using-python-2-x-unicodecsv](https://stackoverflow.com//questions/25062937/unicodedecodeerror-when-using-python-2-x-unicodecsv) and [unicodedecodeerror-when-reading-a-text-file](https://stackoverflow.com/questions/30777370/unicodedecodeerror-when-reading-a-text-file) answers to try to solve it. They are not perfect fits but help you out non the less at deciding which codec your file needs
type: Comment

http://stackoverflow.com/comment/84692731
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48844024
has text: Which Keras and TF versions are you using?
score: 0

http://stackoverflow.com/comment/84721722
comment on: http://stackoverflow.com/q/48859118
type: Comment
has text: I assumed that you were getting error while prettifying.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48871733
score: 0
type: AcceptedAnswer
has body: I think I have solved the problem by adding an extra step in the loop that replaces the masked values by np.NaN using ma.filled (https://docs.scipy.org/doc/numpy/reference/routines.ma.html): SIF_year = np.ndarray((SIF_year0.shape)) for i in range(0,SIF_year0.shape[0]): SIF_test = np.ma.array(SIF_year0[i,:,:], mask = np.logical_not(mask_global_land)) SIF_year[i,:,:] = np.ma.filled(SIF_test, np.nan)
type: Answer
accepted answer of: http://stackoverflow.com/q/48871383
answers question: http://stackoverflow.com/q/48871383

http://stackoverflow.com/comment/84919254
comment on: http://stackoverflow.com/a/48937066
type: AnswerComment
score: 0
type: Comment
has text: Q1: No, definitely not. I meant that, if there is no entry in the dictionary for the id then an entry is created for that id and then the value of version from the current line is put in that entry. Q2: You should, please, show us your actual data so that we know precisely what you mean.

http://stackoverflow.com/comment/84656701
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48822570
type: AnswerComment
has text: Thanks! I am a noobie and this example helped me a lot, but I don't know how to transform my code to integrate that functionality. I suppose I need to introduce my code into a "def main():", but I don't know how to do that. If you could please help me in that regard, I'd be very grateful

recursion
type: Tag
tags question: http://stackoverflow.com/q/48896531
tags question: http://stackoverflow.com/q/48856743
tags question: http://stackoverflow.com/q/48837953
tag name: recursion
tags question: http://stackoverflow.com/q/48957432
tags question: http://stackoverflow.com/q/48831066
tags question: http://stackoverflow.com/q/48879495
tags question: http://stackoverflow.com/q/48942587
tags question: http://stackoverflow.com/q/48948745
tags question: http://stackoverflow.com/q/48806728
tags question: http://stackoverflow.com/q/48912564
tags question: http://stackoverflow.com/q/48941381
tags question: http://stackoverflow.com/q/48879229
tags question: http://stackoverflow.com/q/48918284
tags question: http://stackoverflow.com/q/48872887
tags question: http://stackoverflow.com/q/48893231
tags question: http://stackoverflow.com/q/48823833
tags question: http://stackoverflow.com/q/48846953

http://stackoverflow.com/q/48865396
accepted answer: http://stackoverflow.com/a/48865859
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84734476
type: Question
tagged with: matplotlib
has title: Matplotlib needs careful timing? (Or is there a flag to show plotting is done?)
score: 5
has comment: http://stackoverflow.com/comment/84734292
has body: The following code does not work as expected: import matplotlib.pyplot as plt plt.plot(range(100000), '.') plt.draw() ax = plt.gca() lblx = ax.get_xticklabels() lblx[1]._text = 'hello!' ax.set_xticklabels(lblx) plt.draw() plt.show() I'm getting the following figure: I imagine that the reason is that the automatic xticklabels did not have time to be fully created when get_xticklabels() was called. And indeed, by adding plt.pause(1) import matplotlib.pyplot as plt plt.plot(range(100000), '.') plt.draw() plt.pause(1) ax = plt.gca() lblx = ax.get_xticklabels() lblx[1]._text = 'hello!' ax.set_xticklabels(lblx) plt.draw() plt.show() would give the expected I'm not very happy with this state (having to manually insert delays). And my main concern is: How can I know how much time I need to wait? Surely it depends on number of figure elements, machine strength, etc.. So my question is: Is there some flag to know that matplotlib has finished drawing all the elements? Or is there a better way to do what I'm doing?
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 5
has comment: http://stackoverflow.com/comment/84733967
has answer: http://stackoverflow.com/a/48865859

http://stackoverflow.com/a/48862883
has comment: http://stackoverflow.com/comment/84741323
type: Answer
answers question: http://stackoverflow.com/q/48862435
upvote count: 1
has comment: http://stackoverflow.com/comment/84741836
has body: If I am interpreting this correct, you are looking for a list of the times of the waves, starting at t0 and ending at tf. def time_builder(f, t0=0, tf=300): """ Function building the time line in ms between t0 and tf with a frequency f. f: Hz t0 and tf: ms """ T = 1000 / f # period [ms] n = int( (tf - t0) / T + 0.5 ) # n integer number of wavefronts, +0.5 added for rounding consistency return [t0 + i*T for i in range(n)]
accepted answer of: http://stackoverflow.com/q/48862435
has comment: http://stackoverflow.com/comment/84742585
score: 1
has comment: http://stackoverflow.com/comment/84729000
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84732000

http://stackoverflow.com/q/48842543
tagged with: dump
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84689206
has comment: http://stackoverflow.com/comment/84689270
has answer: http://stackoverflow.com/a/48842673
accepted answer: http://stackoverflow.com/a/48842673
type: Question
has title: Json dump of dict with tuples inside in Python
has comment: http://stackoverflow.com/comment/84689180
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84689162
score: 0
upvote count: 1
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84689239
has body: I have a dictionary in Python which maps tuple to a number as follows. The goal is to have my data printed in pretty json format, but I am getting an error import json data = { (7, 0, 4, 1, 0, 0, 3): 2, (7, 0, 3, 1, 0, 0, 3): 1, (2, 0, 0, 1, 0, 0, 1): 3, (7, 0, 2, 1, 0, 0, 3): 4, (7, 0, 4, 1, 0, 0, 2): 1, (0, 0, 0, 0, 0, 0, 0): 2, } print (json.dumps(data)) I am getting an error return _iterencode(o, 0) TypeError: keys must be a string Apparently it has something to do with the tuple. Casting data to string does not work, it only returns one-line result. "{(7, 0, 4, 1, 0, 0, 3): 2, (7, 0, 3, 1, 0, 0, 3): 1, (2, 0, 0, 1, 0, 0, 1): 3, (7, 0, 2, 1, 0, 0, 3): 4, (7, 0, 4, 1, 0, 0, 2): 1, (0, 0, 0, 0, 0, 0, 0): 2}"
favorite count: 0
tagged with: tuples
has comment: http://stackoverflow.com/comment/84689298

http://stackoverflow.com/q/48914936
type: Question
answer count: 2
has body: With this code: url = "https://github.com/searcho=desc&amp;p=1&amp;q=stars%3A%3E1&amp;s=stars&amp;type=Repositoris" with urllib.request.urlopen(url) as response: html = response.read() html = html.decode('utf-8') with open('page_content.html', 'w', encoding='utf-8') as new_file: new_file.write(html) soup = BeautifulSoup(html,'lxml') g_data= soup.findAll("a", {"class":"v-align-middle"}) print(g_data[0]) The output is: &lt;a class="v-align-middle" data-hydro-click='{"event_type":"search_result.click","payload":{"page_number":1,"query":"stars:&amp;gt;1","result_position":1,"click_id":28457823,"result":{"id":28457823,"global_relay_id":"MDEwOlJlcG9zaXRvcnkyODQ1NzgyMw==","model_name":"Repository","url":"https://github.com/freeCodeCamp/freeCodeCamp"},"originating_request_id":"ECC6:1DF24:CE9C0F:1667572:5A8DDD6F"}}' data-hydro-hmac="42c4e038b86cefc302d5637e870e6d746ee7fa95eadf2b26930cb893c6a3bc53" href="/freeCodeCamp/freeCodeCamp"&gt;freeCodeCamp/freeCodeCamp&lt;/a&gt; How do I extract below url from the output: https://github.com/freeCodeCamp/freeCodeCamp Thanks!
possible better answer: http://stackoverflow.com/a/48915433
has comment: http://stackoverflow.com/comment/84836385
has answer: http://stackoverflow.com/a/48915424
has title: extracting url using beautifulsoup
accepted answer: http://stackoverflow.com/a/48915424
upvote count: 1
has answer: http://stackoverflow.com/a/48915433
has comment: http://stackoverflow.com/comment/84837100
has comment: http://stackoverflow.com/comment/84836971
favorite count: 0
has comment: http://stackoverflow.com/comment/84836704
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: web-scraping
has comment: http://stackoverflow.com/comment/84836904

django-views
tags question: http://stackoverflow.com/q/48936463
tags question: http://stackoverflow.com/q/48814557
tags question: http://stackoverflow.com/q/48818181
tags question: http://stackoverflow.com/q/48943688
tags question: http://stackoverflow.com/q/48815848
tags question: http://stackoverflow.com/q/48918452
tag name: django-views
tags question: http://stackoverflow.com/q/48843462
tags question: http://stackoverflow.com/q/48919241
tags question: http://stackoverflow.com/q/48835978
type: Tag
tags question: http://stackoverflow.com/q/48867604
tags question: http://stackoverflow.com/q/48817253
tags question: http://stackoverflow.com/q/48884829
tags question: http://stackoverflow.com/q/48870584
tags question: http://stackoverflow.com/q/48908156
tags question: http://stackoverflow.com/q/48900409
tags question: http://stackoverflow.com/q/48938719
tags question: http://stackoverflow.com/q/48887001
tags question: http://stackoverflow.com/q/48817226
tags question: http://stackoverflow.com/q/48891878
tags question: http://stackoverflow.com/q/48907523
tags question: http://stackoverflow.com/q/48810444
tags question: http://stackoverflow.com/q/48891247
tags question: http://stackoverflow.com/q/48842068
tags question: http://stackoverflow.com/q/48807821
tags question: http://stackoverflow.com/q/48912441
tags question: http://stackoverflow.com/q/48900777
tags question: http://stackoverflow.com/q/48842061
tags question: http://stackoverflow.com/q/48912402
tags question: http://stackoverflow.com/q/48841036

http://stackoverflow.com/q/48926384
tagged with: python
has title: Reading file from the same directory as the python module
has answer: http://stackoverflow.com/a/66978213
upvote count: 2
type: UnansweredQuestion
tagged with: file
has answer: http://stackoverflow.com/a/58263567
linked to: http://stackoverflow.com/q/4060221
type: Question
answer count: 2
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84859070
favorite count: 0
tagged with: path
has body: Suppose I have got python module foo.py and file myfile.txt that reside in the same directory. foo.py contains the following code to read myfile.txt: from os import path myfile_path = path.join(path.dirname(__file__), 'myfile.txt') myfile = open(myfile_path) I found myself writing path.join(path.dirname(__file__), '...') over and over again in different modules. Is there a shorter and simpler way to read a file from the same directory as the python module ?

http://stackoverflow.com/q/48897875
possible better answer: http://stackoverflow.com/a/48898002
score: -3
tagged with: python-2.7
type: AnsweredQuestion
upvote count: 0
has title: May someone help me figure out how to update my dashes on my python hangman code
favorite count: 0
tagged with: python-3.x
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48897966
has body: I am supposed to be able to update these dashes so that when someone types in "a" the dashes will look like a---a-. And if the user guesses the letter "l", the dashes will look like a---al. magic_word = "animal" dashes = "--------" def get_guess() while True: print dashes guess = str(input("Guess a letter: ")) if len(guess)&gt;1: print "Too long" continue elif not guess.islower(): print "Your guess must be one lowercase letter" continue if guess in magic_word : print "That is in the word" continue else: print "That is not in the word" continue return guess break get_guess()
answer count: 2
downvote count: 3
accepted answer: http://stackoverflow.com/a/48897966
has answer: http://stackoverflow.com/a/48898002
tagged with: python-requests

http://stackoverflow.com/comment/84748860
type: Comment
comment on: http://stackoverflow.com/a/48870891
score: 0
type: AnswerComment
has text: Here are two examples of strings which fail: `longest_rep('aaabcabc') => 'aaa'` (should be `'abcabc'`); `longest_rep('ababcababc') => 'abab'` (should be `'ababcababc'`)

http://stackoverflow.com/a/48957412
has comment: http://stackoverflow.com/comment/84921858
upvote count: 2
has comment: http://stackoverflow.com/comment/84922360
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48957011
has comment: http://stackoverflow.com/comment/84922300
has body: try this one reg = linear_model.LinearRegression() df = get_DP() df=df.reset_index() reg.fit(df.date.values.reshape(-1, 1), df.DP.values.reshape(-1, 1)) print("beta: {}".format(reg.coef_)) print("alpha: {}".format(reg.intercept_)) plt.scatter(df.date.dt.date, df.DP.values, color='black') plt.plot(df.date.dt.date, df.DP.values, color='blue', linewidth=3) See reshape documentation
downvote count: 0

http://stackoverflow.com/comment/84812534
type: AnswerComment
comment on: http://stackoverflow.com/a/48902965
type: Comment
has text: @Madmartigan ok in that case i modified my answer...try with it
score: 0

http://stackoverflow.com/comment/84619072
comment on: http://stackoverflow.com/a/48808066
type: Comment
has text: @cᴏʟᴅsᴘᴇᴇᴅ Yeah, was about to add that. Thanks mate :).
score: 0
type: AnswerComment

http://stackoverflow.com/q/48911638
type: Question
has answer: http://stackoverflow.com/a/48911848
score: 0
tagged with: pandas
answer count: 1
favorite count: 0
has body: Is it possible to fill a dataframe I have in pandas with as many letters of the alphabet as I have columns? For example if I get the amount of columns and there are 50, I would have to fill every column header until "AX". nrcolumns=len(df.columns) The fact is that I haven't found a way to pd.read_excel with the headers taken from the column names in excel. Thanks
accepted answer: http://stackoverflow.com/a/48911848
tagged with: python
has comment: http://stackoverflow.com/comment/84830160
tagged with: excel
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/19153462
has comment: http://stackoverflow.com/comment/84857776
upvote count: 1
downvote count: 1
has title: Pandas header all letters of alphabet

http://stackoverflow.com/q/48874665
type: UnansweredQuestion
tagged with: psycopg2
type: Question
tagged with: heroku
has title: psycopg2 error on heroku
score: 0
answer count: 1
tagged with: postgresql
has body: I have been trying to run a node webserver and django backend server on one dyno following this guide. My ProcfileHoncho looks like: node: cd src-backbone &amp;&amp; npm install --production python: cd src-django &amp;&amp; pip install -r requirements.txt &amp;&amp; gunicorn myapp.wsgi:application --bind 127.0.0.1:8000 When I run pip install requirements.txt from my Procfile it tries to install psycopg2==2.6.1 but it seems to crash every time because psycopg2 cannot find pg_config which is part of the PostgreSQL library usually. I already created (and I assume attached) the Postgres addon to my application but I cannot get the installation to work. Any suggestions? 2018-02-19T20:47:29.441881+00:00 app[web.1]: 20:47:29 python.1 | Collecting djangorestframework==3.3.2 (from -r requirements.txt (line 13)) 2018-02-19T20:47:29.636583+00:00 app[web.1]: 20:47:29 python.1 | Downloading djangorestframework-3.3.2-py2.py3-none-any.whl (634kB) 2018-02-19T20:47:29.948376+00:00 app[web.1]: 20:47:29 python.1 | Collecting factory-boy==2.6.1 (from -r requirements.txt (line 14)) 2018-02-19T20:47:30.007044+00:00 app[web.1]: 20:47:30 python.1 | Downloading factory_boy-2.6.1-py2.py3-none-any.whl 2018-02-19T20:47:30.134889+00:00 app[web.1]: 20:47:30 python.1 | Collecting flake8==2.5.4 (from -r requirements.txt (line 15)) 2018-02-19T20:47:30.224808+00:00 app[web.1]: 20:47:30 python.1 | Downloading flake8-2.5.4-py2.py3-none-any.whl 2018-02-19T20:47:30.349474+00:00 app[web.1]: 20:47:30 python.1 | Collecting freezegun==0.3.6 (from -r requirements.txt (line 16)) 2018-02-19T20:47:30.445518+00:00 app[web.1]: 20:47:30 python.1 | Downloading freezegun-0.3.6-py2.py3-none-any.whl 2018-02-19T20:47:30.619753+00:00 app[web.1]: 20:47:30 python.1 | Collecting gunicorn==19.4.5 (from -r requirements.txt (line 17)) 2018-02-19T20:47:30.713577+00:00 app[web.1]: 20:47:30 python.1 | Downloading gunicorn-19.4.5-py2.py3-none-any.whl (112kB) 2018-02-19T20:47:30.869301+00:00 app[web.1]: 20:47:30 python.1 | Collect…
tagged with: python
has answer: http://stackoverflow.com/a/48874720

http://stackoverflow.com/comment/84633026
comment on: http://stackoverflow.com/q/48814279
score: 0
type: Comment
type: QuestionComment
has text: @MEE Maybe some tools that automatically manipulates sys.path just like what you have with MS c#? In c# with Visual Studio you don't even need to know where a class is provides it's somewhere in the source code tree.

http://stackoverflow.com/comment/84734484
comment on: http://stackoverflow.com/q/48864857
has text: @Nikitka url redirection is not performed after POST . why?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48805046
favorite count: 0
has answer: http://stackoverflow.com/a/48805247
tagged with: python
type: UnansweredQuestion
upvote count: 1
tagged with: tensorflow
has body: I developed a cnn + lstm network which take in input a vector (audio track) and each track has a specific emotional label called arousal and valence. I must use a custom loss function called Concordance correlation coefficient, when I evaluate the loss value between the predictions and the test value I obtain about 99% value, but if I plot the signals they are too disagree. Below there is part of code, I take one audio track and for each of them I take a segment to train the model. Each segment has a specific arousal-valence labels. for t in range(0, train_set.shape[0]): print('Traccia audio: ' + str(t+1)) track = np.expand_dims(train_set[t], axis=2) # shape: (50, 96000, 1) label_arousal = strided_app(train_arousal[t], 96000, 96000) # shape: (50, 96000) label_valence = strided_app(train_valence[t], 96000, 96000) for s in range(0, track.shape[0]): sub_track = np.expand_dims(track[s], axis=0) # shape: (1, 96000, 1) sub_arousal = np.expand_dims(label_arousal[s], axis=0) # shape: (1, 96000) sub_valence = np.expand_dims(label_valence[s], axis=0) model.fit(sub_track, [sub_arousal, sub_valence], batch_size=50, epochs=10, verbose=0) Here there are the loss value (percent) def ccc(x,y): x_mean = np.mean(x) y_mean = np.mean(y) x_var = np.var(x) y_var = np.var(y) x_std = np.std(x) y_std = np.std(y) cov = np.mean((x - x_mean) * (y - y_mean)) numerator = 2 * cov * x_std * y_std denominator = x_var + y_var + (x_mean - y_mean) ** 2 return (1 - numerator / denominator) * 100 for i in range(0, test_predictions_arousal.shape[0]): print('Traccia: ' + str(i+1)) print('Arousal: ' + str(ccc(test_predictions_arousal[i], test_arousal[i]))) print('Valence: ' + str(ccc(test_predictions_valence[i], test_valence[i]))) print('************') Traccia: 1 Arousal: 99.80387506604289 Valence: 99.99019742174045 ************ Traccia: 2 Arousal: 99.90842777974784 Valence: 99.9833303193375 ************ Traccia: 3 Arousal: 99.76175122350213 Valence: 99.91642446964116 ************ Traccia: 4 Arousal: 99.69…
type: Question
answer count: 1
downvote count: 0
score: 1
tagged with: keras
has title: Keras tensorflow weird loss accuracy

http://stackoverflow.com/comment/84654203
has text: "I know how to fix it but I want to understand why this happens" so there shouldn't be an issue just do some research on it
comment on: http://stackoverflow.com/q/48825234
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84913317
type: QuestionComment
has text: done... I really don't understand why it's not working with me (newbie in pandas/python)
type: Comment
comment on: http://stackoverflow.com/q/48953032
score: 0

http://stackoverflow.com/q/48842567
type: AnsweredQuestion
has title: How to create an object which stores mappings from a word in a vocabulary to its index?
accepted answer: http://stackoverflow.com/a/48842713
type: Question
tagged with: vocabulary
has body: I have a tokenized list of words in a vocabulary. (It's been passed through a set, so there are no duplicates.) My problem I want to generate a method which creates a dictionary that allows a mapping from the word to its index in the vocabulary. My attempt My current method is like so: mapping = { w : vocabulary.index(w) for w in vocabulary } This should work but it is far too inefficient, probably due to repeatedly using vocabulary.index(w) for thousands of words. Question Is there a library that I can use that does this more efficiently? Or just more efficient methods? Thanks. POSSIBLE SOLUTION 1 Currently, each time a word is reached in 'vocabulary', vocabulary.index() is implemented, which required a pass through 'vocabulary' to identify the index, which is done for every word. As suggested in an answer, a possibility is to enumerate 'vocabulary' first. This allows one pass through it to identify the index, like so: mapping = { w : i for i, w in enumerate(vocabulary) }
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48842713
tagged with: python
tagged with: nlp

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

http://stackoverflow.com/a/48861742
has comment: http://stackoverflow.com/comment/84726557
score: 0
has comment: http://stackoverflow.com/comment/84726604
has comment: http://stackoverflow.com/comment/84728195
type: Answer
answers question: http://stackoverflow.com/q/48861331
has comment: http://stackoverflow.com/comment/84726977
has body: This might help. I am using a simple for loop and negative indexing to get your required result. s = """1, "asdsdsdsds", "John" 2, "dfdhifdkinf dfjdfgkdnjgknkdjgndkng dkfdkjfnjdnf", "Roy" 3, "dfjfdkgjfgn", "Rahul""" res = [] for i in s.split("\n"): if i[0].isdigit(): res.append(i) else: res[-1] = res[-1] + " " + I for i in res: print(i) Output: 1, "asdsdsdsds", "John" 2, "dfdhifdkinf dfjdfgkdnjgknkdjgndkng dkfdkjfnjdnf", "Roy" 3, "dfjfdkgjfgn", "Rahul

http://stackoverflow.com/q/48856881
type: UnansweredQuestion
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/85107001
score: 3
answer count: 0
type: Question
has title: Show horizontal line separator between cell blocks in PyCharm
downvote count: 1
has body: I am using the cell mode plugin in PyCharm to separate new cells at #%%. How can I make the PyCharm editor to show a horizontal line between adjacent cell blocks akin Spyder? #%% first cell def foo(): print("bar") ------------------ #this is what I want to see #%% second cell print("foo")
favorite count: 0
has comment: http://stackoverflow.com/comment/96049829
tagged with: pycharm

database
tags question: http://stackoverflow.com/q/48837505
tags question: http://stackoverflow.com/q/48945589
tags question: http://stackoverflow.com/q/48855090
tags question: http://stackoverflow.com/q/48922096
tags question: http://stackoverflow.com/q/48876733
tags question: http://stackoverflow.com/q/48899190
tags question: http://stackoverflow.com/q/48951238
tags question: http://stackoverflow.com/q/48866525
tags question: http://stackoverflow.com/q/48927972
type: Tag
tags question: http://stackoverflow.com/q/48863514
tag name: database
tags question: http://stackoverflow.com/q/48888000
tags question: http://stackoverflow.com/q/48896977
tags question: http://stackoverflow.com/q/48939455
tags question: http://stackoverflow.com/q/48844322
tags question: http://stackoverflow.com/q/48874745
tags question: http://stackoverflow.com/q/48861872
tags question: http://stackoverflow.com/q/48914609

http://stackoverflow.com/q/48852699
tagged with: python-3.x
upvote count: 2
has comment: http://stackoverflow.com/comment/84708871
has comment: http://stackoverflow.com/comment/84708876
accepted answer: http://stackoverflow.com/a/48852916
tagged with: python
downvote count: 1
type: AnsweredQuestion
has body: I was wondering if there's a way to refer to a previous part of a calculation in the same statement. For example: (random.randint(1, 2) * 10) + ... ## Is there a way to refer to the random number ## previously calculated, which will go in ## the space of the ellipsis? I know this could be done using a variable, but ideally I'm looking for a one-liner. Thanks!
has comment: http://stackoverflow.com/comment/84709552
score: 1
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48852765
has title: Refer to a previous calculation in python?
has answer: http://stackoverflow.com/a/48852765
favorite count: 0
has comment: http://stackoverflow.com/comment/84709581
has comment: http://stackoverflow.com/comment/84708838
has answer: http://stackoverflow.com/a/48852916

http://stackoverflow.com/comment/92561910
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48888185
has text: @Gavin you will get exactly 100 rows because `limit(n)` will return exactly `n` rows (assuming there's that many in the table, if there are not it will return all of the rows.). This only relies on the `monotonically_increasing_id()` to sort the table.

http://stackoverflow.com/q/48946896
has title: How to count the number of sublists based on common elements from a nested list in python?
answer count: 3
has answer: http://stackoverflow.com/a/48947599
tagged with: nested
has comment: http://stackoverflow.com/comment/84900172
tagged with: sublist
favorite count: 0
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/48947181
tagged with: python
tagged with: list
has answer: http://stackoverflow.com/a/48947066
type: Question
upvote count: 2
has body: I have a list of lists like this: [[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5], [2, 3, 4, 5, 6, 7], [2, 3], [3, 4]]. How can I count the lists which are sublists of more than two lists? For example, here [2, 3] and [3, 4] would be the lists that are sublists of first 3 lists. I want to get rid of them.
score: 0

http://stackoverflow.com/comment/84628166
type: QuestionComment
has text: Try this https://stackoverflow.com/a/37369497/6083655
comment on: http://stackoverflow.com/q/48812105
score: 0
type: Comment

http://stackoverflow.com/q/48863160
has title: Locating a "log error" in log file using Python
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
upvote count: 1
type: Question
has body: I am trying to create a script that discomposes a log file to several lists (ip, log time, GET Request, path, errors). I want my script to print the right error line in my log file, how can i make my script to look for it, finds it and print it? Heres my script: file_1=open("lolz.txt","r") file_2=open("lolz2.txt","r") a = file_1.readlines() b = file_2.readlines() date=[] ipss=[] post=[] date2=[] kind=[] ipss2=[] con=[] erorr=[] for i in a: i = i.split(" - - ") for x in i: x = x.split("/") ipss.append(x[0].strip("[07")) i = i[1].split(' ') date.append(i[0].strip("[]-0800")) for line in a: q = (line[47::]) post.append(q.strip("GET"" ""\n")) for lins in b: t = (lins[0:26]) y = (lins[26:34]) u = (lins[34:56]) p = (lins[56:140]) date2.append(t.strip("[ ]")) kind.append(y.strip("[ ]")) ipss2.append(u.strip("[ ] ( )")) con.append(p.strip("\n - -- ( ) [ ]")) for poop in b: if len(poop) &lt; 138 or len(poop) &gt; 138: erorr.append(poop.strip("\n - [ ] ( )")) Log lines example: [Sun Mar 7 20:58:27 2004] [info] [client 64.242.88.10] (104)Connection reset by peer: client stopped connection before send body completed [Sun Mar 7 21:16:17 2004] [error] [client 24.70.56.49] File does not exist: /home/httpd/twiki/view/Main/WebHome [Sun Mar 7 21:20:14 2004] [info] [client 64.242.88.10] (104)Connection reset by peer: client stopped connection before send body completed
score: 1
has comment: http://stackoverflow.com/comment/84735023
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84729843
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84729994
tagged with: python

http://stackoverflow.com/comment/84615135
has text: It's not a duplicate, the variable swapping is only a first part of this problem. Please read the full article.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48806037

http://stackoverflow.com/comment/84720461
has text: @juanpa.arrivillaga that actually makes sense, thanks!
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48858475

http://stackoverflow.com/q/48877722
tagged with: python
type: AnsweredQuestion
score: 0
type: Question
has body: I already created a get_url function that retrieves one url, I am now trying to call that function to define a different one, print_all_links(s), that prints all urls from an inputted string. This is what I have so far, it prints the correct amount of url's but they are just the first url repeated, and not on one line, please help def get_url(s): #s = s.replace(" ", "") b = s.find('&lt;a href=') if b != -1: return s[b + 9 : b + 9 + s[b + 9::].find('"')] else: return b #prints all URls in HTML input def print_all_links(s): i = s.count('&lt;a href=') n = i x = '' while n &gt; 0: x += get_url(s) print(x) s = s.replace(x, '') n = n-1 sample input: print_all_links(' University of Illinois at Chicago | prints: https://uic.edu https://uic.edu
has answer: http://stackoverflow.com/a/48877871
tagged with: hyperlink
has title: print all urls - python
answer count: 1
tagged with: url
accepted answer: http://stackoverflow.com/a/48877871

http://stackoverflow.com/comment/102715956
type: Comment
has text: You might improve your answer with a single sentence explaining what you changed.
comment on: http://stackoverflow.com/a/58164522
score: 1
type: AnswerComment

http://stackoverflow.com/q/48902846
has answer: http://stackoverflow.com/a/48911259
tagged with: python
has answer: http://stackoverflow.com/a/48906465
type: UnansweredQuestion
has body: I have a masked numpy array like the following: mar = np.ma.array([0, 0, 100, 100], mask=[False, True, True, False], fill_value=-1) So the two values in the middle are masked, calling mar.filled() would return [0, -1, -1, 100]. I want to compare this array to a scalar 0, i.e.: mar == 0 which returns masked_array(data = [True -- -- False], mask = [False True True False], fill_value = True) Note that the fill_value is now True which is the default fill value for bool arrays but does not make sense for me in this case (I would have expected that it is set to -1 == 0 which is False). To illustrate my problem more clearly: (mar == 0).filled() and mar.filled() == 0 do not return the same result. Is this intended behaviour or is it a bug? In any case, is there a workaround to achieve my desired behaviour? I know that I can just convert to a normal array before comparison using .filled() but I would like to avoid that if possible, since the code should not care whether it is a masked array or a normal one.
type: Question
has title: NumPy masked array not considering fill_value when comparing to scalar
tagged with: numpy
score: 0
answer count: 2

http://stackoverflow.com/q/48836635
has comment: http://stackoverflow.com/comment/84680515
has answer: http://stackoverflow.com/a/48843010
tagged with: django
tagged with: logging
type: Question
has answer: http://stackoverflow.com/a/64692986
score: 6
answer count: 2
has comment: http://stackoverflow.com/comment/84678413
has comment: http://stackoverflow.com/comment/84678236
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84678371
has comment: http://stackoverflow.com/comment/128467735
type: UnansweredQuestion
tagged with: python
has body: I have logging set up in my Django app to log to both stdout and a file. When I run my django app normally (./manage.py runserver) the logs are updated as expected. Here is an example that successfully logs when i visit the url for the view below: # views.py import logging logger = logging.getLogger('mylogger') def test(request): logger.error("test") However, when I run ./manage.py shell and run the following commands the log is not updated: import logging logger = logging.getLogger('mylogger') logger.error('test') Here is my logging setup in settings.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { }, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', 'stream': sys.stdout, }, 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '../debug.log', }, }, 'loggers': { 'mylogger': { 'handlers': ['console', 'file'], 'level': 'INFO', 'propagate': True, }, } } Do I have to do something extra to get logging to work within the shell?
upvote count: 6
has title: Django logging does not work with django shell

http://stackoverflow.com/comment/84701614
score: 0
type: Comment
has text: Thank you so much! You helped a lot. I think I was making it more difficult than it needed to be
type: AnswerComment
comment on: http://stackoverflow.com/a/48848930

http://stackoverflow.com/a/54204496
upvote count: 2
has comment: http://stackoverflow.com/comment/119136184
type: Answer
downvote count: 2
has body: You seem to be using an older model of LogisticRegression. model.summary2() should do the trick.
answers question: http://stackoverflow.com/q/48820601
score: 0
has comment: http://stackoverflow.com/comment/115575971

http://stackoverflow.com/a/48897377
has comment: http://stackoverflow.com/comment/84800582
type: Answer
has comment: http://stackoverflow.com/comment/84800540
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84800431
has comment: http://stackoverflow.com/comment/84800650
has body: Edit: As piRSquared mentioned, my previous solution needs to append two False at the beginning and at the end of the series. piRSquared kindly gave an answer based on that. (np.diff(np.flatnonzero(np.append(True, np.append(~s.values, True)))) - 1).max() My original trial is (np.diff(s.where(~s).dropna().index.values) - 1).max() (This will not give the correct answer if the longest True starts at the beginning or ends at the end as pointed out by piRSquared. Please use the solution above given by piRSquared. This work remains only for explanation.) Explanation: This finds the indices of the False parts and by finding the gaps between the indices of False, we can know the longest True. s.where(s == False).dropna().index.values finds all the indices of False array([0, 2, 6, 7]) We know that Trues live between the Falses. Thus, we can use np.diff to find the gaps between these indices. array([2, 4, 1]) Minus 1 in the end as Trues lies between these indices. Find the maximum of the difference.
answers question: http://stackoverflow.com/q/48897265
downvote count: 0

http://stackoverflow.com/comment/84884330
comment on: http://stackoverflow.com/a/48938697
score: 1
type: AnswerComment
has text: Don't need `from __future__ import division` for python3
type: Comment

http://stackoverflow.com/q/48825644
has comment: http://stackoverflow.com/comment/84654903
favorite count: 0
linked to: http://stackoverflow.com/q/37010212
type: Question
upvote count: 2
answer count: 2
downvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84655674
has title: Inserting String at first index number pandas dataframe
accepted answer: http://stackoverflow.com/a/48825706
score: 0
has body: I have a dataframe that looks like this: Index Z1 Z2 Z3 Z4 0 0 0 A A 1 0 B 0 0 2 C 0 C 0 I want to convert it to Index Z1 Z2 Z3 Z4 ABC 0 0 0 A A 1 0 B 0 0 2 C 0 C 0 I want to basically insert text "ABC" before 0th index and the entire row(ABC) will not have any value It will be okay if the index starts from 1 and not 0 as below Index Z1 Z2 Z3 Z4 ABC 1 0 0 A A 2 0 B 0 0 3 C 0 C 0
has comment: http://stackoverflow.com/comment/84655613
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84655312
has comment: http://stackoverflow.com/comment/84655104
has comment: http://stackoverflow.com/comment/84655679
has answer: http://stackoverflow.com/a/48825760
tagged with: pandas
has comment: http://stackoverflow.com/comment/84655192
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48825760
has answer: http://stackoverflow.com/a/48825706

http://stackoverflow.com/q/48849965
tagged with: python
score: -2
has title: When I run this code, it gives None instead of the 'Python' getting appended to the List. Why is that so?
has answer: http://stackoverflow.com/a/48850003
has comment: http://stackoverflow.com/comment/84703547
downvote count: 2
has body: When I run this code, it gives None instead of the 'Python' getting appended to the List. Why is that so? input_tuple = ('Monty Python', 'British', 1969) input_list = list(input_tuple) print(input_list) input_list_1 = input_list.append('Python') print(input_list_1)
has answer: http://stackoverflow.com/a/48850010
has answer: http://stackoverflow.com/a/48850182
linked to: http://stackoverflow.com/q/20016802
type: UnansweredQuestion
answer count: 4
upvote count: 0
duplicate of: http://stackoverflow.com/q/11205254
favorite count: 0
tagged with: python-3.x
type: Question
has answer: http://stackoverflow.com/a/48850013

http://stackoverflow.com/comment/84913581
has text: Yes, you can base your logic on the string-valued result of `x` if you don't strictly need to perform integer operations on it.
comment on: http://stackoverflow.com/a/48953392
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/109986672
comment on: http://stackoverflow.com/a/62165649
has text: i'm a new contributor so thanks for the feedback i will definitely be looking into this
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84853995
type: AnswerComment
comment on: http://stackoverflow.com/a/48923166
score: 0
type: Comment
has text: I don't know what you mean by it will make a mess. Nothing will make a mess: if you can't find any incorrect behaviour or differences in performance, you're fine. Call and define the functions however makes you happy.

http://stackoverflow.com/comment/84700830
comment on: http://stackoverflow.com/a/48848385
type: AnswerComment
has text: @TerryA I'm not sure what you mean by that. Instead of saving `result.text` to a variable named `result_text` and then passing it into `json.loads(result_text)`, you can jump straight to JSON by using `result.json()` (It's the [6th line run in the first example box of the `requests` docs.](http://docs.python-requests.org/en/master/)). That way you don't have to `import json` and it simplifies your code.
score: 0
type: Comment

http://stackoverflow.com/q/48901691
type: Question
tagged with: nltk
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48901924
tagged with: scikit-learn
has body: Code: import nltk eng_lish= open("english.txt","r", encoding='utf-8',errors="ignore").read() bang_lish= open("banglish.txt","r", encoding='utf-8',errors="ignore").read() import numpy as np from nltk.probability import FreqDist from nltk.classify import SklearnClassifier from sklearn.feature_extraction.text import TfidfTransformer from sklearn.feature_selection import SelectKBest, chi2 from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline pipeline = Pipeline([('tfidf', TfidfTransformer()), ('chi2', SelectKBest(chi2, k=1000)), ('nb', MultinomialNB())]) classif = SklearnClassifier(pipeline) pos_data= [FreqDist(nltk.word_tokenize(bang_lish))] neg_data= [FreqDist(nltk.word_tokenize(eng_lish))] print (pos_data) print (neg_data) pos=[FreqDist(pos_data.words(f)) for f in pos_data.append('pos')] neg=[FreqDist(neg_data.words(f)) for f in neg_data.append('neg')] #from nltk.corpus import movie_reviews #pos = [FreqDist(movie_reviews.words(i)) for i in movie_reviews.fileids('pos')] #neg = [FreqDist(movie_reviews.words(i)) for i in movie_reviews.fileids('neg')] add_label = lambda lst, lab: [(x, lab) for x in lst] classif.train(add_label(pos[:100], 'pos') + add_label(neg[:100], 'neg')) l_pos = np.array(classif.classify_many(pos[100:])) l_neg = np.array(classif.classify_many(neg[100:])) print ("Confusion matrix:\n%d\t%d\n%d\t%d" % ( (l_pos == 'pos').sum(), (l_pos == 'neg').sum(), (l_neg == 'pos').sum(), (l_neg == 'neg').sum())) Error: &gt;C:\Users\Nouros\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/Nouros/Desktop/Thesis/nltk_run_copy.py [FreqDist({'?': 312, '.': 182, 'er': 122, 'na': 122, '...': 101, 'ki': 92, 'o': 62, '!': 59, 'ta': 56, 'e': 56, ...})] Traceback (most recent call last): [FreqDist({'.': 6972, 'the': 5060, 'a': 3842, 'and': 3553, 'of': 3311, 'to': 1970, "'s": 1813, 'is': 1776, 'it': 1674, 'that': 1357, ...})] File "C:/Users/Nouros/Desktop/Thesis/nltk_run_copy.py", line 20, in &lt;module&gt; pos=[FreqDist(pos_data.words(f…
tagged with: python
tagged with: nlp
has answer: http://stackoverflow.com/a/48929555
type: UnansweredQuestion
tagged with: machine-learning
has title: I am not sure how this loop for finding positive and negative data set will work out to give me a the confusion matrix. Any suggestion?

http://stackoverflow.com/a/49164867
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48941526
accepted answer of: http://stackoverflow.com/q/48941526
score: 0
has body: Found the problem, my old code query all objects every time, return Entry.objects.filter().order_by('date')[::-1] and the new code will run internal query command to query severl objects each time. return Entry.objects.filter().order_by('date') With elasticsearch, I use the answer here, it create a proxy between the Paginator and the Elasticsearch query.

http://stackoverflow.com/a/48886476
type: Answer
has body: Using re import re addr = ['100 NORTH MAIN ROAD', '100 BROAD ROAD APT.', 'SAROJINI DEVI ROAD', 'BROAD AVENUE ROAD'] for i, v in enumerate(addr): addr[i] = re.sub('ROAD', 'RD', v) #v.replace("ROAD", "RD") print addr Output: ['100 NORTH MAIN RD', '100 BRD RD APT.', 'SAROJINI DEVI RD', 'BRD AVENUE RD']
answers question: http://stackoverflow.com/q/48886423
score: 0

http://stackoverflow.com/comment/84855880
type: Comment
type: QuestionComment
has text: You don't have a chance without ISO 7816 part 4 as a basis (describing lots of possibilities and options) and the operating system manual of the card you have (to state, which options were chosen, what additional data objects exist in the response and what these proprietary additions mean).
comment on: http://stackoverflow.com/q/48924045
score: 0

http://stackoverflow.com/q/48879595
tagged with: cassandra
tagged with: azure
answer count: 1
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/44371692
tagged with: python
has comment: http://stackoverflow.com/comment/84763330
accepted answer: http://stackoverflow.com/a/48883665
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84763267
has body: I am trying to install python package cassandra driver in Azure Machine Learning studio. I am following this answer from here. Unfortunately i don't see any wheel file for cassandra-driver https://pypi.python.org/pypi/cassandra-driver/ so i downloaded the .tar file and converted to zip. I included this .zip file as dataset and connected to python script But when i run it, it says No module named cassandra Does this work only with wheel file? Any solution is much appreciated. I am using Python Version : Anoconda 4.0/Python 3.5
tagged with: azure-machine-learning-service
upvote count: 1
type: Question
has title: ImportError: No module named cassandra in Azure Machine Learning Studio
downvote count: 0
has answer: http://stackoverflow.com/a/48883665

http://stackoverflow.com/a/48965960
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/84939491
has body: You can simplify this a lot by using lxml's getpath() method. This is input.xml: &lt;root1&gt; &lt;child1/&gt; &lt;child2&gt; &lt;child21&gt; &lt;child221/&gt; &lt;/child21&gt; &lt;/child2&gt; &lt;child3/&gt; &lt;/root1&gt; Here is how you can generate an absolute XPath expression for each element in the XML document: from lxml import etree tree = etree.parse("input.xml") for elem in tree.iter(): print(tree.getpath(elem)) Output: /root1 /root1/child1 /root1/child2 /root1/child2/child21 /root1/child2/child21/child221 /root1/child3
answers question: http://stackoverflow.com/q/48959744
score: 4

http://stackoverflow.com/comment/84755460
has text: Not really, though it is common practice where I am working. A working solution using another mock library would be ok-- I guess even better if new uses of mox are discouraged.
comment on: http://stackoverflow.com/q/48874768
score: 0
type: Comment
type: QuestionComment

tensorflow
tags question: http://stackoverflow.com/q/48880273
tags question: http://stackoverflow.com/q/48832052
tags question: http://stackoverflow.com/q/48814781
tags question: http://stackoverflow.com/q/48819139
tags question: http://stackoverflow.com/q/48957335
tags question: http://stackoverflow.com/q/48954694
tags question: http://stackoverflow.com/q/48946687
tags question: http://stackoverflow.com/q/48861215
tags question: http://stackoverflow.com/q/48954952
tags question: http://stackoverflow.com/q/48818277
tags question: http://stackoverflow.com/q/48829294
tags question: http://stackoverflow.com/q/48963438
tags question: http://stackoverflow.com/q/48891263
tags question: http://stackoverflow.com/q/48856444
tags question: http://stackoverflow.com/q/48898318
tags question: http://stackoverflow.com/q/48915279
tags question: http://stackoverflow.com/q/48848733
tags question: http://stackoverflow.com/q/48911354
tags question: http://stackoverflow.com/q/48883034
tags question: http://stackoverflow.com/q/48875354
tags question: http://stackoverflow.com/q/48869256
tags question: http://stackoverflow.com/q/48834462
tags question: http://stackoverflow.com/q/48860388
tags question: http://stackoverflow.com/q/48909330
tags question: http://stackoverflow.com/q/48956404
tags question: http://stackoverflow.com/q/48910253
tags question: http://stackoverflow.com/q/48835999
tags question: http://stackoverflow.com/q/48805407
tags question: http://stackoverflow.com/q/48870598
tags question: http://stackoverflow.com/q/48852907
tags question: http://stackoverflow.com/q/48852926
tags question: http://stackoverflow.com/q/48883332
tags question: http://stackoverflow.com/q/48893528
tags question: http://stackoverflow.com/q/48944682
tags question: http://stackoverflow.com/q/48890276
tags question: http://stackoverflow.com/q/48819022
tags question: http://stackoverflow.com/q/48900949
tags question: http://stackoverflow.com/q/48856174
tags question: http://stackoverflow.com/q/48822166
tags question: http://stackoverflow.com/q/48952134
tags question: http://stackoverflow.com/q/48826372
tags question: http://stackoverflow.com/q/48874558
tags question: http://stackoverflow.com/q/48832753
tags question: http://stackoverflow.com/q/48899234
tags question: http://stackoverflow.com/q/48824381
tags question: http://stackoverflow.com/q/48830257
tags question: http://stackoverflow.com/q/48898665
tags question: http://stackoverflow.com/q/48880649
tags question: http://stackoverflow.com/q/48885246
tags question: http://stackoverflow.com/q/48909198
tags question: http://stackoverflow.com/q/48868188
tags question: http://stackoverflow.com/q/48955971
tags question: http://stackoverflow.com/q/48867173
tags question: http://stackoverflow.com/q/48853437
tags question: http://stackoverflow.com/q/48942740
tags question: http://stackoverflow.com/q/48867691
tags question: http://stackoverflow.com/q/48918964
tags question: http://stackoverflow.com/q/48847365
tags question: http://stackoverflow.com/q/48882368
tags question: http://stackoverflow.com/q/48879125
tags question: http://stackoverflow.com/q/48878639
tags question: http://stackoverflow.com/q/48961563
tags question: http://stackoverflow.com/q/48805046
tags question: http://stackoverflow.com/q/48830704
tags question: http://stackoverflow.com/q/48960412
tags question: http://stackoverflow.com/q/48815350
tags question: http://stackoverflow.com/q/48885193
tags question: http://stackoverflow.com/q/48824185
tags question: http://stackoverflow.com/q/48838386
tags question: http://stackoverflow.com/q/48846679
tags question: http://stackoverflow.com/q/48938165
tags question: http://stackoverflow.com/q/48820940
tags question: http://stackoverflow.com/q/48885417
tags question: http://stackoverflow.com/q/48941836
tags question: http://stackoverflow.com/q/48865554
tags question: http://stackoverflow.com/q/48940155
tags question: http://stackoverflow.com/q/48839618
tags question: http://stackoverflow.com/q/48842037
tags question: http://stackoverflow.com/q/48930933
tags question: http://stackoverflow.com/q/48907910

http://stackoverflow.com/comment/84754624
has text: Wow... do you know how many nodes there are in a tree of height 30?
comment on: http://stackoverflow.com/q/48875318
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48896660
has title: Python Error: 'list' has no attribute 'mean'
linked to: http://stackoverflow.com/q/20109391
score: 1
has comment: http://stackoverflow.com/comment/84799122
has answer: http://stackoverflow.com/a/48897014
type: Question
possible better answer: http://stackoverflow.com/a/48896722
has comment: http://stackoverflow.com/comment/84799638
answer count: 2
has answer: http://stackoverflow.com/a/48896722
downvote count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84799670
accepted answer: http://stackoverflow.com/a/48897014
has comment: http://stackoverflow.com/comment/84799776
favorite count: 0
tagged with: python-3.x
has body: I am trying to get the mean value for a list of percentages from an Excel file which has data. My current code is as follows: import numpy as pd data = pd.DataFrame =({'Percentages': [.20, .10, .05], 'Nationality':['American', 'Mexican', 'Russian'], 'Gender': ['Male', 'Female'], 'Question': ['They have good looks']}) pref = data[data.Nationality == 'American'] prefPref = pref.pivot_table(data.Percentage.mean(), index=['Question'], column='Gender') The error is coming from where I try to get the .mean() from my ['Percentage'] list. So, how can I get the mean from the list of Percentages? Do I need to create a variable for the mean value, and if so how to I implement that into the code?
has comment: http://stackoverflow.com/comment/84799047
linked to: http://stackoverflow.com/q/47152691
tagged with: pivot-table
upvote count: 1
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84850087
score: 0
type: Comment
type: AnswerComment
has text: I added the asterisk but that didn't sort out the output in the file. Let me explore changing the method. Thanks for pointing me in the right direction.
comment on: http://stackoverflow.com/a/48902578

http://stackoverflow.com/a/48805233
score: 1
has comment: http://stackoverflow.com/comment/84613751
has comment: http://stackoverflow.com/comment/84613345
has comment: http://stackoverflow.com/comment/84614310
answers question: http://stackoverflow.com/q/48804936
downvote count: 0
has comment: http://stackoverflow.com/comment/84613504
accepted answer of: http://stackoverflow.com/q/48804936
type: AcceptedAnswer
has body: You suffer from discrete spacing issues. Try increasing the number of points: n = int(2*numpy.pi//0.01) (BTW: the int is redundant here since you using the // operator)
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84655312
score: 0
type: Comment
type: QuestionComment
has text: I just dont know why some people downvoted it
comment on: http://stackoverflow.com/q/48825644

http://stackoverflow.com/comment/84837984
has text: @ekhumoro Cool! Thanks for pointing that out, I've edited my answer to take that into account.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48915535
type: AnswerComment

http://stackoverflow.com/comment/84624021
score: 0
comment on: http://stackoverflow.com/q/48810094
type: Comment
type: QuestionComment
has text: https://stackoverflow.com/questions/38388423/what-does-on-delete-do-on-django-models

http://stackoverflow.com/q/48894087
favorite count: 0
has body: I am having trouble with splitting based on a known order with a secondary criterion in addition to distance. I have tried to manually loop through my list and cluster them based on a greedy method. But it seems inefficient, if there is a more efficient scipy package that can do the same thing and someone can point me towards it, that would be greatly appreciated. So I have a list of nodes in a specified order. list_of_nodes = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] I have a distance list which contains the distances between the nodes. distanceList = [d_01, d_12, d_23, d_34, d_45, d_56, d_67, d_78, d_89] Lastly, I have a demand list which contains the demand at each node. demandList = [dm_0, dm_1, dm_2, dm_3, dm_4, dm_51, dm_6, dm_7, dm_8, dm_9] I want to be able to split this list such that nodes of a certain max distance and max demand of each other are grouped together. groups = [0, 0, 0, 0, 0, 0, 0, 1, 1, 1] The groups list indicates that nodes 7, 8, 9 belong together as their distance (e.g. d_78 + d_89 &lt; max distance) and their demand (e.g. dm_7 + dm_8 + dm_9 &lt; max demand) are less than the specified maximum. Since the order of the list is given, I am only splitting based on the distance between points and not the full matrix of distance.
tagged with: python
has comment: http://stackoverflow.com/comment/84884074
has title: Split based on a distance list and capacity
tagged with: list
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84828164
has comment: http://stackoverflow.com/comment/84849226
has comment: http://stackoverflow.com/comment/84806224
has comment: http://stackoverflow.com/comment/84872848
score: 1
type: Question
upvote count: 1

http://stackoverflow.com/q/48894093
has body: Can someone explain how to use re.find all to separate only dates from the following strings? When the date can be either of the format- 1.1.2001 or 11.11.2001. There is volatile number of digits in the string representing days and months- import re str = "This is my date: 1.1.2001 fooo bla bla bla" str2 = "This is my date: 11.11.2001 bla bla foo bla" I know i should use re.findall(pattern, string) but to be honest I am completely confused about those patterns. I don't know how to assemble the pattern to fit in my case. I have found something like this but I absolutely don't know why there is the r letter before the pattern ... \ means start of string? d means digit? and number in {} means how many? match = re.search(r'\d{2}.\d{2}.\d{4}', text) Thanks a lot!
has answer: http://stackoverflow.com/a/48894240
linked to: http://stackoverflow.com/q/33729045
has answer: http://stackoverflow.com/a/48894182
answer count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/84794007
accepted answer: http://stackoverflow.com/a/48894309
possible better answer: http://stackoverflow.com/a/48894182
has title: re find date in string
has comment: http://stackoverflow.com/comment/84805174
score: -3
downvote count: 4
type: AnsweredQuestion
tagged with: findall
tagged with: string
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48894309
tagged with: python

http://stackoverflow.com/comment/92573885
comment on: http://stackoverflow.com/a/52451527
score: 0
type: AnswerComment
type: Comment
has text: I’ve tried with the proposal of anhoppe said here [link](https://stackoverflow.com/questions/2077870/how-to-load-a-c-sharp-dll-in-python) as indicated by @The Machine. Something seems not to work.

http://stackoverflow.com/comment/84789103
has text: Can we see it? It needs to specific the modules, either manually or with setuptools' find_packages()
type: QuestionComment
comment on: http://stackoverflow.com/q/48890084
score: 0
type: Comment

http://stackoverflow.com/q/48808997
tagged with: memory-address
has comment: http://stackoverflow.com/comment/84621065
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84621364
has title: How to read from pointer address in Python?
downvote count: 1
type: Question
upvote count: 9
has comment: http://stackoverflow.com/comment/84645551
tagged with: memory
has comment: http://stackoverflow.com/comment/84623505
answer count: 3
favorite count: 0
has body: I want to read in a Python script a number of bytes starting from a specific address. E.g., I want to read 40000 bytes starting from 0x561124456. The pointer is given from a C# app. I want to use this method to pass data between the app and script. I've used a TCP socket via localhost, but I want to try this method also. How can I do this?
has answer: http://stackoverflow.com/a/51107407
linked to: http://stackoverflow.com/q/8250625
has answer: http://stackoverflow.com/a/48809155
tagged with: python
has answer: http://stackoverflow.com/a/51200615
has comment: http://stackoverflow.com/comment/84621326
score: 8

http://stackoverflow.com/a/67937818
score: 0
has body: I got this issue solved by upgrading Django to Dajngo==1.11.29, the last release of Dajngo 1.11. I think my python version was 3.8.x. Give it a try if you are not planning to upgrade to Django 2.x or 3.x
type: Answer
answers question: http://stackoverflow.com/q/48822571

http://stackoverflow.com/a/48890897
downvote count: 0
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48890559
has body: As expected, the official documentation has the answer. On this page, you'll find the base exceptions, and the concrete exceptions as well, sorted by category. You'll find at section 5.4. Exception hierarchy an inheritance tree displaying the hierarchy between built-in exceptions. The most interesting point certainly is that every exception extends BaseException, and that a custom exception should in most cases inherit from Exception. Here is the exceptions hierarchy tree: BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError | +-- ModuleNotFoundError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError | +-- RecursionError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning

http://stackoverflow.com/a/48912699
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48912598
has body: Instead of removing the "bad" rows, you can locate and preserve the "good" rows: b = a[a.data.fillna(method='ffill').notnull()] # data #4 4.0 #5 5.0 #6 6.0 #7 2.0 #8 NaN #9 1.0
score: 2
upvote count: 2

http://stackoverflow.com/q/48854387
favorite count: 0
has answer: http://stackoverflow.com/a/59492041
has comment: http://stackoverflow.com/comment/84712404
has comment: http://stackoverflow.com/comment/84727127
has comment: http://stackoverflow.com/comment/84716310
tagged with: python
tagged with: regex
type: AnsweredQuestion
upvote count: 3
tagged with: screen-scraping
has answer: http://stackoverflow.com/a/48855256
accepted answer: http://stackoverflow.com/a/48855256
downvote count: 3
has comment: http://stackoverflow.com/comment/84712391
type: Question
has comment: http://stackoverflow.com/comment/84712739
answer count: 2
has title: How to get all emails from raw strings
score: 0
possible better answer: http://stackoverflow.com/a/59492041
tagged with: email
tagged with: web
has body: I tried this code: contents = 'alokm.014@gmail.yahoo.com.....thankyou' match = re.findall(r'[\w\.-]+@[\w\.-]+', contents) print match Result: alokm.014@gmail.yahoo.com.....thankyou I want to remove ....thankyou from my email Is it possible to obtain only alok.014@gmail.yahoo.com and one more thing the content list is bigger so I want some changes in re.findall(r'[\w\.-]+@[\w\.-]+', contents) if it is possible.

http://stackoverflow.com/a/48935145
answers question: http://stackoverflow.com/q/48932571
has comment: http://stackoverflow.com/comment/84883137
type: Answer
has comment: http://stackoverflow.com/comment/84906624
downvote count: 0
score: 1
has body: The data is requested but the html is not refreshed by the js script. You have to add the logic for the browser to load the data in the html. For example: setInterval(function() { // load the data from your endpoint into the div $.getJSON("/sys_info.json", function (data) { $.each(data, function (_, element) { $('.list-group').append('&lt;div&gt;' + elment['Batting team'] + '&lt;/div&gt;); }); }) },1000) You need the client browser to do the same you do on the server with jijna.
has comment: http://stackoverflow.com/comment/84877309
has comment: http://stackoverflow.com/comment/84894674
has comment: http://stackoverflow.com/comment/84911463
has comment: http://stackoverflow.com/comment/84911304
accepted answer of: http://stackoverflow.com/q/48932571
has comment: http://stackoverflow.com/comment/84877287
upvote count: 1
has comment: http://stackoverflow.com/comment/84903505
type: AcceptedAnswer

http://stackoverflow.com/q/48847939
answer count: 3
has comment: http://stackoverflow.com/comment/84699844
tagged with: python
favorite count: 0
score: -1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84699872
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48848055
has comment: http://stackoverflow.com/comment/112045919
has body: I need some quick help, I've been having this problem: "TypeError: 'int' object is not iterable" at line 8 in this code: sold = 0 max = 0 for i in range(0,5): print ("Scout",(i+1),"&gt; ",end="") x = int(input()) sold = sold + x for i in x: if i &gt; max: max = i print (max) Can anyone help or rearrange this for me? Im trying to make python find the maximum value from the value x.
downvote count: 1
has answer: http://stackoverflow.com/a/48847974
has title: TypeError: 'int' object is not iterable in while loops
has answer: http://stackoverflow.com/a/48848006
type: Question
upvote count: 0
has comment: http://stackoverflow.com/comment/84699826
tagged with: int

http://stackoverflow.com/q/48930217
has comment: http://stackoverflow.com/comment/84867384
answer count: 1
downvote count: 0
favorite count: 0
tagged with: markdown
score: 1
has comment: http://stackoverflow.com/comment/84867050
has comment: http://stackoverflow.com/comment/84867538
accepted answer: http://stackoverflow.com/a/48930474
has comment: http://stackoverflow.com/comment/84867152
upvote count: 1
tagged with: python
type: AnsweredQuestion
has title: Python convert markdown to html fix
type: Question
has answer: http://stackoverflow.com/a/48930474
has body: This is my actual code : import bleach import markdown html = """ **### The Facebook Campaign will be alligned:** **### What you get:** """ def render_markdown(text): if not text: return '' html = markdown.markdown(text, extensions=[ 'markdown.extensions.sane_lists', 'markdown.extensions.nl2br', ]) return bleach.clean(html, tags=[ 'p', 'h1', 'h2', 'br', 'h3', 'b', 'strong', 'u', 'i', 'em', 'hr', 'ul', 'ol', 'li', 'blockquote' ]) print render_markdown(html) problem is, same user add more time markdown code like ### What you get: , the conversion results is this : ### The Facebook Campaign will be aligned to your business goal (1 x goal per hour): ### What you get: how could I prevent this situation? i want return clean html code without rimanend markdown code in text, the perfect output is this : The Facebook Campaign will be aligned to your business goal (1 x goal per hour): What you get:

http://stackoverflow.com/q/48951957
answer count: 1
tagged with: logging
has comment: http://stackoverflow.com/comment/84916774
has title: Is it possible to disable logging entirely in Python Twisted?
tagged with: twisted
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/84914118
has comment: http://stackoverflow.com/comment/84917042
has comment: http://stackoverflow.com/comment/84913570
downvote count: 0
has answer: http://stackoverflow.com/a/48955794
favorite count: 0
type: Question
tagged with: python
has body: I notice that the generally accepted solution is to send it to /dev/null. However, by design, the log file gets rotated whenever a SIGUSR1 gets sent to twisted. This will then rotate /dev/null, which is undesired. In fact, I have half a mind to think that this is a bug. Anyway, does anyone know how to circumvent this?
upvote count: 2
accepted answer: http://stackoverflow.com/a/48955794
has comment: http://stackoverflow.com/comment/84915579

graphics
tag name: graphics
tags question: http://stackoverflow.com/q/48844863
tags question: http://stackoverflow.com/q/48944296
type: Tag
tags question: http://stackoverflow.com/q/48911463

http://stackoverflow.com/a/48939165
has body: I would recommend reading a basic Python programming tutorial (such as the official docs). Particularly, you need to study assignment statements. But as a quick reference: assignment (using the = sign) works like this: Calculate the answer of the right-hand side (evaluation) Assign the answer of #1 to the variable name on the left-hand side (assignment) If the left-hand side isn't a single variable name, this process fails, and you get an error. (In more advanced usage, you can assign to multiple variables at once using tuples, but it's different to the way you're doing it, and you won't need to learn it right now.)
answers question: http://stackoverflow.com/q/48939090
score: 0
type: Answer

http://stackoverflow.com/comment/139737515
has text: Note that if you want the axes edges to be colored too, add `mp.rcParams['axes.edgecolor'] = COLOR`.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48958263
type: Comment

http://stackoverflow.com/a/48865773
upvote count: 3
answers question: http://stackoverflow.com/q/48865605
has body: Check in both columns by str.contains and chain conditions by | (or), last filter by boolean indexing: mylist = ['GAB', 'A2M', 'GIG24'] m1 = df.Synonyms.str.contains('|'.join(mylist)) m2 = df.Symbol.str.contains('|'.join(mylist)) df = df[m1 | m2] Another solution is logical_or.reduce all masks created by list comprehension: masks = [df[x].str.contains('|'.join(mylist)) for x in ['Symbol','Synonyms']] m = np.logical_or.reduce(masks) Or by apply, then use DataFrame.any for check at least one True per row: m = df'Symbol','Synonyms'.apply(lambda x: x.str.contains('|'.join(mylist))).any(1) df = df[m] print (df) Symbol Synonyms 0 A1BG A1B|ABG|GAB|HYST2477 1 A2M A2MD|CPAMD5|FWP007|S863-7 2 A2MP1 A2MP 6 SERPINA3 AACT|ACT|GIG24|GIG25
type: Answer
downvote count: 0
score: 3

http://stackoverflow.com/q/48842112
answer count: 2
tagged with: dictionary-comprehension
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Dictionary comprehension whilst checking if key already exists?
has answer: http://stackoverflow.com/a/48842510
has body: I know you can check if a key exists using: if key in mydict: ... but I wish to somehow use this in a dictionary comprehension as I construct the dictionary. For example: mylist = [('a', 0.01), ('b', 0.02), ('c', 0.03), ('a', 0.04)] mydict = {item[0]: item[1] for item in mylist if item[0] not in mydict else blah blah} What's the best way to achieve this? I need the else part also. Edit: For clarification. In my case I actually need the sum of item[1] values for all items with a given item[0] value.
upvote count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/84688906
type: Question
score: 1
has comment: http://stackoverflow.com/comment/84688258
has comment: http://stackoverflow.com/comment/84688379
has answer: http://stackoverflow.com/a/48842180

http://stackoverflow.com/q/48912993
tagged with: bokehjs
type: AnsweredQuestion
tagged with: bokeh
has body: I have these python code from bokeh.embed import components from bokeh.plotting import figure from bokeh.models import layouts, CustomJS, Select bokeh_tools = "pan,wheel_zoom" plot_1 = figure(x_axis_type="datetime", plot_width=800, tools=bokeh_tools, title="plot_1") plot_1.line(x_values, y_values) plot_2 = figure(x_axis_type="datetime", plot_width=800, tools=bokeh_tools, title="plot_2") plot_2.line(x_values_other, y_values_other) plot_3 = figure(x_axis_type="datetime", plot_width=800, tools=bokeh_tools, title="plot_3") plot_3.line(x_values, y_values) select = Select(title="SELECT", options=["val1", "val2"]) column = layouts.Column(plot_1, select, plot_2) select.callback = CustomJS(args={"column": column, "plot_1": plot_1, "plot_2": plot_2, "plot_3": plot_3}, code=""" if(cb_obj.value === "val1"){ Bokeh.index[column.id].child_views[plot_2.id].remove(); // remove plot_2 from html //what i must to do to add generated on python side plot_3 and show it }else if(cb_obj.value === "val2"){ // some code here }""") script, div = components(column) Then this div and script i insert in html and show on the some page. On the page will visible 'plot_1', 'plot_2' and 'select' is dropdown. These plots have differents values with many lines. I want to click by selected dropdown and then change plot_2 on plot_3. What i had to do that plot_3 render in html document by clicking on dropdown? Or any other way to change rerender plots by clicking on client html ?
type: Question
answer count: 1
tagged with: javascript
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/48961696
has title: Bokeh js change or rerender one plot to another plot by clicking
accepted answer: http://stackoverflow.com/a/48961696

http://stackoverflow.com/q/48915838
tagged with: data-manipulation
tagged with: dataframe
tagged with: replace
tagged with: pandas
downvote count: 0
score: 1
linked to: http://stackoverflow.com/q/24458645
favorite count: 0
has comment: http://stackoverflow.com/comment/84838218
has comment: http://stackoverflow.com/comment/84839729
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/24458645
tagged with: python
has body: I have a data frame where I want to replace the strings with values, but want to create a new column when doing so. Note: this is a small example, I have 81 columns and many are numerical. A B C D 0 .5 Ex Ex Po 1 35 Gd TA Gd 2 52 TA Fa Ex 3 47 Bd Po Gd I'm new to python so I can only do this into a new data frame using: df_train_scaled = df_train.replace(['Ex','Gd','TA','Fa','Po'], [5, 4, 3, 2, 1]) This outputs the values in place of the string for the same column, but I want to create a new column with the replaced values like below ('original_col_name' + '_scl': A B B_scl C C_scl D D_scl 0 .5 Ex 5 Ex 5 Po 1 1 35 Gd 4 TA 3 Gd 4 2 52 TA 3 Gd 4 Ex 5 3 47 Bd 2 Po 1 Gd 4 Ultimately, I would like to select the columns that include the ordinal variables (Ex, Gd, etc.) above, replace them with the scale values (1, 2, 3, etc.), then create new columns to use for modeling. It would also be helpful so that I can run on the validation data set or be prepared to run in production. EDIT: This doesn't seem like a duplicate because I'm not simply trying to convert categorical data to numerical. I read the label encoder documentation and it just replaces a categorical value with a number. This is an ordinal set where each string represents a rank, which I'm converting to numbers. Ex - Excellent = 5 Gd - Good = 4 TA - Average = 3 etc.
has title: Pandas - Convert categorical values to number scale and create new column with replacements (not labelencode)
answer count: 0
upvote count: 1
type: Question

http://stackoverflow.com/a/48911768
has body: There is actually a difference between using and not using self. here. If you use self., you are actually adding a count and a current attribute to whatever object you are calling size on. If you don't use self., you are defining local variables called count and current in the size method. This means that if you have self., you can do something like this: my_list = LinkedList() my_list.size() print(my_list.count) If you don't use self.. The above will produce an error saying that count is not an attribute. The reason why head needs self. is because head is an instance attribute as you wrote in the __init__. And obviously you want to use the head of the current instance when you are calculating the size of the linked list. That's why you refer to it as self.head. Just head would refer to a local variable, which is not defined. As to your question of whether it is good to use self. in this case. I would say no, since the nature of count and current seems to just be helper variables that you use to calculate the size, and it does not make sense to make them an attribute of the LinkedList class.
type: Answer
answers question: http://stackoverflow.com/q/48911576
score: 0

http://stackoverflow.com/q/48959611
tagged with: sendkeys
tagged with: python
has comment: http://stackoverflow.com/comment/84935632
type: Question
score: 0
tagged with: qwerty
has body: My question is how do I use a module like keyboard.write() or shell.sendkeys() to send keystrokes that will be recognized by ALL versions of keyboards. Is there a base level dictionary so to speak that maps every key to a code, regardless of what keyboard format you use? (QWERTY, AZERTY, QWERTZ etc) It seems that all the letter keys work through different keyboard formats, but numbers and some special keys do not. For example there is no grave key (`) on AZERTY keyboards like there is on QWERTY. You have to press " Alt Gr + è" to access grave key on AZERTY.... is there some base level codes for every key? I have tried chr() which does not translate to other keyboard formats.
has comment: http://stackoverflow.com/comment/84929153
answer count: 0
type: UnansweredQuestion
has title: Low level codes for sending keys regardless of keyboard format? (QWERTY, AZERTY, etc) Python
tagged with: keyboard

http://stackoverflow.com/comment/84833804
has text: The output should be simple a simple value: Weak, Good, Fair or Excellent (a numberical representation would be nice but not strictly needed)
comment on: http://stackoverflow.com/q/48913388
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84878909
comment on: http://stackoverflow.com/a/48935962
score: 1
type: AnswerComment
has text: This works thanks! I'll check the indexes in the future. Also, it's taking a really long time to parse lol.
type: Comment

http://stackoverflow.com/comment/84913934
has text: @heemayl I thought that too, but the desired one has `’k3_3’: ‘v3’` instead of `’k3_3’: ‘v4’`
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48953557
type: Comment

image
tags question: http://stackoverflow.com/q/48931944
tags question: http://stackoverflow.com/q/48925796
tags question: http://stackoverflow.com/q/48896115
tags question: http://stackoverflow.com/q/48886830
tags question: http://stackoverflow.com/q/48953844
tags question: http://stackoverflow.com/q/48850764
tags question: http://stackoverflow.com/q/48917250
tags question: http://stackoverflow.com/q/48814937
tags question: http://stackoverflow.com/q/48846876
tags question: http://stackoverflow.com/q/48855788
tags question: http://stackoverflow.com/q/48916296
tags question: http://stackoverflow.com/q/48857725
tags question: http://stackoverflow.com/q/48816703
tags question: http://stackoverflow.com/q/48895902
tags question: http://stackoverflow.com/q/48818373
tags question: http://stackoverflow.com/q/48850987
tags question: http://stackoverflow.com/q/48916237
tags question: http://stackoverflow.com/q/48895057
tags question: http://stackoverflow.com/q/48953273
tag name: image
tags question: http://stackoverflow.com/q/48878059
tags question: http://stackoverflow.com/q/48906294
tags question: http://stackoverflow.com/q/48944819
tags question: http://stackoverflow.com/q/48846517
tags question: http://stackoverflow.com/q/48815087
type: Tag
tags question: http://stackoverflow.com/q/48842320
tags question: http://stackoverflow.com/q/48827085
tags question: http://stackoverflow.com/q/48888293
tags question: http://stackoverflow.com/q/48886637
tags question: http://stackoverflow.com/q/48884495

http://stackoverflow.com/a/48886605
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84777995
type: Answer
accepted answer of: http://stackoverflow.com/q/48886551
has comment: http://stackoverflow.com/comment/84778467
upvote count: 1
has body: You can simply just do "sudo python3 -m pip install " instead of setting the default python which could cause some issues.
answers question: http://stackoverflow.com/q/48886551

http://stackoverflow.com/comment/84704208
type: AnswerComment
score: 0
has text: Tensors are outputs of **nodes** in a graph and not a graph!
type: Comment
comment on: http://stackoverflow.com/a/48848805

http://stackoverflow.com/a/48873617
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48873499
accepted answer of: http://stackoverflow.com/q/48873499
type: AcceptedAnswer
downvote count: 0
has body: This should work: import pandas as pd employee = {'EmployeeID' : [0, 1, 2, 3, 4, 5, 6], 'LastName' : ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 'Name' : ['w', 'x', 'y', 'z', None, None, None], 'Name2' : ['H','I', None, 'J', 'K', 'L', 'M']} df = pd.DataFrame(employee) df['Name'] = df['Name'].fillna(df['Name2']) df['FullName'] = df['LastName'] + df['Name'] df = df.drop('Name2', 1) # EmployeeID LastName Name FullName # 0 0 a w aw # 1 1 b x bx # 2 2 c y cy # 3 3 d z dz # 4 4 e K eK # 5 5 f L fL # 6 6 g M gM
has comment: http://stackoverflow.com/comment/84751093

http://stackoverflow.com/q/48935590
has body: I'm trying to convert a Python object into C void pointer so that it would be callable from C API's, however the following code doesn't seem to work from ctypes import * class myclass: def __init__(self): self.val = 6 return foo = myclass() data = c_void_p(foo) Output: Traceback (most recent call last): File "test.py", line 26, in &lt;module&gt; data = c_void_p(foo) TypeError: cannot be converted to pointer I've also tried pointer() and byref(), but none of them works. How can I achieve what I'm trying to do? Thanks in advance.
tagged with: http://stackoverflow.com/tag/c
has comment: http://stackoverflow.com/comment/84878022
has comment: http://stackoverflow.com/comment/84878339
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48935804
favorite count: 0
has comment: http://stackoverflow.com/comment/84878204
tagged with: python
has comment: http://stackoverflow.com/comment/84879411
score: 2
has title: Converting Python instance to ctypes.c_void_p
type: AnsweredQuestion
upvote count: 2
accepted answer: http://stackoverflow.com/a/48935804
type: Question
tagged with: ctypes

http://stackoverflow.com/comment/84667392
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48831559
has text: Can you provide some detail on the `output` data structure? You declare it as a list of dictionaries, but then treat it as a list of two-tuples. Perhaps you meant to declare it as a dict then iterate over its items (ie `for k, v in output.items(): ...`). And what is input data? Where in this structure does the company name actually lie?

http://stackoverflow.com/a/48856871
has body: The idea would be to turn the grid off for the secondary axes and turn it on for the primary one. import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.style.use('seaborn') df_x = pd.DataFrame({"a": [100, 200, 300], "b": [40, 5, 6]}) ax = df_x.plot(figsize=(10, 6), secondary_y='b') ax.grid(axis='y') ax2 = ax.figure.axes[1] ax2.grid(False) plt.show()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48855752
type: Answer
accepted answer of: http://stackoverflow.com/q/48855752
score: 0

http://stackoverflow.com/comment/84830944
comment on: http://stackoverflow.com/a/48912203
score: 0
type: AnswerComment
type: Comment
has text: I edited accordingly, now that I know what your index looks like... :)

http://stackoverflow.com/comment/84828314
type: Comment
has text: Excellent, will try that!
comment on: http://stackoverflow.com/a/48911016
type: AnswerComment
score: 0

http://stackoverflow.com/q/48911754
has title: Transcrypt: using code from another python script causes 'TypeError: module is undefined'
has body: I am having trouble splitting code across multiple files using transcrypt (version 3.6.95). As a basic example, I have the following files in the same directory: index.htm Transcrypt test Set box content mymodule.py def helloworld(): return "Hello world!" myscript.py from mymodule import helloworld def set_box_content(): document.getElementById("box").innerHTML = helloworld() I then run python -m transcrypt -n mymodule.py python -m transcrypt -n myscript.py Which runs without error and generates mymodule.js, mymodule.mod.js, myscript.js and myscript.mod.js in the directory __javascript__. When I open index.htm in Firefox 58 and open the console it says 'TypeError: module is undefined'. I have tried adding to the HTML but this does not help. I read through this part of the transcrypt documentation, but the -u switch does not appear in the list of available commands when I type python -m transcrypt -h.
tagged with: javascript
tagged with: transcrypt
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48912026
favorite count: 0
tagged with: python
type: AnsweredQuestion
upvote count: 3
type: Question
score: 3
has answer: http://stackoverflow.com/a/48912026

http://stackoverflow.com/q/48917403
answer count: 0
has comment: http://stackoverflow.com/comment/84842494
type: UnansweredQuestion
has body: I am running a function that changes a label value in a thread while my tkinter is running. This code works unless I close the window before my thread stops. I have attached the error below. How can I fix this problem? Is there a better way to set up these threads when using tkinter? Code (works unless I close GUI window early): from tkinter import * from tkinter import ttk import threading import time def fun(): for i in range(10): var.set(var.get() + 1) print(var.get()) time.sleep(.5) t = threading.Thread(target=fun) root = Tk() var = IntVar() var.set(0) mainframe = ttk.Frame(root) mainframe.grid(column = 0, row = 0) label = ttk.Label(mainframe, textvariable=var) label.grid(column = 0, row = 0) t.start() root.mainloop() t.join() print('Done') Error when I close GUI window before fun() has finished running: Exception in thread Thread-1: Done Traceback (most recent call last): File "C:\Users\PC-User\AppData\Local\Programs\Python\Python36-32\Lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\PC-User\AppData\Local\Programs\Python\Python36-32\Lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:/Users/PC-User/PycharmProjects/Arb/example.py", line 8, in fun var.set(var.get() + 1) File "C:\Users\PC-User\AppData\Local\Programs\Python\Python36-32\Lib\tkinter\__init__.py", line 503, in get value = self._tk.globalgetvar(self._name) RuntimeError: main thread is not in main loop
has title: Python - Error in thread when closing tkinter GUI window
tagged with: python
has comment: http://stackoverflow.com/comment/84843000
has comment: http://stackoverflow.com/comment/84841632
type: Question
has comment: http://stackoverflow.com/comment/84841590
has comment: http://stackoverflow.com/comment/84841560
score: 0
has comment: http://stackoverflow.com/comment/84841450
has comment: http://stackoverflow.com/comment/84880590
tagged with: tkinter

http://stackoverflow.com/q/48805801
has body: I'm trying to install the requests module on Mac following this tutorial http://docs.python-requests.org/en/master/user/install/ when I do the command pip install I get the following error: Processing /Users/thomasmakkink/Documents/Acsone/Obfg/requests Collecting chardet&lt;3.1.0,&gt;=3.0.2 (from requests==2.18.4) Using cached chardet-3.0.4-py2.py3-none-any.whl Collecting idna&lt;2.7,&gt;=2.5 (from requests==2.18.4) Using cached idna-2.6-py2.py3-none-any.whl Collecting urllib3&lt;1.23,&gt;=1.21.1 (from requests==2.18.4) Using cached urllib3-1.22-py2.py3-none-any.whl Collecting certifi&gt;=2017.4.17 (from requests==2.18.4) Using cached certifi-2018.1.18-py2.py3-none-any.whl Installing collected packages: chardet, idna, urllib3, certifi, requests Exception: Traceback (most recent call last): File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_set.py", line 784, in install **kwargs File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Er…
has comment: http://stackoverflow.com/comment/84614440
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84614556
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48805885
has comment: http://stackoverflow.com/comment/84614379
score: 1
upvote count: 1
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84614406
has title: Installing request for python on Mac
type: Question

http://stackoverflow.com/a/48867950
type: Answer
has body: python2.7 might already be on the PATH, but if not you can do /usr/local/opt/python/bin/python2.7 -m pip install imageio Or you can install a Jupyter kernel for your system's Python
score: 0
answers question: http://stackoverflow.com/q/48867682
has comment: http://stackoverflow.com/comment/84749951

http://stackoverflow.com/comment/84878064
type: Comment
has text: I did it but still I get error as I have written at the end of my message. I did install version 1.3.0 and 1.4.1 but none worked.
comment on: http://stackoverflow.com/a/48935551
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84880064
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48936580
has text: Wow, can you explain a little bit for the replace('.', '-', regex=True) part ?

http://stackoverflow.com/comment/84614935
score: 0
has text: You should be targeting Python 3 now anyway, unless you have a very specific reason you need to target legacy systems (in which please tag with [tag:python-2.7] explicitly).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48805910

http://stackoverflow.com/q/48911285
tagged with: pandas
answer count: 1
accepted answer: http://stackoverflow.com/a/48911658
has comment: http://stackoverflow.com/comment/84829105
has comment: http://stackoverflow.com/comment/84829576
tagged with: python
type: AnsweredQuestion
has title: Python pandas plot TypeError
has answer: http://stackoverflow.com/a/48911658
type: Question
tagged with: matplotlib
has body: I have a data frame that looks like: CreateDate Store Orders_am Orders_pm 0 2018-01-21 2001 56 2 1 2018-01-21 2002 51 4 2 2018-01-21 2003 85 0 dtypes for the data frame are: CreateDate datetime64[ns] Store int64 Orders_am int64 Orders_pm int64 I'm trying to create a simple plot using the following: plt.plot(df.groupby("Store").plot(x="CreateDate", y="Orders_am")) But it's throwing the following error: TypeError: float() argument must be a string or a number, not 'AxesSubplot' I'm assuming that it's choking on CreateDate - but I can't figure out how to solve it.
score: 0

http://stackoverflow.com/q/48937872
score: 0
tagged with: python
has body: So I have these two models Lecture and FileUpload. I want that the user to be able to add a lecture to a specific course and also upload multiple files for that lecture. Thing is that after I submit the form the information gets saved except for the uploaded files, so I am guessing something is wrong with my formset. Please have a look: FileFormset = inlineformset_factory(Lecture, FileUpload, exclude=[]) def classroom(request): if request.method == 'POST': form1 = LectureForm(request.POST) if form1.is_valid(): lecture = form1.save() formset = FileFormset(request.POST, request.FILES, instance=lecture, prefix='files') if formset.is_valid(): formset.save() else: print(formset.errors) formset.save() return redirect('courses:index') else: form1 = LectureForm() formset = FileFormset() context = {'teacher_data': TeacherData.objects.all(), 'teachers': Teacher.objects.all(), 'courses': Course.objects.all(), 'form1': form1, 'formset': formset, } return render(request, 'courses/classroom.html', context) {% csrf_token %} {{ form1.as_p }} {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %} Add Lecture class LectureForm(forms.ModelForm): class Meta: model = Lecture fields = ('course', 'lecture_title', 'lecture_category', 'content') class FileForm(forms.ModelForm): class Meta: model = FileUpload fields = ('files',) class Lecture(models.Model): LECTURE_CHOICES = ( ('Courses', 'Courses'), ('Seminars', 'Seminars'), ) course = models.ForeignKey('Course', on_delete=models.CASCADE, default='', related_name='lectures',) lecture_category = models.CharField(max_length=10, choices=LECTURE_CHOICES, default='Courses',) lecture_title = models.CharField(max_length=100, blank=True, null=True) content = models.TextField(blank=True, null=True) def __str__(self): return str(self.lecture_title) class FileUpload(models.Model): files = models.FileField(upload_to='documents', null=True, blank=True) lecture = models.ForeignKey('Lecture', related_name='files', on_delete=None, …
tagged with: django
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48942241
has title: Django formset not saving my files
answer count: 1
accepted answer: http://stackoverflow.com/a/48942241

http://stackoverflow.com/a/48936982
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84890861
has comment: http://stackoverflow.com/comment/84885585
answers question: http://stackoverflow.com/q/48913931
has body: Thats what I did: #!/bin/python3 import sys def breakingRecords(score): # Complete this function min = -1 minCount = 0 maxCount = 0 for s in score: if min == -1: min = s max = s continue if s &lt; min: min = s minCount+=1 if s &gt; max: max = s maxCount+=1 return maxCount, minCount if __name__ == "__main__": n = int(input().strip()) score = map(int,input().strip().split(' ')) result = breakingRecords(score) print(" ".join(map(str, result))) I think I left the original code part in - thats all below the if __name__ == "__main__":

http://stackoverflow.com/a/48820437
has body: You said your files are in Users/myname/Documents/Programming folder. However, the error message is complaining about a different folder - Users/myname/Downloads folder. Check your paths and make sure the files are in the correct folders.
score: 0
accepted answer of: http://stackoverflow.com/q/48820312
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84665573
answers question: http://stackoverflow.com/q/48820312
type: Answer

http://stackoverflow.com/q/48834817
tagged with: python
has body: I have a mixed integer programming problem, (cutting stock with column generation), that I've solved in AMPL and I'm ported to Python using cvxopt. CVXOPT "op" doesn't provide the binary variable option that I need, so I'm extending it with GLPK to use "ILP". I'm getting the ilp status = "LP relaxation is primal infeasible", which I know isn't right because of the prior AMPL solution. So I know I have it configured incorrectly. I'm trying to understand that the use of the integer "I" &amp; the binary "B" keys by playing around with the example in the stackoverflow question The integer linear programming(ILP) function in CVXOPT returns non integers. My question is, what's the difference between the I&amp;B keys, such that: stat, sol1 = glpk.ilp(W, G.T, h, I=set([0, 1])) stat, sol2 = glpk.ilp(W, G.T, h, I={0,1}) stat, sol3 = glpk.ilp(W, G.T, h) has the 3 different solutions below: (print(soli.T) [ 0.00e+00 0.00e+00 5.00e-01 5.00e-01 5.00e-01 -0.00e+00 ... ] [ 0.00e+00 0.00e+00 5.00e-01 5.00e-01 5.00e-01 -0.00e+00 ... ] [ 5.00e-01 5.00e-01 5.00e-01 5.00e-01 5.00e-01 -0.00e+00 ... ] I've looked at help(ilp), but it just says that I&amp;B are sets of indicies of the integer and binary variables, (which I understand), but it doesn't describe what happens if you use both (I&amp;B), or they overlap, or one or the other is the empty set, or not defined. I would have thought that sol1=sol2 above, since it is just two different ways to define the set I. I presume sol3 is all integer and no binary variables since B is left undefined, but I don't have any documentation to confirm that.
tagged with: mixed-integer-programming
has comment: http://stackoverflow.com/comment/84680233
has title: cvxopt.glpk.ilp documentation on Integer & Binary set keys
type: Question
score: 5
has answer: http://stackoverflow.com/a/48891798
upvote count: 5
tagged with: cvxopt
has comment: http://stackoverflow.com/comment/84708650
answer count: 1
downvote count: 0
tagged with: glpk
favorite count: 0
linked to: http://stackoverflow.com/q/39384909
type: UnansweredQuestion

http://stackoverflow.com/comment/84640188
type: Comment
has text: When i try the 'category' option I get an error: `ValueError: Categorial categories cannot be null`
comment on: http://stackoverflow.com/a/48817973
type: AnswerComment
score: 0

http://stackoverflow.com/q/48810444
type: Question
has title: Django: Loop over 2 objects in same loop in template
tagged with: django-views
upvote count: 4
has comment: http://stackoverflow.com/comment/84624452
has answer: http://stackoverflow.com/a/48810929
answer count: 1
downvote count: 0
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/84625072
has comment: http://stackoverflow.com/comment/84624850
tagged with: python
type: AnsweredQuestion
tagged with: django-templates
accepted answer: http://stackoverflow.com/a/48810929
has body: I have two models that are related, and I need to create a table that takes from both objects. In my models: class Chamber(models.Model): chamber_name = models.CharField(max_length=100) chamber_type = models.CharField(max_length=50) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) class ChamberProperties(models.Model): chamber = models.ForeignKey(Chamber, on_delete=models.CASCADE) property_name = models.CharField(max_length=20) property_value = models.CharField(max_length=100) The structure is strange, but it's too late to just add properties and values to the chamber model. I'll have to live with the fact that they are two separate models. In my table I need the following structure: chamber_name(obj A) - property_value(obj B) - customer(obj A again) I tried zipped lists, but I don't seem to be able to unpack it: class ChambersView(generic.DetailView): template_name = 'pages/chambers.html' def get(self, request): user = User.objects.get(username=request.user) customer = Customer.objects.get(user=user) chambers_list = list(Chamber.objects.filter(customer=customer)) chamber_properties = list(ChamberProperties.objects.filter(chamber__in=chambers_list).order_by('id')) objects_list = zip(chamber_properties, chambers_list) form = ChambersFilterForm(request=request) return render(request, self.template_name, {'filter_form':form, 'objects_list': objects_list}) If I unpack it in python it works: for properties, chambers in objects_list: print("-----------------------------------------------------------") print("Property is: ", properties.property_value, "and the chamber is:", chambers.chamber_name) print("-----------------------------------------------------------") But when I go to my HTML template: Chamber Property Value Customer {% for properties, chambers in objects_list %} {{chambers.chamber_name}} {{properties.property_value}} {{chambers.customer}} {% endfor %} The table comes up empty. There are no errors, no logs, the server works fine. If I just do {…
tagged with: django
has comment: http://stackoverflow.com/comment/84624963

http://stackoverflow.com/q/48897252
tagged with: python
linked to: http://stackoverflow.com/q/20449427
type: UnansweredQuestion
score: 0
duplicate of: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/84800441
has title: python (baseball game) TypeError : not all arguments converted during string formatting
has comment: http://stackoverflow.com/comment/84800133
has comment: http://stackoverflow.com/comment/84800170
duplicate of: http://stackoverflow.com/q/45499191
type: Question
has comment: http://stackoverflow.com/comment/84800373
answer count: 1
has answer: http://stackoverflow.com/a/48897279
tagged with: typeerror
has body: import random q=[0,0,0,0] p=random.randint(1000,9999) def div_1(x): A = [0,0,0,0] A[0]= (x-(x%1000))/1000 A[1]= (x-(x%100))/100 -10*A[0] A[2]= (x-(x%10))/10 -100*A[0] - 10*A[1] A[3]= x -1000*A[0] - 100*A[1] - 10*A[2] return A ranq = div_1(p) m=1 while 1: n=input("Enter number: ") q = div_1(n) S=0 B=0 O=0 i=0 j=0 for i in range(0, 3): for j in range(0, 3): if(ranq[i]==q[j]): if(i==j): S+=1 else: B+=1 j+=1 i+=1 print("Strike: {0} Ball: {1} Try: {2} \n".format(S, B, m)) m+=1 if S==4: print("Bingo!") break if(m&lt;10): print("Error!") break else: continue Can u guys solve this error? the script keeps giving me TypeError: not all arguments converted during string formatting... this code is written in python version 3.6 ================================================================================

http://stackoverflow.com/q/48915248
has comment: http://stackoverflow.com/comment/84837619
has comment: http://stackoverflow.com/comment/84836969
has body: Given I have a list of tuples like this: [('a', 'c'), ('b', 'c'), ('f', 'g'), ('e', 'f'), ('b', 'd')] or [['a', 'c'], ['b', 'c'], ['f', 'g'], ['e', 'f'], ['b', 'd']] I want to merge every tuple/list that has one matching element (the position doesn't matter). The above should result in (order doesn't matter): [['a', 'c', 'b', 'd'], ['f', 'g', 'e']] For sure I could write a recursive function merging every tuple/list until there is no more merge able tuple/list. But I'm looking for a existing function / function in python or in a package that can do this preferably in a one liner.
favorite count: 0
has comment: http://stackoverflow.com/comment/84838365
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84837707
has comment: http://stackoverflow.com/comment/84837016
has comment: http://stackoverflow.com/comment/84837060
answer count: 0
has comment: http://stackoverflow.com/comment/84837159
has comment: http://stackoverflow.com/comment/84836956
type: Question
has comment: http://stackoverflow.com/comment/84838143
has comment: http://stackoverflow.com/comment/84837024
has comment: http://stackoverflow.com/comment/84837058
has title: How to reduce list of tuples/lists with equal elements to sub graphs?
has comment: http://stackoverflow.com/comment/84838224
upvote count: 3
score: 0
has comment: http://stackoverflow.com/comment/84837481
downvote count: 3
has comment: http://stackoverflow.com/comment/84837964
has comment: http://stackoverflow.com/comment/84837198

http://stackoverflow.com/q/48817433
downvote count: 0
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48818843
tagged with: django
tagged with: export-to-excel
has body: I need just export data from my admin. My code now looks like: models.py from django.db import models from services.models import Services,PromoCodes,CauseOfReservedPromocodes # Create your models here. class User(models.Model): name=models.CharField(max_length=200) surname=models.CharField(max_length=200) email=models.EmailField() password=models.CharField(max_length=200) telephone=models.PositiveIntegerField(max_length=12,blank=True,null=True) userRequest=models.ForeignKey('UsersRequests', blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.name + " " + self.surname class UsersRequests(models.Model): date = models.DateField() requestChannel = models.CharField(max_length=30) problem = models.CharField(max_length=200) solution = models.CharField(max_length=200) def __unicode__(self): return str(self.date) + " " + str(self.requestChannel) + " " + str(self.problem) + " " + str(self.solution) And my admin.py is: from django.contrib import admin from .models import User,UsersRequests from import_export import resources, widgets, fields from import_export.admin import ImportExportModelAdmin,ExportMixin class UsersResource(resources.ModelResource): class Meta: model = User fields = ('id', 'name', 'email', 'telephone', 'userRequest') class UserAdmin(ImportExportModelAdmin): resource_class = UsersResource @admin.register(User) class UserAdmin(ImportExportModelAdmin): search_fields = ('name', 'surname', 'email', 'telephone') I try everything to get userRequest work, but it send just integer - id for userRequest. How to get full data from class UsersRequests(models.Model)?
type: Question
has comment: http://stackoverflow.com/comment/84639783
has title: django-import-export :ForeignKey with many fields
upvote count: 1
answer count: 1
favorite count: 0
tagged with: django-import-export
tagged with: python

http://stackoverflow.com/a/48942821
answers question: http://stackoverflow.com/q/48942762
accepted answer of: http://stackoverflow.com/q/48942762
upvote count: 2
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84892389
type: Answer
downvote count: 2
has body: First of all add() is in-place operation and it returns nothing so when you are doing fd['a'] = fs.add('x') then 'x' gets added to list inside set and returns 'None' which gets assigned to dictionary 'fd' that the reason for dictionary key 'a' you're observing None. To solve this problem assign set object to dictionary key like fd['a'] = fs. I hope this helps (: code: fd = {} fs = set() fs.add('x') fs.add('y') fd['a'] = fs print fd output: {'a': set(['y', 'x'])}
has comment: http://stackoverflow.com/comment/84892390

http://stackoverflow.com/q/48952003
type: Question
has body: I have a training model that takes all training data and creates a queue: x = tf.placeholder(tf.float32, (N, steps, size), name='x') y = tf.placeholder(tf.float32, (N, out_size), name='y') var_x = tf.Variable(x, trainable=False, collections=[]) var_y = tf.Variable(y, trainable=False, collections=[]) x_queue, y_queue = tf.train.slice_input_producer([var_x, var_y], num_epochs=10, shuffle=True) x_batch, y_batch = tf.train.batch([x_queue, y_queue], batch_size=batch_size) ... with tf.Session() as sess: sess.run(var_x, feed_dict={x: X}) sess.run(var_y, feed_dict={y: Y}) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord) ... This network works fine and I am able to train it. In this network I'd like to add a new placeholder that takes my test data: x_test = tf.placeholder(tf.float32, (1, steps, size), name='x_test') And I'd like to use tf.cond to control which placeholder gets fed: rnn_inputs = tf.cond(is_train, lambda: x, lambda: x_test) However, a lot of posts say using tf.cond is not efficient. In addition, using a new placeholder for test/validation data is a problem since tensorflow throws an error asking me to feed data into it even if I am trying to train the model. Is there a standard way of doing this?
answer count: 1
tagged with: neural-network
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/48952641
tagged with: tensorflow
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48952641
has title: What is a standard way to add tf.placeholder for test/validation data with queue runners

http://stackoverflow.com/q/48829294
linked to: http://stackoverflow.com/q/46364876
accepted answer: http://stackoverflow.com/a/48829849
type: Question
tagged with: python
upvote count: 2
has title: Wide and deep tensorflow tutorial: Why do you test using only a batch of your evaluation dataset?
tagged with: machine-learning
linked to: http://stackoverflow.com/q/46529834
answer count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48829849
tagged with: neural-network
tagged with: deep-learning
type: AnsweredQuestion
score: 2
downvote count: 0
has body: I'm trying to understand the TensorFlow Wide &amp; Deep Learning Tutorial. The census income dataset has two files for validation: adult.data and adult.test. After a certain number of epochs, it prints an evaluation (you can see the complete code here: https://github.com/tensorflow/models/blob/master/official/wide_deep/wide_deep.py). It uses "input_fn" to read input information from a csv file. It's used to read both files, adult.data and adult.test. def input_fn(data_file, num_epochs, shuffle, batch_size): """Generate an input function for the Estimator.""" assert tf.gfile.Exists(data_file), ( '%s not found. Please make sure you have either run data_download.py or ' 'set both arguments --train_data and --test_data.' % data_file) def parse_csv(value): print('Parsing', data_file) columns = tf.decode_csv(value, record_defaults=_CSV_COLUMN_DEFAULTS) features = dict(zip(_CSV_COLUMNS, columns)) labels = features.pop('income_bracket') return features, tf.equal(labels, '&gt;50K') # Extract lines from input files using the Dataset API. dataset = tf.data.TextLineDataset(data_file) if shuffle: dataset = dataset.shuffle(buffer_size=_NUM_EXAMPLES['train']) dataset = dataset.map(parse_csv, num_parallel_calls=5) # We call repeat after shuffling, rather than before, to prevent separate # epochs from blending together. dataset = dataset.repeat(num_epochs) dataset = dataset.batch(batch_size) return dataset It builds an estimator, DNNLinearCombinedClassifier, and evaluates and prints the accuracy like this: ... results = model.evaluate(input_fn=lambda: input_fn( FLAGS.test_data, 1, False, FLAGS.batch_size)) # Display evaluation metrics print('Results at epoch', (n + 1) * FLAGS.epochs_per_eval) print('-' * 60) for key in sorted(results): print('%s: %s' % (key, results[key])) I understand you should train your network with batches. My question is, why would they evaluate the model with a batch? Shouldn't they use the entire evaluation dataset? The dataset has 16281 validation values, s…
favorite count: 0

http://stackoverflow.com/comment/84832571
comment on: http://stackoverflow.com/q/48912747
type: Comment
has text: If we just give you code @YashKaushik, that really won't help you learn. When given homework, the goal is to become a good problem solver. Here's some hints though. **(1)** You'll need a `for`-loop to iterate over each message. **(2)** You'll need a variable to store each message. **(3)** Think about the logic of your program. While iterating, if the current string starts with `'New: '`, you need to store the current message and reset the message holding variable. Otherwise, add the current string to the current message. If you sit down and think through this, I know you can solve it!
type: QuestionComment
score: 1

http://stackoverflow.com/comment/84698210
type: Comment
comment on: http://stackoverflow.com/a/48846954
score: 0
type: AnswerComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ yep , that is great improvement :-)

http://stackoverflow.com/comment/84722737
score: 0
comment on: http://stackoverflow.com/q/48859410
type: Comment
type: QuestionComment
has text: vote the answer if its rigth

http://stackoverflow.com/a/48858676
has body: Try: &gt;&gt;&gt; a[x[:,None], y[None,:], b] array([[ 0, 21, 42, 63], [ 84, 105, 126, 147], [168, 189, 210, 231]]) Discussion You tried a[x,y,b]. Note the error message: &gt;&gt;&gt; a[x, y, b] Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (4,) (3,4) The (3,) means that we need to extend x to have 3 as the first dimension and 4 as the second dimension. We do this by specifying x[:,None] (which actually allows x to be broadcast to any size second dimension). Similarly, the error message shows that we need to map y to shape (3,4) and we do that with y[None,:]. Alternative style If one prefers, we can replace None with np.newaxis: &gt;&gt;&gt; a[x[:,np.newaxis], y[np.newaxis,:], b] array([[ 0, 21, 42, 63], [ 84, 105, 126, 147], [168, 189, 210, 231]]) np.newaxis is None: &gt;&gt;&gt; np.newaxis is None True (If I recall correctly, some earlier versions of numpy used a different capitalization style for newaxis. For all versions, though, None seems to works.)
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48858600
score: 5
upvote count: 5

http://stackoverflow.com/q/48947026
tagged with: python
has comment: http://stackoverflow.com/comment/84900562
score: -2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48947244
type: Question
tagged with: function
upvote count: 0
has title: Variable number of arguments in function
accepted answer: http://stackoverflow.com/a/48947244
tagged with: multiple-arguments
answer count: 1
has comment: http://stackoverflow.com/comment/84900773
favorite count: 0
has comment: http://stackoverflow.com/comment/84900460
has body: Is it possible to run a function like this: def call(a,*alphabets,*numbers): print(a) print(alphabets) print(numbers) I'm getting the following error: File "&lt;ipython-input-331-ddaef8a7e66f&gt;", line 1 def call(a,*alphabets,*numbers): ^ SyntaxError: invalid syntax Can somebody tell me if there's an alternative way to do this?
downvote count: 2
has comment: http://stackoverflow.com/comment/84900618
tagged with: arguments

http://stackoverflow.com/comment/84781414
has text: (*Spyder maintainer here*) This looks like a bug. Please report it in our [issues tracker](https://github.com/spyder-ide/spyder/issues)
score: 1
comment on: http://stackoverflow.com/q/48881224
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48939277
tagged with: saleor
score: 0
tagged with: e-commerce
answer count: 1
has answer: http://stackoverflow.com/a/48961582
has title: GraphQL support with django-saleor Ecomm platform
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: I need to know to what degree saleor supports GraphQL? My understanding is that the front end is just django templates, but I see a graphql folder there, so what is it? I was told by the moderators to take a look into the demo branch. I need to know how different is it compared to the master branch.
type: Question

http://stackoverflow.com/q/48847922
has comment: http://stackoverflow.com/comment/84699776
has body: I am trying to convert binary value strings into ASCII values on Python 3. Let's say the letter 'l' in ASCII has a binary value of 01101100. If the '01101100' is represented as a string, how would you convert that string into the ASCII value in Base 10 form (108) into the ASCII character itself?
linked to: http://stackoverflow.com/q/8928240
tagged with: data-conversion
duplicate of: http://stackoverflow.com/q/8928240
type: Question
has comment: http://stackoverflow.com/comment/84699778
tagged with: ascii
score: 0
has title: How do you convert binary value strings into ASCII values in Python 3?
tagged with: binary
answer count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48945911
downvote count: 0
has body: The price is later added by the browser which renders the page using javascript code found in the html. If you disable javascript in your browser, you would notice that the page would look a bit different. Also, take a look at the page source, usually that's unaltered, to see that the tag you're looking for doesn't exist (yet). Scrapy doesn't execute any javascript code. It receives the plain html and that's what you have to work with. If you want to extract data from pages which look the same as in the browser, I recommend using an headless browser like Splash (if you're already using scrapy): https://github.com/scrapinghub/splash You can programaticaly tell it to download your page, render it and select the data points you're interested in. The other way is to check for the request made to the Asos API which asks for the product data. In your case, for this product: http://www.asos.com/api/product/catalogue/v2/stockprice?productIds=9065343&amp;currency=AUD&amp;keyStoreDataversion=0ggz8b-4.1&amp;store=AU I got this url by taking a look at all the XMLHttpRequest (XHR) requests sent in the Network tab found in Developers Tools (on Google Chrome).
score: 1
answers question: http://stackoverflow.com/q/48945567
upvote count: 1
type: Answer

http://stackoverflow.com/comment/84758069
type: Comment
comment on: http://stackoverflow.com/a/48876624
score: 0
type: AnswerComment
has text: I see, that wont require I use any HTML templates right? I'm just trying to use requests. What you're saying is that I should construct the form in my view?

http://stackoverflow.com/comment/84714474
has text: You want a faster solution, but what do you mean by "faster", when you haven't shown your own solution?
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48855492

global
type: Tag
tag name: global
tags question: http://stackoverflow.com/q/48838029
tags question: http://stackoverflow.com/q/48910561

numpy
tags question: http://stackoverflow.com/q/48934811
tags question: http://stackoverflow.com/q/48859008
tags question: http://stackoverflow.com/q/48818373
tags question: http://stackoverflow.com/q/48919157
tags question: http://stackoverflow.com/q/48939455
tags question: http://stackoverflow.com/q/48871438
tags question: http://stackoverflow.com/q/48879587
tags question: http://stackoverflow.com/q/48846257
tags question: http://stackoverflow.com/q/48818335
tags question: http://stackoverflow.com/q/48898406
tags question: http://stackoverflow.com/q/48958509
tags question: http://stackoverflow.com/q/48897873
tags question: http://stackoverflow.com/q/48952443
tags question: http://stackoverflow.com/q/48856497
tags question: http://stackoverflow.com/q/48907651
tags question: http://stackoverflow.com/q/48897486
tags question: http://stackoverflow.com/q/48929634
tags question: http://stackoverflow.com/q/48962594
tags question: http://stackoverflow.com/q/48873995
tags question: http://stackoverflow.com/q/48917460
tags question: http://stackoverflow.com/q/48900858
tags question: http://stackoverflow.com/q/48948769
tags question: http://stackoverflow.com/q/48839626
tags question: http://stackoverflow.com/q/48824842
tags question: http://stackoverflow.com/q/48887461
tags question: http://stackoverflow.com/q/48928944
tags question: http://stackoverflow.com/q/48938251
tags question: http://stackoverflow.com/q/48817300
tags question: http://stackoverflow.com/q/48864890
tags question: http://stackoverflow.com/q/48804936
tags question: http://stackoverflow.com/q/48926156
tags question: http://stackoverflow.com/q/48847798
tags question: http://stackoverflow.com/q/48828568
tags question: http://stackoverflow.com/q/48920120
tags question: http://stackoverflow.com/q/48931887
tags question: http://stackoverflow.com/q/48854578
tags question: http://stackoverflow.com/q/48917761
tags question: http://stackoverflow.com/q/48867620
tags question: http://stackoverflow.com/q/48875590
tags question: http://stackoverflow.com/q/48935422
tags question: http://stackoverflow.com/q/48938877
tags question: http://stackoverflow.com/q/48819547
tags question: http://stackoverflow.com/q/48950473
tags question: http://stackoverflow.com/q/48886648
tags question: http://stackoverflow.com/q/48828484
tags question: http://stackoverflow.com/q/48899255
tags question: http://stackoverflow.com/q/48843102
tags question: http://stackoverflow.com/q/48952228
tags question: http://stackoverflow.com/q/48865972
tags question: http://stackoverflow.com/q/48895397
tags question: http://stackoverflow.com/q/48853311
tags question: http://stackoverflow.com/q/48818277
tags question: http://stackoverflow.com/q/48846980
tags question: http://stackoverflow.com/q/48847417
tags question: http://stackoverflow.com/q/48907067
tags question: http://stackoverflow.com/q/48847856
tags question: http://stackoverflow.com/q/48900310
tags question: http://stackoverflow.com/q/48852022
tags question: http://stackoverflow.com/q/48887986
tags question: http://stackoverflow.com/q/48953373
tags question: http://stackoverflow.com/q/48829633
tags question: http://stackoverflow.com/q/48893445
tags question: http://stackoverflow.com/q/48815385
tags question: http://stackoverflow.com/q/48844322
tags question: http://stackoverflow.com/q/48912313
tags question: http://stackoverflow.com/q/48913031
tags question: http://stackoverflow.com/q/48870709
tags question: http://stackoverflow.com/q/48942424
tags question: http://stackoverflow.com/q/48929508
tags question: http://stackoverflow.com/q/48822715
tags question: http://stackoverflow.com/q/48816718
tags question: http://stackoverflow.com/q/48896441
tags question: http://stackoverflow.com/q/48912427
tags question: http://stackoverflow.com/q/48865868
tags question: http://stackoverflow.com/q/48880363
tags question: http://stackoverflow.com/q/48856982
tags question: http://stackoverflow.com/q/48850394
tags question: http://stackoverflow.com/q/48928253
tags question: http://stackoverflow.com/q/48819240
tags question: http://stackoverflow.com/q/48863068

http://stackoverflow.com/comment/84879678
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48936045
has text: the function is `sqrt(4 - y**2 - x**2)`, the bounds of the outer integral is 0 to 2, and the bounds for the inner integral is `sqrt(2 * y - y**2)` to `sqrt(4 - y**2)`, which evaluates to 16/9. (1.777 repeating)
score: 0

http://stackoverflow.com/a/48853032
downvote count: 0
type: Answer
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48852976
score: 6
has body: Its because you are closing the browser every time loop ends , you just need to keep driver.close() outside the loop. import json from selenium.webdriver import Chrome with open('path to json file', encoding='utf-8') as s: data = json.loads(s.read()) for site in data['sites']: driver = Chrome('path to chrome driver') driver.get(data['sites'][site]) driver.get_screenshot_as_file(site + '.png') driver.close()
answers question: http://stackoverflow.com/q/48852976
type: AcceptedAnswer

http://stackoverflow.com/a/48852961
has comment: http://stackoverflow.com/comment/118417802
downvote count: 1
upvote count: 12
has body: you can use a dictionary: my_dict = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2} then use list comprehension: z = [my_dict[zi] for zi in z]
has comment: http://stackoverflow.com/comment/84926820
type: Answer
score: 11
answers question: http://stackoverflow.com/q/48852930

http://stackoverflow.com/q/48847966
tagged with: python
tagged with: list
type: UnansweredQuestion
has title: Return other value in a 2-element set Python
tagged with: set
downvote count: 1
score: -1
type: Question
upvote count: 0
has answer: http://stackoverflow.com/a/48848001
answer count: 1
tagged with: runtime
has body: given a value in an immutable set of two values, how do I access what the other value is? It needs to be in a set of sets, so I'm not sure how else I would do it without frozenset. example: myset = frozenset([a,b]) given a, how do I access the value of b? context: so I'm iterating over a set of sets data = [(a list of lists)] movies = set(frozenset(d[:2]) for d in data) for movie in movies: ...if a in movie: ...other_value = b thanks
has comment: http://stackoverflow.com/comment/84699889
favorite count: 0

http://stackoverflow.com/q/48926974
favorite count: 0
tagged with: tuples
has answer: http://stackoverflow.com/a/48931433
tagged with: python
accepted answer: http://stackoverflow.com/a/48931433
tagged with: dictionary
linked to: http://stackoverflow.com/q/40340133
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84861122
tagged with: http://stackoverflow.com/tag/json
has body: I have following list of tuples [ ('A-1', 'B-1', 'C'), ('A-1', 'B-2', 'D'), ('A-1', 'B-3', 'E'), ('A-1', 'B-4', 'F'), ('A-1', 'B-5', 'G') ] and I want to create following dictionary of dictionaries: {A:{"A-1":{"B":{"B-1":"C","B-2":"D","B-3":"E","B-4":"F","B-5":"G"}}}} What is the best option? I have to extract data from a bbdd and generate a JSON file so this conversion will be done many times and it is needed the most efficient solution
type: Question
upvote count: 2
score: 0
downvote count: 2
answer count: 1
has title: Merge list of tuples to a dictionary

http://stackoverflow.com/comment/84744305
type: Comment
comment on: http://stackoverflow.com/q/48814216
score: 0
type: QuestionComment
has text: You seem to be following correct sample code on how to achieve this. If you paste your code here, perhaps we can help debug it.

http://stackoverflow.com/q/48899527
has comment: http://stackoverflow.com/comment/84808968
has answer: http://stackoverflow.com/a/48899693
type: Question
has title: Plot histogram from unbinned file in python
has comment: http://stackoverflow.com/comment/84806829
has comment: http://stackoverflow.com/comment/84806784
score: 0
has comment: http://stackoverflow.com/comment/84809515
has comment: http://stackoverflow.com/comment/84805993
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48899693
has body: I have a json file data (2Go) where each line is (threadTitle, numberOfSubscribers) thread1 1092 thread2 44481 thread3 12105 thread4 2835 thread5 4292 ... I want to plot an histogram in python with : Y : number of threads X : 5 ranges of # of subscribers. [0 to 100], [101 to 1000], [1001 to 5000], [5001 to 10000] and [10001 and more] Is there a way to do it efficiently with any library in python? Currently, I have to preprocess the data this way and then plot the data, but that seems a bit cumbersome. subreddit_subscriber = open("subreddit_subscriber.txt","w"); # 5 counters, one for each bin subreddit_count = dict(); subreddit_count["below_100"] = 0; subreddit_count["below_1000"] = 0; subreddit_count["below_5000"]= 0; subreddit_count["below_10000"] = 0; subreddit_count["more_10000"] = 0; with open(file, "r") as f: for line in f: subreddits = json.loads(line); subscribers = subreddits["subscribers"] #increment the counter according to the number of subscribers if(subscribers &lt;=100): subreddit_count["below_100"] += 1; elif (subscribers &lt;= 1000): subreddit_count["below_1000"] += 1; elif (subscribers &lt;= 5000): subreddit_count["below_5000"] += 1; elif (subscribers &lt;= 10000): subreddit_count["below_10000"] += 1; else: subreddit_count["more_10000"] += 1; for key in subreddit_count.keys(): subreddit_subscriber.write(key + "\t" + str(subreddit_count[key])); subreddit_subscriber.close(); ** First line of the original dataset is this one: ** {"header_img":"...","submit_link_label":"Submit a new post","name":"t5_2qgzg","description":"/r/business brings you the best of your business section. From tips for running a business, to pitfalls to avoid, /r/business teaches you the smart moves and helps you dodge the foolish.\n\n/r/business is not the place for stories about the government's economic policies or corporate corruption. \n#### Rules:\n\n1. **This is not the place to promote your business.** \nAny and every post promoting a business in any capacity will be remov…
answer count: 1
has comment: http://stackoverflow.com/comment/84808909
has comment: http://stackoverflow.com/comment/84810605
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib

http://stackoverflow.com/comment/84865487
has text: Seems like this would make more sense with a factory.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48929299

http://stackoverflow.com/comment/93048405
comment on: http://stackoverflow.com/a/48851244
has text: This answer is correct if you remove the `execute()` call.
score: 0
type: AnswerComment
type: Comment

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

http://stackoverflow.com/comment/84670249
type: QuestionComment
comment on: http://stackoverflow.com/q/48832925
has text: What do you mean? -0.72... is quite different from 0.78...
score: 0
type: Comment

http://stackoverflow.com/comment/84761404
type: QuestionComment
comment on: http://stackoverflow.com/q/48878730
score: 1
has text: What does this have to do with C?
type: Comment

http://stackoverflow.com/a/48928702
score: 2
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48928640
answers question: http://stackoverflow.com/q/48928640
type: Answer
has body: setText() expects a string but you are passing it a tuple, a possible solution is: self.label_2.setText(str(circles.shape))
upvote count: 2
has comment: http://stackoverflow.com/comment/84868547

http://stackoverflow.com/comment/84877311
has text: I see what you mean. However, I want it to print the board after each turn, if I did what you suggested, would it alternate between inputs?
score: 0
comment on: http://stackoverflow.com/a/48935348
type: Comment
type: AnswerComment

spatial
tags question: http://stackoverflow.com/q/48901783
type: Tag
tag name: spatial
tags question: http://stackoverflow.com/q/48897868

http://stackoverflow.com/comment/84910003
comment on: http://stackoverflow.com/a/48951680
has text: Does this guarantee chronological ordering or should a reordering of the index be performed for one to be sure?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48815357
answers question: http://stackoverflow.com/q/48813922
upvote count: 1
type: AcceptedAnswer
has body: (Except for a "AttributeError: '_Screen' object has no attribute 'done'" error when closing the window) Your code works as expected on my system (Apple OS X) without modification. Below is my rework of your code for style and efficiency, see if it works any better for you: from turtle import Turtle, Screen def draw_grid(): for distance in range(0, 500, 100): turtle.goto(0, distance) for _ in range(5): turtle.dot() turtle.fd(100) def get_mouse_click_coor(x, y): if -20 &lt; x &lt; 20 and 20 &lt; y &lt; 380: turtle.penup() if 20 &lt; y &lt; 80: turtle.goto(0, 0) turtle.pendown() turtle.goto(0, 100) elif 120 &lt; y &lt; 180: turtle.goto(0, 100) turtle.pendown() turtle.goto(0, 200) elif 220 &lt; y &lt; 280: turtle.goto(0, 200) turtle.pendown() turtle.goto(0, 300) elif 320 &lt; y &lt; 380: turtle.goto(0, 300) turtle.pendown() turtle.goto(0, 400) screen = Screen() turtle = Turtle() turtle.penup() turtle.speed('fastest') draw_grid() screen.onscreenclick(get_mouse_click_coor) screen.mainloop() You don't need both mainloop() and done() as they are the same thing (aliases.)
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48813922

http://stackoverflow.com/comment/85008711
has text: Thank you for an amazing answer. I was able to get the .cov_params() method, results.t_test and results.wald_test methods all working.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48940720
type: AnswerComment

http://stackoverflow.com/comment/84737715
comment on: http://stackoverflow.com/a/48843835
score: 1
has text: Sure, you would need to shift the origin to some other point, `R = np.sqrt((x-x0)**2+(y-y0)**2)`m where `(x0,y0)` would be the new center point.
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84695677
comment on: http://stackoverflow.com/a/48845736
type: Comment
has text: It shouldn't matter. A request is a request, no matter what browser you're using.
score: 0
type: AnswerComment

http://stackoverflow.com/a/48897285
has comment: http://stackoverflow.com/comment/119844153
type: Answer
has comment: http://stackoverflow.com/comment/84800420
answers question: http://stackoverflow.com/q/48897265
has comment: http://stackoverflow.com/comment/84800999
has comment: http://stackoverflow.com/comment/115990373
accepted answer of: http://stackoverflow.com/q/48897265
has comment: http://stackoverflow.com/comment/84800537
upvote count: 29
has body: Option 1 Use a the series itself to mask the cumulative sum of the negation. Then use value_counts (~s).cumsum()[s].value_counts().max() 3 explanation (~s).cumsum() is a pretty standard way to produce distinct True/False groups 0 1 1 1 2 2 3 2 4 2 5 2 6 3 7 4 dtype: int64 But you can see that the group we care about is represented by the 2s and there are four of them. That's because the group is initiated by the first False (which becomes True with (~s)). Therefore, we mask this cumulative sum with the boolean mask we started with. (~s).cumsum()[s] 1 1 3 2 4 2 5 2 dtype: int64 Now we see the three 2s pop out and we just have to use a method to extract them. I used value_counts and max. Option 2 Use factorize and bincount a = s.values b = pd.factorize((~a).cumsum())[0] np.bincount(b[a]).max() 3 explanation This is a similar explanation as for option 1. The main difference is in how I a found the max. I use pd.factorize to tokenize the values into integers ranging from 0 to the total number of unique values. Given the actual values we had in (~a).cumsum() we didn't strictly need this part. I used it because it's a general purpose tool that could be used on arbitrary group names. After pd.factorize I use those integer values in np.bincount which accumulates the total number of times each integer is used. Then take the maximum. Option 3 As stated in the explanation of option 2, this also works: a = s.values np.bincount((~a).cumsum()[a]).max() 3
has comment: http://stackoverflow.com/comment/84800424
type: AcceptedAnswer
downvote count: 1
score: 28

http://stackoverflow.com/q/48901319
has title: how to print valus using for loop inside HTML table cell?
score: 0
has comment: http://stackoverflow.com/comment/84808105
tagged with: http://stackoverflow.com/tag/html
tagged with: python
type: UnansweredQuestion
has body: My code is : &lt;td&gt; {% for i in value %} &lt;input type='radio' value='{{i}}' name='radiobutt1' /&gt;{{i}} &lt;br&gt;&lt;br&gt; {% endfor %} &lt;/td&gt; The problem is that whatever is inside is printed as such. Hence instead of printing the values it is printing the content inside and as such. Here value has been returned by render_template in app.py file of flask.
has comment: http://stackoverflow.com/comment/84808100
has answer: http://stackoverflow.com/a/48902555
type: Question
answer count: 1
has comment: http://stackoverflow.com/comment/84812023
tagged with: flask

http://stackoverflow.com/comment/84809863
score: 0
has text: @cricket_007 I have tried Brute Force Regex, works well for queries on single line, but if query spans multiple lines (frequent scenario in the code) then its problematic.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48899627

http://stackoverflow.com/a/48858258
accepted answer of: http://stackoverflow.com/q/48858242
answers question: http://stackoverflow.com/q/48858242
has comment: http://stackoverflow.com/comment/84719904
score: 2
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has body: now is a function (technically a class method) so call it like this: print(now().second)
type: Answer

http://stackoverflow.com/comment/84987732
type: Comment
type: QuestionComment
has text: @Uvar I managed to extract the problematic piece of code. I tried putting `[x,y]` but it gave me a "TypeError: list indices must be integers or slices, not tuple". Q is A 2D array with x rows and Y columns, when I want to print the contents of one element it works ok, but when I store something in there, it assigns it to the whole row
score: 0
comment on: http://stackoverflow.com/q/48957439

http://stackoverflow.com/comment/84627480
has text: What is `s` ? I add it to answer.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48811687
type: Comment

http://stackoverflow.com/comment/84811145
type: QuestionComment
comment on: http://stackoverflow.com/q/48902856
score: 0
type: Comment
has text: Well, is `numpy` already satisfied? Also, not clear which Python version's `pip` you are using

http://stackoverflow.com/q/48821969
has title: Force Python in Pycharm, Mac, to use Discrete AMD GPU
has comment: http://stackoverflow.com/comment/84647180
tagged with: gpu
tagged with: python
tagged with: macos
answer count: 0
tagged with: pycharm
downvote count: 0
type: UnansweredQuestion
score: 1
has body: Does anyone know how(e.g. libraries) to force Pycharm(Python) to use a discrete AMD GPU in a mac? I'm using a 2016 Macbook Pro with Radeon 460, and I am in need to prime factorise this number, and I thought using the GPU would be faster: 8347879453436694939854738058201715370889272649572324043195256045640311690537183795264318225428212999500788633703142598940875581237513027689211142340762913 Many thanks!
type: Question
upvote count: 1
favorite count: 0

http://stackoverflow.com/comment/84737619
has text: @brunodesthuilliers this doesn't convert to any Python type except a string though
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48865303

http://stackoverflow.com/comment/84656345
type: AnswerComment
comment on: http://stackoverflow.com/a/48826044
type: Comment
has text: my python shell kept waiting and waiting with http://edition.cnn.com/services/rss/ as input. Won't https://edition.cnn.com/ or http://cnn.com/ work ?
score: 0

http://stackoverflow.com/comment/84837929
type: AnswerComment
type: Comment
has text: Thanks for your response Todor, for this line of code - data-hydro = g_data[0]['data-hydro-click'] , I get following error: can't assign to operator
comment on: http://stackoverflow.com/a/48915424
score: 0

http://stackoverflow.com/a/48810301
has body: You have a column without a name. Either remove it before loading, change the column names and remove it after loading, or use something like (assuming first column is A): df=pd.read_excel('sp500.xlsx', parse_dates=True, index_col=3, usecols='B:G')
type: Answer
score: 3
downvote count: 0
upvote count: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48809990
answers question: http://stackoverflow.com/q/48809990

http://stackoverflow.com/a/48846527
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48846461
has body: If you really want to increment the credits variable within the function, you can use global: credits = 0 def add_credits(x): global credits credits += x add_credits(3) print(credits) # 3 add_credits(4) print(credits) # 7 But using global in this way is not recommended, so I would definitely use Evyatar's solution.

http://stackoverflow.com/q/48846686
tagged with: python
tagged with: regex
has body: I have some numbers within sentences and they look like this s='rare blond Canadian terrier on wheels. Only $8.98. test test. ...0.1/10 very rare' patt='[0-9\.{1}]*/10' re.findall(patt,s) i want to find float/10 ( or sometimes int/10) , but with my pattern i got ['...1/10'] im sure this should be an easy fix, anyone please help?
has comment: http://stackoverflow.com/comment/84697448
type: AnsweredQuestion
has title: regex to find numbers with slash
has answer: http://stackoverflow.com/a/48846710
accepted answer: http://stackoverflow.com/a/48846710
type: Question
score: 0
upvote count: 1
answer count: 1
downvote count: 1
duplicate of: http://stackoverflow.com/q/14550526
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/14550526

http://stackoverflow.com/q/48948014
favorite count: 0
tagged with: curve-fitting
tagged with: python
has comment: http://stackoverflow.com/comment/84903103
has answer: http://stackoverflow.com/a/48954189
accepted answer: http://stackoverflow.com/a/48954189
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
tagged with: spline
has comment: http://stackoverflow.com/comment/84902329
has title: Fitting a closed curve to a set of discrete points and finding it's perimeter
upvote count: 1
has body: I have a set of points pts which form a loop which looks like this: Closed curve The code I used for the same is as follows: pts=np.array( [ [1145,1130], [1099.5,1056.5], [1026,1062], [950.3,1054.3], [909,1130], [940.4,1215.6], [1026,1264], [1111.6,1215.6] ]) pts = np.vstack([pts, pts[0]]) #pts = np.array([...]) # Your points x, y = pts.T i = np.arange(len(pts)) # 5x the original number of points interp_i = np.linspace(0, i.max(), 5 * i.max()) xi = interp1d(i, x, kind='cubic')(interp_i) yi = interp1d(i, y, kind='cubic')(interp_i) fig, ax = plt.subplots() ax.plot(xi, yi) ax.plot(x, y, 'ko') plt.show() I want to know how to find the length of this curve/ the perimeter of this figure. Is there any way to do it?
answer count: 1

http://stackoverflow.com/comment/84873172
comment on: http://stackoverflow.com/a/48929889
type: AnswerComment
has text: Try running with OP's input. You'll see what I mean.
type: Comment
score: 1

http://stackoverflow.com/a/48845042
has comment: http://stackoverflow.com/comment/130075102
has body: The error is quite self-explanatory. The environment variable LD_LIBRARY_PATH must be defined so that the operating system knows the location of the libraries. Use the setenv command to define it properly, as follows: setenv LD_LIBRARY_PATH path/to/libraries It seems that this link can point you to the right path (no pun intended) and that the required location is in the form of matlabroot/bin/glnxa64:matlabroot/sys/os/glnxa64.
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48844547
score: 1
accepted answer of: http://stackoverflow.com/q/48844547
upvote count: 1

http://stackoverflow.com/comment/84852359
type: AnswerComment
type: Comment
has text: @ Anony-Mousse can you suggest an way to produce the desired output so that it clusters accordingly.
score: 1
comment on: http://stackoverflow.com/a/48922229

http://stackoverflow.com/q/48957546
downvote count: 5
has answer: http://stackoverflow.com/a/48957966
has comment: http://stackoverflow.com/comment/84922112
has comment: http://stackoverflow.com/comment/84922088
has comment: http://stackoverflow.com/comment/84922075
type: Question
has body: I need to read a list of colors from txt file. For example color.txt which looks like this: red blue green what I do is: with open('color.txt') as f: line = f.readline().strip() when calling 'line' my result comes as: 'red' 'blue' 'green' However, I need my output without ' ' as: red blue green Is the problem in encoding of my txt file? Or am I doing something wrong? Thanks in advance for help. UPDATE: Since there is no clear understanding on what I do here, please see the full code. The program shall print colorful rectangles in defined number of columns. The amount of rectangles is defined by amount of colors in the file. Each rectangle has color as per line, one by one. import tkinter canvas = tkinter.Canvas() canvas.pack() def stvor(file, width): a = 30 pocetr = 0 z = 0 with open(file, 'r') as f: x = 10 y = 10 for line in f: #line counter pocetr += 1 for b in range(pocetr): #defined how many rectangles shall be drawn z += 1 col = f.readline().strip() #reading color from a file canvas.create_rectangle(x, y, x+a, y+a, fill = col) x = x + a if z == width: #if the width reaches certain level continue in new line y = y + a x = 10 z = 0
has comment: http://stackoverflow.com/comment/84922377
has comment: http://stackoverflow.com/comment/84922191
has title: f.readline() returns text in apostrophes, how to remove it?
upvote count: 2
has answer: http://stackoverflow.com/a/48957603
tagged with: apostrophe
favorite count: 0
possible better answer: http://stackoverflow.com/a/48957603
accepted answer: http://stackoverflow.com/a/48957823
tagged with: python-3.x
answer count: 3
score: -3
tagged with: python
tagged with: readline
has answer: http://stackoverflow.com/a/48957823
has comment: http://stackoverflow.com/comment/84922106
tagged with: text
type: AnsweredQuestion

http://stackoverflow.com/comment/84702695
type: Comment
has text: Do you mean the [Windows-1252](https://en.m.wikipedia.org/wiki/Windows-1252) encoding? If so, use `text=f.read().decode('cp1252')`.
comment on: http://stackoverflow.com/a/48849448
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84787264
score: 0
comment on: http://stackoverflow.com/q/48890866
type: Comment
type: QuestionComment
has text: and what is the problem?

http://stackoverflow.com/a/48855773
has body: The file osd.kv is loaded multiples times, you might have unwanted behaviors (For example, you will have several Screen instances with the same name). You can declare ScreenManagement as a rule in your kv file and not use Builder.load_file method: osd.py: import kivy kivy.require('1.10.0') from kivy.app import App from kivy.clock import Clock from kivy.config import Config from kivy.uix.screenmanager import ScreenManager, Screen import threading Config.set('graphics', 'width', '800') Config.set('graphics', 'height', '480') class PauseScreen(Screen): def on_enter(self): print('enter') Clock.schedule_once(self.switch_back, 5) def switch_back(self, *args): print('back') self.manager.current = "osd_screen" class MainScreen(Screen): def on_enter(self): print('start threading') Clock.schedule_once(self.switch, 5) def switch(self, *args): self.manager.current = "pause" class ScreenManagement(ScreenManager): stop = threading.Event() class OsdApp(App): def on_stop(self): self.root.stop.set() def build(self): return ScreenManagement() if __name__ == '__main__': OsdApp().run() osd.kv: &lt;ScreenManagement&gt;: id: screen_manager MainScreen: id: main_screen name: 'osd_screen' PauseScreen: id: pause_screen name: 'pause' &lt;MainScreen&gt;: BoxLayout: orientation: 'vertical' Label: text_size: self.size text: 'MainScreen' font_size: 50 bold: True halign: 'center' valign: 'top' size_hint: 1, .3 &lt;PauseScreen&gt;: BoxLayout: orientation: 'vertical' Label: text: 'Pause Screen' font_size: 25
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48855187
answers question: http://stackoverflow.com/q/48855187
type: Answer
has comment: http://stackoverflow.com/comment/84725942
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84725215
upvote count: 1

mask
tags question: http://stackoverflow.com/q/48853083
type: Tag
tag name: mask
tags question: http://stackoverflow.com/q/48871383
tags question: http://stackoverflow.com/q/48855930

http://stackoverflow.com/comment/84745669
type: Comment
has text: You can use almost the same syntax as what your answer is suggesting: `s = {1, 2}; s ^= {3}; print(s); s ^= {3}; print(s)`. My original suggestion was more concerning using a dictionary in this use case in general. A Set strikes me as a better container, unless you need to track all three of "seen, but true", "seen, but false", and "unseen", in which case a dictionary *would* make more sense.
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48870623

http://stackoverflow.com/a/48843454
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48841782
score: 0
answers question: http://stackoverflow.com/q/48841782
has body: Thanks all of you I tried everything mentioned at first and finally got a solution I did a crazy thing at first. I wanted to define an empty queryset so for results['posts'] so I did a bad but a working way results['posts']=Post.objects.filter(text_icontains='sth_that_will_never_b_true') and I used Django Merge QuerySets and solved the problem and then later studied genuine way to define empty QuerySet as django.db.models.query.QuerySet.none And gladly final code is count = {} results = {} results['posts']=Post.objects.none() # empty QuerySet queries = querystring.split() for query in queries: results['posts'] = results['posts'] | Post.objects.filter( text__icontains=query) count['posts'] = results['posts'].count() Now everything works as expected.

http://stackoverflow.com/comment/84813507
type: AnswerComment
comment on: http://stackoverflow.com/a/48903480
type: Comment
has text: Yes, for efficiency I suggest merging dataframes before the query.
score: 0

http://stackoverflow.com/q/48891222
has title: Python class return TypeError: 'list' object is not callable
has comment: http://stackoverflow.com/comment/84788617
type: AnsweredQuestion
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/31087111
has comment: http://stackoverflow.com/comment/84833912
accepted answer: http://stackoverflow.com/a/48891858
has body: I have a class: class mountain: def __init__(self,pk_positions,chann_1,chann_2): self.pk_positions = pk_positions self.chann_1 = chann_1 self.chann_2 = chann_2 def chann_1_pk(self): return(list(self.chann_1[i] for i in self.pk_positions)) def chann_2_pk(self): return(list(self.chann_2[i] for i in self.pk_positions)) def vall_positions(self): return(list(int((i+j)/2) for i,j in zip(self.pk_positions[:-1],self.pk_positions[1:]))) def vall_sum(self): return(list(self.chann_1[i]+self.chann_2[i] for i in self.vall_positions())) If I call in the main script: peaks = mountain(pk_positions,chann_1,chann_2) pk1 = peaks.chann_1_pk() # ==&gt; without error pk2 = peaks.vall_positions() # ==&gt; TypeError: 'list' object is not callable pk3 = peaks.vall_sum() # == &gt; TypeError: 'list' object is not callable Why there is no error for pk1 but errors for pk2 and pk, please? I did some stackoverflow searching, but i don't think the problems is the naming of the defs and lists. Thanks.
has comment: http://stackoverflow.com/comment/84787750
tagged with: class
downvote count: 0
answer count: 1
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84791943
has answer: http://stackoverflow.com/a/48891858
tagged with: python

http://stackoverflow.com/a/48946713
has body: The SciPy interpolation routines return a function that you can call to perform an interpolation. For nearest neighbour interpolation on a regular grid, you can use scipy.interpolate.RegularGridInterpolator: import numpy as np from scipy.interpolate import RegularGridInterpolator nearest_function = RegularGridInterpolator( (old_lon, old_lat), old_data, method="nearest", bounds_error=False ) new_data = np.array( [[nearest_function([i, j]) for j in new_lat] for i in new_lon] ).squeeze() That isn't perfect, though, because lon=175 are all fill values. (If I hadn't set bounds_error=False then you'd get an error there.) In that case, you need to ask how you want to wrap around the dateline. A straightforward solution would be to copy the lon=0 line to the end of the array and call it lon=180. Should you want linear or higher order interpolation one day, which I'd recommend if your data are points rather than cells, you can use scipy.interpolate.RectBivariateSpline: import numpy as np from scipy.interpolate import RectBivariateSpline old_step = 10 old_lon = np.arange(-180, 180, old_step) old_lat = np.arange(-90, 90, old_step) old_data = np.random.random((len(old_lon), len(old_lat))) interp_function = RectBivariateSpline(old_lon, old_lat, old_data, kx=1, ky=1) new_lon = np.arange(-180, 180, new_step) new_lat = np.arange(-90, 90, new_step) new_data = interp_function(new_lon, new_lat)
answers question: http://stackoverflow.com/q/48945682
upvote count: 3
has comment: http://stackoverflow.com/comment/84901695
has comment: http://stackoverflow.com/comment/84902370
has comment: http://stackoverflow.com/comment/84902299
downvote count: 0
score: 3
type: Answer

http://stackoverflow.com/a/48807264
upvote count: 2
type: AcceptedAnswer
type: Answer
has body: Option 1 Using a combination of the csv module and the collections.Counter object: import csv from collections import Counter data = [] with open('data.csv') as f: data = [word for row in csv.reader(f) for word in row[1].lower().split()] counts = Counter(data) Option 2 Using pandas. Load in your data as a Series, specifying no header with header=False, and ignoring the first column with usecols=[1] (which ignores the 0th column). import pandas as pd s = pd.read_csv('data.csv', header=None, usecols=[1], squeeze=True) s 0 This dress is great 1 This coat is terrible 2 That dress was ok Name: 1, dtype: object Next, call str.split on space, stack columns, and then call value_counts: s.str.lower().str.split(None, expand=True).stack().value_counts() this 2 dress 2 is 2 coat 1 ok 1 was 1 great 1 terrible 1 that 1 dtype: int64
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48807103
answers question: http://stackoverflow.com/q/48807103

http://stackoverflow.com/comment/84656334
type: Comment
comment on: http://stackoverflow.com/q/48826287
type: QuestionComment
has text: Did you add "django.contrib.messages.context_processors.messages" to your "context_processors" list?
score: 0

http://stackoverflow.com/q/48849610
score: 1
possible better answer: http://stackoverflow.com/a/64965909
has body: I am using a custom register serializer in django-rest-auth to add new fields on registration. I have a country model and a country field in the user model that is an FK to countries. user.models @python_2_unicode_compatible class User(AbstractUser): phone = models.CharField(max_length=15, null=True) verified_phone = models.BooleanField(default=False) country = models.ForeignKey(Country, related_name='country') level = models.ForeignKey(UserLevel, related_name='user_level') user.serializers class UserModelSerializer(HyperlinkedModelSerializer): class Meta: model = User country = serializers.ReadOnlyField(source='country.name') fields = [ 'url', 'id', 'username', 'country', 'email', 'phone', ] read_only_fields = ( 'id', 'password', ) custom register serializer class CustomRegisterSerializer(RegisterSerializer): country = serializers.PrimaryKeyRelatedField(read_only=True) def get_cleaned_data(self): return { 'country': self.validated_data.get('country', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'username': self.validated_data.get('username', ''), } def save(self, request): print(self.get_cleaned_data()) adapter = get_adapter() user = adapter.new_user(request) user.country = self.validated_data.get('country', '') self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.save() return user Sample data that is sent from the client with the country as an object {username: "bernie", email: "bernie@d.com", country: {…}, password1: "password", password2: "password"} but this error keeps coming, Cannot assign "''": "User.country" must be a "Country" instance. when I printed the request on the console this is what I got {'country': '', 'password1': 'password', 'email': 'bernie@d.com', 'username': 'bernie'} which means that somewhere along the line, the country data is lost. I have tried sending only the id, name of the country and nothing works. Wh…
type: Question
accepted answer: http://stackoverflow.com/a/48850060
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/64965909
has answer: http://stackoverflow.com/a/48850060
tagged with: django-rest-framework
favorite count: 0
has title: Cannot assign "''": "User.country" must be a "Country" instance
tagged with: django
tagged with: python
type: AnsweredQuestion
downvote count: 0

wav
tags question: http://stackoverflow.com/q/48937077
tag name: wav
tags question: http://stackoverflow.com/q/48923943
type: Tag
tags question: http://stackoverflow.com/q/48863141

http://stackoverflow.com/q/48836567
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48836783
type: Question
tagged with: numpy
has title: pandas compare multiple column values from different frames of different lengths
accepted answer: http://stackoverflow.com/a/48836783
has comment: http://stackoverflow.com/comment/84678297
possible better answer: http://stackoverflow.com/a/48836768
tagged with: dataframe
has body: I have a data frame with GPS coordinates and I'm trying to make an offline reverse geocode city lookup service. I'm essentially trying to resolve the city name from a pair of GPS coordinates. I cannot use 3rd party services. My data frame looks like this: data = [ ["LATITUDE","LONGITUDE"], [41.9021454,-87.624176], [38.8898163,-76.9598312], [39.304615,-76.6136703], [38.9550285,-76.7441483], [41.8815498,-87.6620789], [33.9141922,-84.3123169] ] df = pd.DataFrame(data[1:],columns=data[0]) LATITUDE LONGITUDE 41.9021454 -87.624176 38.8898163 -76.9598312 39.304615 -76.6136703 38.9550285 -76.7441483 41.8815498 -87.6620789 33.9141922 -84.3123169 I made a city lookup data frame city_data = [ ['CITY',"LAT","LON"], ['PHOENIX',33.0,-112.0], ['ATLANTA',33.0,-84.0], ['MIAMI',25.0,-80.0], ['WASHINGTON_DC',39.0,-77.0], ['CHICAGO',41.0,-87.0], ] df_geo = pd.DataFrame(city_data[1:],columns=city_data[0]) CITY LAT LON 0 PHOENIX 33.0 -112.0 1 ATLANTA 33.0 -84.0 2 MIAMI 25.0 -80.0 3 WASHINGTON_DC 39.0 -77.0 4 CHICAGO 41.0 -87.0 I want to compare the lat and lon of both data frames to see if the values are ~roughly +/- 1 within each other and if so make a new column with the city name like this: LATITUDE LONGITUDE CITY 41.9021454 -87.624176 CHICAGO 38.8898163 -76.9598312 WASHINGTON_DC 39.304615 -76.6136703 WASHINGTON_DC 38.9550285 -76.7441483 WASHINGTON_DC 41.8815498 -87.6620789 CHICAGO 33.9141922 -84.3123169 ATLANTA The data frames are of different lengths. The city lookup might be 10 rows but the data might be thousands. I'm pretty sure the comparison can be done in one line with np.where or df.isin but I don't know how to say it. I have this but I'm stuck df['city'] = np.where(abs(df['LATITUDE'] - df_geo.loc[df["LAT"]]) &lt;= 1 and abs(df['LONGITUDE'] - df_geo.loc[df["LON"]]) &lt;= 1, df_geo['CITY'], 'TBD') df['city'] = np.where(df['LATITUDE'].round(0) in df_geo['LAT'] and df['LONGITUDE'] in df_geo['LON'] , df_geo['CITY'], 'TBD')
has answer: http://stackoverflow.com/a/48836768
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84678218
has comment: http://stackoverflow.com/comment/84678051
has comment: http://stackoverflow.com/comment/84678081

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

http://stackoverflow.com/q/48877925
favorite count: 0
has title: PIL shows black image when attempting to view image
tagged with: python
has comment: http://stackoverflow.com/comment/84780030
answer count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/84779256
downvote count: 1
type: Question
tagged with: opencv
tagged with: python-imaging-library
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/84765759
has comment: http://stackoverflow.com/comment/84766176
linked to: http://stackoverflow.com/q/12438813
tagged with: image-processing
score: 0
has body: The current goal of what I am writing is to download an image from S3, open it using Pillow, and show the image. I am able to download the image fine; it can be viewed properly from my photos. However, when I try to use the image with PIL, all of the pixel values are black. It does however, retain the shape of the image, which leads me to know that the image is at least being read. the code is shown below: s3.Bucket(bucket).download_file(key, key) # downloaded perfectly fine img = Image.open(key) img.show() # shows all black with the Images's dimensions I know I can read from bytes, but that will give me a 1d array of all the bytes instead of the dimensions needed for an image.
has comment: http://stackoverflow.com/comment/84764998

http://stackoverflow.com/a/65161693
score: 1
has comment: http://stackoverflow.com/comment/117061371
downvote count: 0
has body: I won't be certain about this but it might be that your code is trying to change your cursor. At the very end of the main loop, put the following code. pygame.mouse.set_system_cursor(pygame.SYSTEM_CURSOR_ARROW) Might be completely wrong though.
answers question: http://stackoverflow.com/q/48847871
type: Answer
upvote count: 1

http://stackoverflow.com/q/48949726
type: Question
linked to: http://stackoverflow.com/q/4779963
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84912022
has title: Build an Android App to communicate with python Tornado Server
favorite count: 0
tagged with: rest
tagged with: android
has comment: http://stackoverflow.com/comment/84930372
has answer: http://stackoverflow.com/a/48949951
has comment: http://stackoverflow.com/comment/84930683
type: UnansweredQuestion
tagged with: python
tagged with: http
downvote count: 0
has body: I've seen very little information online for creating a web server with Tornado to handle GET/POST requests from an android phone. I'm relatively new to both Android and web server dev but I have some experience with Tornado so I thought I would use that, although there seems to be a huge lack of tutorials for using these two technologies. import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") def main(): return tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": app = main() app.listen(8888) tornado.ioloop.IOLoop.current().start() I'm using the HttpURLConnection class to create a connection with the web server, which has worked with a tutorial I used, but I'm now trying to connect my android app to my Tornado web server on my computer to simply get "Hello world" from the server when I click a button on my android app. Instead of providing the tutorial's http.php/get URL (which is tested and works), I want to try to use my computer's IP to connect with my server, so I replaced the URL with http://x.x.x.x:8888/, my IPv4 address, but that doesn't work. GetBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View V) { new MakeNetworkCall().execute("http://androidpala.com/" + "tutorial/http.php?get=1", "Get"); } }); I can provide more of my android code if necessary. Thanks for the help, I can't figure this out at all.
score: 1
has comment: http://stackoverflow.com/comment/84912396
tagged with: tornado

http://stackoverflow.com/q/48951629
accepted answer: http://stackoverflow.com/a/48951713
linked to: http://stackoverflow.com/q/36901
has answer: http://stackoverflow.com/a/48952112
has answer: http://stackoverflow.com/a/48951776
tagged with: python
has comment: http://stackoverflow.com/comment/84910221
score: 2
type: AnsweredQuestion
has body: When a function I'm calling has a lot of parameters, and there's one I'd like to include conditionally, do I have to have two separate calls to the function, or is there someway to pass nothing (almost like None) so that I'm not passing in any argument for a particular parameter? For example, I want to pass an argument for the parameter sixth sometimes, but other times I want to not pass anything for that parameter. This code works, but it feels like I'm duplicating more than I should have to. The function I'm calling is in a third-party library, so I can't change how it handles the received arguments. If I pass in None for sixth, the function raises an exception. I need to either pass my 'IMPORTANT_VALUE' or not pass in anything. What I'm doing currently: def do_a_thing(stuff, special=False): if special: response = some.library.func( first=os.environ['first'], second=stuff['second'], third=stuff['third'] fourth='Some Value', fifth=False, sixth='IMPORTANT_VALUE', seventh='example', eighth=True ) else: response = some.library.func( first=os.environ['first'], second=stuff['second'], third=stuff['third'] fourth='Some Value', fifth=False, seventh='example', eighth=True ) return response What I'd like to do: def do_a_thing(stuff, special=False): special_value = 'IMPORTANT_VALUE' if special else EMPTY_VALUE response = some.library.func( first=os.environ['first'], second=stuff['second'], third=stuff['third'] fourth='Some Value', fifth=False, sixth=special_value, seventh='example', eighth=True ) return response
has title: Pass empty argument to Python function?
type: Question
has comment: http://stackoverflow.com/comment/84917218
downvote count: 0
has answer: http://stackoverflow.com/a/48951713
answer count: 3
has comment: http://stackoverflow.com/comment/84910036
favorite count: 0
possible better answer: http://stackoverflow.com/a/48952112
upvote count: 2

http://stackoverflow.com/a/48918501
has body: Your count data is in a dictionary of {letter:count} pairs. You can use the dictionary to calculate the total count like this: total_count = sum(counts.values()) Then don't calculate the percentage till you are iterating over the counts... for letter, count in counts.items(): print(f'{letter} - {count} - {100*count/total}') #Python v3.6+ #print('{} - {} - {}'.format(letter, count, 100*count/total) #Python version &lt;3.6+ Or if you want to put it all in a list so you can sort it: data = [] for letter, count in counts.items(): data.append((letter,count,100*count/total) Using operator.itemgetter for the sort key function can help code readability. import operator letter = operator.itemgetter(0) count = operator.itemgetter(1) frequency = operator.itemgetter(2) data.sort(key=letter) data.sort(key=count) data.sort(key=frequency)
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
answers question: http://stackoverflow.com/q/48918175
accepted answer of: http://stackoverflow.com/q/48918175
upvote count: 1

http://stackoverflow.com/q/48935441
has comment: http://stackoverflow.com/comment/84877656
tagged with: python
type: AnsweredQuestion
tagged with: linked-list
tagged with: pycharm
score: 0
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48935557
tagged with: data-structures
has title: AttributeError: 'NoneType' object has no attribute 'next_node'
answer count: 1
has comment: http://stackoverflow.com/comment/84877519
accepted answer: http://stackoverflow.com/a/48935557
favorite count: 0
has comment: http://stackoverflow.com/comment/84877579
has body: I've been doing some training in data structures and i'm implementing linked list. here's the code: def insertEnd(self, data): if self.head is None: self.insertStart(data) return new_node = Node(data) self.counter += 1 actual_node = self.head while actual_node is not None: actual_node = actual_node.next_node actual_node.next_node = new_node after i try to insert the second node i get this error. i dont know what's the problem

http://stackoverflow.com/comment/84945975
type: Comment
type: QuestionComment
has text: please provide a sample data.
comment on: http://stackoverflow.com/q/48939152
score: 1

http://stackoverflow.com/comment/84724504
comment on: http://stackoverflow.com/q/48860505
type: Comment
type: QuestionComment
has text: I just went through that and I don't think it helps.I used sendall() too but had the same result
score: 0

http://stackoverflow.com/comment/84800725
score: 0
type: AnswerComment
type: Comment
has text: @SamCraig, you're right. I'll edit this answer after he clarifies those 2 points. If my answer matches yours after the edit, I'll delete mine.
comment on: http://stackoverflow.com/a/48897556

http://stackoverflow.com/comment/84907781
score: 0
has text: Stick with GDAL or convert to a lower bits-per-sample (up to 16) format, I'd say.
comment on: http://stackoverflow.com/q/48944819
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84912510
type: AnswerComment
comment on: http://stackoverflow.com/a/48949752
type: Comment
has text: You don't need to add `threading` and `socket` to your requirements, as these are included with python's standard library.
score: 1

python-3.x
tags question: http://stackoverflow.com/q/48938316
tags question: http://stackoverflow.com/q/48827501
tags question: http://stackoverflow.com/q/48815924
tags question: http://stackoverflow.com/q/48848888
tags question: http://stackoverflow.com/q/48852699
tags question: http://stackoverflow.com/q/48957986
tags question: http://stackoverflow.com/q/48924352
tags question: http://stackoverflow.com/q/48880009
tags question: http://stackoverflow.com/q/48844923
tags question: http://stackoverflow.com/q/48817972
tags question: http://stackoverflow.com/q/48889154
tags question: http://stackoverflow.com/q/48832832
tags question: http://stackoverflow.com/q/48883998
tags question: http://stackoverflow.com/q/48847450
tags question: http://stackoverflow.com/q/48901682
tags question: http://stackoverflow.com/q/48930927
tags question: http://stackoverflow.com/q/48904268
tags question: http://stackoverflow.com/q/48804769
tags question: http://stackoverflow.com/q/48868845
tags question: http://stackoverflow.com/q/48824056
tags question: http://stackoverflow.com/q/48906173
tags question: http://stackoverflow.com/q/48903689
tags question: http://stackoverflow.com/q/48936865
tags question: http://stackoverflow.com/q/48901950
tags question: http://stackoverflow.com/q/48878287
tags question: http://stackoverflow.com/q/48953848
tags question: http://stackoverflow.com/q/48947290
tags question: http://stackoverflow.com/q/48926844
tags question: http://stackoverflow.com/q/48814917
tags question: http://stackoverflow.com/q/48877559
tags question: http://stackoverflow.com/q/48868313
tags question: http://stackoverflow.com/q/48862429
tags question: http://stackoverflow.com/q/48817141
tags question: http://stackoverflow.com/q/48842212
tags question: http://stackoverflow.com/q/48892148
tags question: http://stackoverflow.com/q/48832024
tags question: http://stackoverflow.com/q/48819547
tags question: http://stackoverflow.com/q/48951960
tags question: http://stackoverflow.com/q/48834392
tags question: http://stackoverflow.com/q/48878440
tags question: http://stackoverflow.com/q/48938632
tags question: http://stackoverflow.com/q/48815210
tags question: http://stackoverflow.com/q/48936196
tags question: http://stackoverflow.com/q/48871537
tags question: http://stackoverflow.com/q/48886648
tags question: http://stackoverflow.com/q/48959921
tags question: http://stackoverflow.com/q/48811568
tags question: http://stackoverflow.com/q/48912467
tags question: http://stackoverflow.com/q/48932983
tags question: http://stackoverflow.com/q/48957994
tags question: http://stackoverflow.com/q/48910537
tags question: http://stackoverflow.com/q/48931049
tags question: http://stackoverflow.com/q/48953689
tags question: http://stackoverflow.com/q/48883829
tags question: http://stackoverflow.com/q/48875854
tags question: http://stackoverflow.com/q/48951973
tags question: http://stackoverflow.com/q/48907305
tags question: http://stackoverflow.com/q/48951711
tags question: http://stackoverflow.com/q/48898729
tags question: http://stackoverflow.com/q/48812506
tags question: http://stackoverflow.com/q/48834300
tags question: http://stackoverflow.com/q/48883283
tags question: http://stackoverflow.com/q/48858357
tags question: http://stackoverflow.com/q/48819139
tags question: http://stackoverflow.com/q/48855506
tags question: http://stackoverflow.com/q/48858495
tags question: http://stackoverflow.com/q/48948219
tags question: http://stackoverflow.com/q/48868807
tags question: http://stackoverflow.com/q/48888862
tags question: http://stackoverflow.com/q/48891184
tags question: http://stackoverflow.com/q/48878687
tags question: http://stackoverflow.com/q/48897760
tags question: http://stackoverflow.com/q/48818277
tags question: http://stackoverflow.com/q/48843380
tags question: http://stackoverflow.com/q/48929403
tags question: http://stackoverflow.com/q/48831050
tags question: http://stackoverflow.com/q/48912441
tags question: http://stackoverflow.com/q/48867941
tags question: http://stackoverflow.com/q/48872134
tags question: http://stackoverflow.com/q/48931681

http://stackoverflow.com/q/48851473
has answer: http://stackoverflow.com/a/48851901
tagged with: pywin32
tagged with: python
type: AnsweredQuestion
score: 2
has title: Python win32serviceutil QueryServiceStatus: What does the return value mean?
upvote count: 2
tagged with: winapi
has answer: http://stackoverflow.com/a/48851931
type: Question
accepted answer: http://stackoverflow.com/a/48851901
possible better answer: http://stackoverflow.com/a/48851931
answer count: 2
downvote count: 0
has body: I am learning to use pywin32, and am trying to use the win32serviceutil modules on 64bit Python 3.6.4 The following code: import win32serviceutil as service serviceStatus = service.QueryServiceStatus("WinDefend") print(serviceStatus) Returns the following tuple: (16, 4, 197, 0, 0, 0, 0) I am utterly new to the windows api and pywin32, what does these 6 values mean? Any documentation on pywin32 and win32 isn't revealing anything. Edit - I'm running Windows 10
favorite count: 0

http://stackoverflow.com/comment/84835325
has text: @Personman or one person about a week if you want Javascript :)
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48914411

http://stackoverflow.com/q/48960941
type: UnansweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/49038855
has title: sklearn2pmml save machine learning model error
upvote count: 1
answer count: 1
has body: I was recently looking for a solution to transfer machine learning model across platforms between python and java. In other words, firstly train machine learning model with python, then carry out prediction on line with java. Fortunately, I found out sklearn2pmml. however, I hit the java error when trying to use the basic usage examples，the error resulted in the saved empty file. code as follows: from sklearn_pandas import DataFrameMapper import pandas as pd import numpy as np from sklearn2pmml import sklearn2pmml,PMMLPipeline from sklearn.linear_model import LinearRegression from sklearn.preprocessing import MinMaxScaler,LabelBinarizer,FunctionTransformer heart_data = pd.read_csv("heart.csv") # 用Mapper定义特征工程 mapper = DataFrameMapper([ (['sbp'], MinMaxScaler()), (['tobacco'], MinMaxScaler()), ('ldl', None), ('adiposity', None), (['famhist'], LabelBinarizer()), ('typea', None), ('obesity', None), ('alcohol', None), (['age'], FunctionTransformer(np.log)), ]) #用pipeline定义使用的模型，特征工程等 pipeline = PMMLPipeline([ ('mapper', mapper), ("classifier", LinearRegression()) ]) pipeline.fit(heart_data[heart_data.columns.difference(["chd"])], heart_data["chd"]) # 排除某些列，使用df.columns.difference(['列名']) #导出模型文件 sklearn2pmml(pipeline, "lrHeart.xml", with_repr = True) error as follows: Standard output is empty Standard error: 2月 24, 2018 3:55:48 下午 org.jpmml.sklearn.Main run 信息: Parsing PKL.. 2月 24, 2018 3:55:48 下午 org.jpmml.sklearn.Main run 信息: Parsed PKL in 42 ms. 2月 24, 2018 3:55:48 下午 org.jpmml.sklearn.Main run 信息: Converting.. 2月 24, 2018 3:55:48 下午 org.jpmml.sklearn.Main run 信息: Converted in 119 ms. 2月 24, 2018 3:55:48 下午 org.jpmml.sklearn.Main run 信息: Marshalling PMML.. Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBContext at org.jpmml.model.JAXBUtil.getContext(JAXBUtil.java:126) at org.jpmml.model.MetroJAXBUtil.marshalPMML(MetroJAXBUtil.java:25) at org.jpmml.sklearn.Main.run(Main.java:159) at org.jpmml.sklearn.Main.main(Main.java:94) Caused by: jav…

http://stackoverflow.com/q/48893893
has answer: http://stackoverflow.com/a/48895530
has answer: http://stackoverflow.com/a/48894374
has title: Find max value for each year in 3D array NetCDF file (way to use Pandas or xarray?)
has answer: http://stackoverflow.com/a/48901698
tagged with: python
has comment: http://stackoverflow.com/comment/84825924
has comment: http://stackoverflow.com/comment/84852273
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84830076
possible better answer: http://stackoverflow.com/a/48901698
tagged with: netcdf
accepted answer: http://stackoverflow.com/a/48895530
type: Question
has comment: http://stackoverflow.com/comment/84794159
has comment: http://stackoverflow.com/comment/84793558
has body: I am trying to makes some maps and such of data from several NetCDF files. Each one contains data for 5 years worth of data. The data is in a 3D array of shape (14608, 145, 192) (time, lat, lon). I would like the maximum value for each year at each coordinate, so basically when it's all said and done I'll have an output array with shape (5,145,192) (one value per each lat. and lon. value). It has been suggested I try using pandas, specifically DataFrame and DatetimeIndex, but I couldn't find a way to use it for more anything greater than a 2D array. Xarray was also suggested, but I haven't used xarray before and wouldn't know where to start. Edit 1: Sample Data Here is a simplified version of what I've been trying to do with pandas and then I realized DataFrame doesn't work for a 3D array. import numpy as np import pandas as pd fake = np.random.randint(2, 30, size = (14608,145,192)) index = pd.date_range(start = '1985-1-1 01:30:00', end = '1989-12-31 22:30:00' , freq='3H') df = pd.DataFrame(data = fake, index = index) Edit 2: Fixed Listed Array Shape To clarify, I actually want an array with shape (5, 145, 192) as the output. I wrote it wrong because originally I was splitting the 3D array into 5 separate arrays, finding the max, and then stacking them again into one array witch ended with a shape of (5, 145, 192). I want to be able to skip the tedious breaking apart the array by hand, so to speak, that I was doing before and simplify the code.
has comment: http://stackoverflow.com/comment/84808517
score: 0
answer count: 3
tagged with: pandas
tagged with: max
tagged with: arrays
has comment: http://stackoverflow.com/comment/84794599

http://stackoverflow.com/a/48939516
upvote count: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/84895849
answers question: http://stackoverflow.com/q/48937645
score: 1
has body: I think your paths must be export PATH=$HOME/python3p5/bin:$PATH export PYTHONPATH=$HOME/python3p5/lib Please check these directories exist.

http://stackoverflow.com/q/48856896
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48857023
type: AnsweredQuestion
downvote count: 0
score: 1
has body: I am using requests to get some data from a server, which is done in a while loop. However, every now and then, one of two errors occur. The first is that the status_code of the return from the request is not equal to 200, and this prints out an error message. The second is that a ConnectionError exception is raised. If I receive either error, I want to keep attempting to get the data. However, I'm not sure how to do this for both types of error. I know how to handle the ConnectionError exception, for example: def get_data(self, path): # Keep trying until the connection attempt is successful while True: # Attempt a request try: request_return = requests.get(path, timeout=30) break # Handle a connection error except ConnectionError as e: pass # Return the data return request_return.json() But how can I also handle the status_code in a similar manner? Is it something to do with the raise_for_status() method?
tagged with: python-requests
has title: Handling both a ConnectionError and a status code error
type: Question
accepted answer: http://stackoverflow.com/a/48857020
possible better answer: http://stackoverflow.com/a/48857023
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48857020

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

http://stackoverflow.com/q/48885400
tagged with: pyqt
answer count: 1
has answer: http://stackoverflow.com/a/48887005
accepted answer: http://stackoverflow.com/a/48887005
tagged with: python-3.x
tagged with: python
tagged with: qtableview
type: AnsweredQuestion
has title: How to show all rows containing a specific name on QTableView from an sqlite database
tagged with: pyqt5
type: Question
score: 0
has body: Am designing a program with Pyqt to be used to store data to an sqlite database and retrieve it using a QTableView. Apparently, i would like to retrieve a specific column like "name" and show all rows that have the name "Anderson". The following code is failing because it misses alot. database = QtSql.QSqlDatabase().addDatabase('QSQLITE') database.setDatabaseName('database.db') database.open() model = QtSql.QSqlTableModel() #model.setQuery("SELECT Name, Sale, Date FROM Individuals") model.setEditStrategy(QtSql.QSqlTableModel.OnManualSubmit) model.select() self.tableView.setModel(model) self.tableView.setShowGrid(False) model.setHeaderData(0, QtCore.Qt.Horizontal, "Name") model.setHeaderData(1, QtCore.Qt.Horizontal, "Amount") model.setHeaderData(2, QtCore.Qt.Horizontal, "Date") self.tableView.horizontalHeader().setVisible(True) print(model.setFilter("SELECT Name = 'Anderson' FROM Individuals"))

http://stackoverflow.com/q/48862653
has title: How to retrieve data from HTML canvas using python?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48944291
has comment: http://stackoverflow.com/comment/84728701
score: 1
type: Question
tagged with: html5-canvas
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48944291
has body: I am new of web scraping and for one of the project I am working on, I need to retrieve data of bitcoin transactions over time from an interactive chart (https://bitinfocharts.com/comparison/bitcoin-transactions.html) using Python 2.7. I found that all the data I want is hidden in the 855x455 canvas instead of directly in the html file. However, I could find those data in Page source in the form of [new Date("2018/02/18"),159333]]. Why is that? And how can I scrape those data? Appreciate for the help!
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84728586
upvote count: 1
tagged with: web-scraping

http://stackoverflow.com/comment/84755282
score: 1
comment on: http://stackoverflow.com/q/48875609
type: Comment
type: QuestionComment
has text: `sum=df.sum(0)`, `min= df.min()`, `max= df.max()` - you just destroyed three useful built-in functions.

http://stackoverflow.com/comment/84891980
type: Comment
comment on: http://stackoverflow.com/q/48942649
type: QuestionComment
score: 0
has text: go into browser developer tools and see in html how `{{ form.new_password2 }}` is rendered. If you can post the html of this input filed. it would be great

http://stackoverflow.com/comment/84794257
comment on: http://stackoverflow.com/q/48878497
type: Comment
type: QuestionComment
has text: No it is not intentional ... It is also not necessary to use os.path
score: 0

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

http://stackoverflow.com/q/48856477
has comment: http://stackoverflow.com/comment/84716750
tagged with: slice
tagged with: int
has comment: http://stackoverflow.com/comment/84716560
has comment: http://stackoverflow.com/comment/84716468
favorite count: 0
possible better answer: http://stackoverflow.com/a/48856684
has answer: http://stackoverflow.com/a/48856684
tagged with: reverse
has answer: http://stackoverflow.com/a/48856680
has body: I am trying to create a program to reverse only the integers in a given list, ignoring floats and strings. In addition, It cannot use any built in functions to do so (reverse() and [::-1]). So far, I have def intvert(lst): finallst = [] for i in range(len(lst)-1,-1,-1): if i == type(int): finallst.append(i) elif i != type(int): continue return finallst However, this only produces [] as the output example: (1,g,2.6,2,3,4,h,dfgs,dsgfgdsg,5) becomes (5,4,3,2,1)
tagged with: python
has comment: http://stackoverflow.com/comment/84716459
has answer: http://stackoverflow.com/a/48895707
answer count: 4
score: 2
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84716545
accepted answer: http://stackoverflow.com/a/48856680
upvote count: 3
has comment: http://stackoverflow.com/comment/84716460
has title: Reversing ONLY integers in list without slice or reverse()
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48856763

http://stackoverflow.com/q/48876511
tagged with: python-requests
has answer: http://stackoverflow.com/a/48877544
type: Question
has body: I'm trying to test a connection to one of my Django views using Python's requests library. When I try to make a POST request on it I receive info when viewing request.text telling me the CSRF verification failed, and that I need a CSRF token when submitting forms. I've done some more research here and tried my best with this This is my code right now: post_request = requests.session() post_request.get('http://127.0.0.1:8000/message/') csrftoken = post_request.cookies['csrftoken'] headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36'} final_request = post_request.post('http://127.0.0.1:8000/message/', headers=dict(Referer=post_request)) This is my view: def add_message(request): form = InputInfoForm(request.POST) if request.method == 'POST': return HttpResponse('hey') return HttpResponse('test') So how do I verify the CSRF token in the view using requests?
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48877544
tagged with: python
favorite count: 0
score: 2
has title: Getting a 403 error involving CSRF when trying to connect to localhost (python requests)
type: AnsweredQuestion
upvote count: 2
possible better answer: http://stackoverflow.com/a/48876624
tagged with: django
has answer: http://stackoverflow.com/a/48876624

cisco
type: Tag
tag name: cisco
tags question: http://stackoverflow.com/q/48868464
tags question: http://stackoverflow.com/q/48915073
tags question: http://stackoverflow.com/q/48930324

windows
tags question: http://stackoverflow.com/q/48868524
tags question: http://stackoverflow.com/q/48944037
tags question: http://stackoverflow.com/q/48916243
tags question: http://stackoverflow.com/q/48859672
tags question: http://stackoverflow.com/q/48951166
tags question: http://stackoverflow.com/q/48862654
tags question: http://stackoverflow.com/q/48919738
tags question: http://stackoverflow.com/q/48959521
tags question: http://stackoverflow.com/q/48951759
tags question: http://stackoverflow.com/q/48910093
tags question: http://stackoverflow.com/q/48891406
tags question: http://stackoverflow.com/q/48870758
tags question: http://stackoverflow.com/q/48867728
tags question: http://stackoverflow.com/q/48867221
tags question: http://stackoverflow.com/q/48887676
tags question: http://stackoverflow.com/q/48934895
type: Tag
tags question: http://stackoverflow.com/q/48812195
tags question: http://stackoverflow.com/q/48924787
tags question: http://stackoverflow.com/q/48942155
tags question: http://stackoverflow.com/q/48878287
tag name: windows
tags question: http://stackoverflow.com/q/48877266
tags question: http://stackoverflow.com/q/48855506
tags question: http://stackoverflow.com/q/48911582

http://stackoverflow.com/a/49921321
has body: import calendar print ("Welcome to my leap year program") print ("You may type any year and I will tell you if it is a leap year") count = 0 for i in range(5): count = count + i t1= int(input()) if calendar.isleap(t1): # returns true if t1 is leap year else returns false print (t1, "is a leap year.") # if test condition is true else: print (t1, "is not a leap year.") # if test condition is false
answers question: http://stackoverflow.com/q/48837553
type: Answer
accepted answer of: http://stackoverflow.com/q/48837553
score: 0
type: AcceptedAnswer

http://stackoverflow.com/comment/84750323
type: Comment
comment on: http://stackoverflow.com/q/48872596
type: QuestionComment
has text: A clear example and explanation: http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#building-a-relationship
score: 1

http://stackoverflow.com/q/48826785
linked to: http://stackoverflow.com/q/43999710
type: Question
accepted answer: http://stackoverflow.com/a/48828610
tagged with: matplotlib
tagged with: dataframe
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84660831
has body: I have dataframe: temp_old temp_new Year 2013 2014 2015 2016 2017 2018 2013 2014 2015 2016 2017 2018 Date 2013-01-01 23:00:00 21.587569 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2013-01-02 00:00:00 21.585347 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 2013-01-02 01:00:00 21.583472 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN ... ... ... ... ... ... ... ... ... ... ... ... ... 2018-02-05 00:00:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 22.882083 2018-02-05 01:00:00 NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN 22.878472 When I plot this df thats my result. My goal is show it but without separate by years. So I want to have 5 curves in range January: December on one chart. update:(code to plot) df_sep_by_year.plot(figsize=(15,8))
has comment: http://stackoverflow.com/comment/84658573
favorite count: 0
has comment: http://stackoverflow.com/comment/84658272
has answer: http://stackoverflow.com/a/48828610
tagged with: python
type: AnsweredQuestion
score: 3
has title: Plot DataFrame in 1 year period
upvote count: 3

http://stackoverflow.com/comment/84681050
score: 1
type: Comment
has text: Possible duplicate of [Python Function to test ping](https://stackoverflow.com/questions/26468640/python-function-to-test-ping)
type: QuestionComment
comment on: http://stackoverflow.com/q/48838266

http://stackoverflow.com/comment/84637568
type: Comment
type: QuestionComment
has text: The border size differ from picture to picture so I can not enter a certain value for cropping. Maybe I am thinking too complicated though
comment on: http://stackoverflow.com/q/48816703
score: 0

http://stackoverflow.com/a/48932604
score: 63
has body: Django 2.x is not supported using Python 2.x. From the Django download page: We recommend using the latest version of Python 3. The last version to support Python 2.7 is Django 1.11 LTS. You should use Python 3.x with Pip3: pip3 install Django
answers question: http://stackoverflow.com/q/48932445
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48932445
type: Answer
upvote count: 63

http://stackoverflow.com/q/48857218
has title: Django - how to delete model item from list
type: Question
has body: I'm currently building an app with Django for the purpose of creating user-story cards (a bit like a Trello board). On one page I have my cards displayed as a list: The code for the list is: ScrumBuddy Board {% for card in cards.all %} {{ card.title }} {% endfor %} And the view def for the board is: def board(request): cards = Card.objects context = {'cards': cards} return render(request, 'scrumbuddy/board.html', context) I'd like to add a delete link to each card that removes it from this list, preferable with a confirmation dialogue box. Any suggestions on how to do that would be fantastic. Many thanks.
answer count: 1
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/48857458
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/a/48900153
has body: I changed your data to a list of dict: data = [ { 'Total_Amount' : '150.00', 'LinkAPI' : [{"ConfidenceScore":4},{"ConfidenceScore":9}], 'RecordID' : 5687, 'ClientId' : 45, 'Customer_Number' : ["HDMO70232"], 'RowNumber' : 0, 'Invoice_Number' : '', 'Customer_Name' : 'HD MOTORCYCLES SIS/SVC' }, { 'Total_Amount' : '1500.00', 'LinkAPI' : [{"ConfidenceScore":8},{"ConfidenceScore":10}, {"ConfidenceScore":20}, {"test":2}], 'RecordID' : 56287, 'ClientId' : 415, 'Customer_Number' : ["HDMO70232"], 'RowNumber' : 1, 'Invoice_Number' : '', 'Customer_Name' : 'HD MOTORCYCLES SIS/SVC' }, ] df = pd.DataFrame(data) df2 = pd.DataFrame(np.concatenate(df.LinkAPI).tolist(), index=np.repeat(df.index, df.LinkAPI.str.len().astype(int))) df.drop("LinkAPI", axis=1).join(df2) the output: ClientId Customer_Name Customer_Number Invoice_Number RecordID RowNumber Total_Amount ConfidenceScore test 0 45 HD MOTORCYCLES SIS/SVC [HDMO70232] 5687 0 150.00 4.0 NaN 0 45 HD MOTORCYCLES SIS/SVC [HDMO70232] 5687 0 150.00 9.0 NaN 1 415 HD MOTORCYCLES SIS/SVC [HDMO70232] 56287 1 1500.00 8.0 NaN 1 415 HD MOTORCYCLES SIS/SVC [HDMO70232] 56287 1 1500.00 10.0 NaN 1 415 HD MOTORCYCLES SIS/SVC [HDMO70232] 56287 1 1500.00 20.0 NaN 1 415 HD MOTORCYCLES SIS/SVC [HDMO70232] 56287 1 1500.00 NaN 2.0
downvote count: 0
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48899573

http://stackoverflow.com/q/48889473
has comment: http://stackoverflow.com/comment/84880002
tagged with: sqlalchemy
has title: SQLAlchemy alias a joined table in a many-to-many relation
has comment: http://stackoverflow.com/comment/84795919
downvote count: 0
favorite count: 0
has body: In a legacy database we have, there is a pretty special datastructure where we have two many-to-many relations joining the same two tables companies to paymentschedules. There is a many-to-many relation using an association table called companies_paymentschedules, and a second many-to-many relation using an association table called companies_comp_paymentschedules. Both relations serve different purposes. companies_paymentschedules stores paymentschedules for which the company has a discount, companies_comp_paymentschedules stores paymentschedules that are linked to the company. (I know that this could be simplified by replacing these tables with a single lookup table, but that is not an option in this legacy database.) The problem is that I need to join both types of companies (discounted and linked) in the same query. SQLAlchemy joins both tables without problems, but it also joins the companies table, and calls them both "companies", which leads to a SQL syntax error (using MSSQL BTW). This is the query: q = Paymentschedules.query # join companies if a company is specified if company is not None: q = q.join(Paymentschedules.companies) q = q.join(Paymentschedules.companies_with_reduction) The many-to-many relations are both defined in our companies model, and look like this: paymentschedules_with_reduction = relationship("Paymentschedules", secondary=companies_paymentschedules, backref="companies_with_reduction") paymentschedules = relationship("Paymentschedules", secondary=companies_comp_paymentschedules, backref="companies") The problem is that the JOINS trigger SQLAlchemy to create a SQL statement that looks like this: FROM paymentschedules JOIN companies_comp_paymentschedules AS companies_comp_paymentschedules_1 ON paymentschedules.pmsd_id = companies_comp_paymentschedules_1.pmsd_id JOIN companies ON companies.comp_id = companies_comp_paymentschedules_1.comp_id JOIN companies_paymentschedules AS companies_paymentschedules_1 ON paymentschedules.pmsd_id = compani…
type: UnansweredQuestion
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/84804090
upvote count: 1
type: Question
score: 1
linked to: http://stackoverflow.com/q/35327701

beautifulsoup
tags question: http://stackoverflow.com/q/48902469
tags question: http://stackoverflow.com/q/48919871
tags question: http://stackoverflow.com/q/48844421
tags question: http://stackoverflow.com/q/48926576
tags question: http://stackoverflow.com/q/48935660
tags question: http://stackoverflow.com/q/48943528
tags question: http://stackoverflow.com/q/48834073
tags question: http://stackoverflow.com/q/48898704
tags question: http://stackoverflow.com/q/48958711
tags question: http://stackoverflow.com/q/48865341
tags question: http://stackoverflow.com/q/48916514
tags question: http://stackoverflow.com/q/48877343
tags question: http://stackoverflow.com/q/48832200
tags question: http://stackoverflow.com/q/48885995
tags question: http://stackoverflow.com/q/48892305
tags question: http://stackoverflow.com/q/48817659
tags question: http://stackoverflow.com/q/48931459
tags question: http://stackoverflow.com/q/48928968
tags question: http://stackoverflow.com/q/48951527
tags question: http://stackoverflow.com/q/48921315
tag name: beautifulsoup
tags question: http://stackoverflow.com/q/48825587
tags question: http://stackoverflow.com/q/48845652
tags question: http://stackoverflow.com/q/48932103
tags question: http://stackoverflow.com/q/48820947
tags question: http://stackoverflow.com/q/48884889
tags question: http://stackoverflow.com/q/48854663
tags question: http://stackoverflow.com/q/48958725
tags question: http://stackoverflow.com/q/48944802
tags question: http://stackoverflow.com/q/48918438
tags question: http://stackoverflow.com/q/48918137
tags question: http://stackoverflow.com/q/48933579
tags question: http://stackoverflow.com/q/48959744
tags question: http://stackoverflow.com/q/48856118
tags question: http://stackoverflow.com/q/48818431
tags question: http://stackoverflow.com/q/48820655
tags question: http://stackoverflow.com/q/48875305
tags question: http://stackoverflow.com/q/48898460
tags question: http://stackoverflow.com/q/48929730
tags question: http://stackoverflow.com/q/48836215
tags question: http://stackoverflow.com/q/48962221
tags question: http://stackoverflow.com/q/48934646
tags question: http://stackoverflow.com/q/48821832
tags question: http://stackoverflow.com/q/48888168
tags question: http://stackoverflow.com/q/48902955
tags question: http://stackoverflow.com/q/48856479
tags question: http://stackoverflow.com/q/48958184
tags question: http://stackoverflow.com/q/48928355
tags question: http://stackoverflow.com/q/48874874
tags question: http://stackoverflow.com/q/48953042
tags question: http://stackoverflow.com/q/48959291
tags question: http://stackoverflow.com/q/48884184
type: Tag
tags question: http://stackoverflow.com/q/48859561
tags question: http://stackoverflow.com/q/48852522
tags question: http://stackoverflow.com/q/48915708
tags question: http://stackoverflow.com/q/48942121
tags question: http://stackoverflow.com/q/48895642
tags question: http://stackoverflow.com/q/48935514
tags question: http://stackoverflow.com/q/48913101
tags question: http://stackoverflow.com/q/48826450
tags question: http://stackoverflow.com/q/48870908
tags question: http://stackoverflow.com/q/48950800
tags question: http://stackoverflow.com/q/48892445
tags question: http://stackoverflow.com/q/48847927
tags question: http://stackoverflow.com/q/48874148
tags question: http://stackoverflow.com/q/48897760
tags question: http://stackoverflow.com/q/48867072
tags question: http://stackoverflow.com/q/48874002
tags question: http://stackoverflow.com/q/48835298
tags question: http://stackoverflow.com/q/48829055
tags question: http://stackoverflow.com/q/48916043
tags question: http://stackoverflow.com/q/48948520
tags question: http://stackoverflow.com/q/48897586
tags question: http://stackoverflow.com/q/48923951
tags question: http://stackoverflow.com/q/48948495
tags question: http://stackoverflow.com/q/48938552
tags question: http://stackoverflow.com/q/48918284
tags question: http://stackoverflow.com/q/48831440
tags question: http://stackoverflow.com/q/48856837

ttk
tags question: http://stackoverflow.com/q/48922679
tags question: http://stackoverflow.com/q/48930355
type: Tag
tags question: http://stackoverflow.com/q/48816552
tags question: http://stackoverflow.com/q/48910513
tag name: ttk
tags question: http://stackoverflow.com/q/48873051
tags question: http://stackoverflow.com/q/48933964
tags question: http://stackoverflow.com/q/48867800

pandas
tags question: http://stackoverflow.com/q/48949193
tags question: http://stackoverflow.com/q/48928882
tags question: http://stackoverflow.com/q/48858906
tags question: http://stackoverflow.com/q/48959301
tags question: http://stackoverflow.com/q/48943425
tags question: http://stackoverflow.com/q/48840042
tags question: http://stackoverflow.com/q/48927671
tags question: http://stackoverflow.com/q/48873890
tags question: http://stackoverflow.com/q/48815110
tags question: http://stackoverflow.com/q/48890385
tags question: http://stackoverflow.com/q/48926828
tags question: http://stackoverflow.com/q/48842293
tags question: http://stackoverflow.com/q/48909110
tags question: http://stackoverflow.com/q/48939650
tags question: http://stackoverflow.com/q/48867092
tags question: http://stackoverflow.com/q/48888614
tags question: http://stackoverflow.com/q/48942801
tags question: http://stackoverflow.com/q/48869471
tags question: http://stackoverflow.com/q/48860428
tags question: http://stackoverflow.com/q/48911638
tags question: http://stackoverflow.com/q/48877457
tags question: http://stackoverflow.com/q/48849930
tags question: http://stackoverflow.com/q/48841370
tags question: http://stackoverflow.com/q/48873893
tags question: http://stackoverflow.com/q/48957986
tags question: http://stackoverflow.com/q/48950791
tags question: http://stackoverflow.com/q/48904194
tags question: http://stackoverflow.com/q/48958282
tags question: http://stackoverflow.com/q/48846530
tags question: http://stackoverflow.com/q/48955833
tags question: http://stackoverflow.com/q/48852824
tags question: http://stackoverflow.com/q/48955262
tags question: http://stackoverflow.com/q/48815162
tags question: http://stackoverflow.com/q/48845867
tags question: http://stackoverflow.com/q/48808472
tags question: http://stackoverflow.com/q/48896723
tags question: http://stackoverflow.com/q/48941807
tags question: http://stackoverflow.com/q/48935971
tags question: http://stackoverflow.com/q/48811978
tags question: http://stackoverflow.com/q/48874483
tags question: http://stackoverflow.com/q/48935342
tags question: http://stackoverflow.com/q/48835553
tags question: http://stackoverflow.com/q/48932345
tags question: http://stackoverflow.com/q/48807456
tags question: http://stackoverflow.com/q/48814786
tags question: http://stackoverflow.com/q/48864668
tags question: http://stackoverflow.com/q/48935958
tags question: http://stackoverflow.com/q/48868880
tags question: http://stackoverflow.com/q/48873035
tags question: http://stackoverflow.com/q/48951166
tags question: http://stackoverflow.com/q/48917141
tags question: http://stackoverflow.com/q/48876238
tags question: http://stackoverflow.com/q/48853989
tags question: http://stackoverflow.com/q/48841838
tags question: http://stackoverflow.com/q/48862429
tags question: http://stackoverflow.com/q/48914328
tags question: http://stackoverflow.com/q/48956597
tags question: http://stackoverflow.com/q/48839381
tags question: http://stackoverflow.com/q/48903434
tags question: http://stackoverflow.com/q/48950473
tags question: http://stackoverflow.com/q/48869196
tags question: http://stackoverflow.com/q/48895811
tags question: http://stackoverflow.com/q/48843357
tags question: http://stackoverflow.com/q/48897200
tags question: http://stackoverflow.com/q/48870463
tags question: http://stackoverflow.com/q/48843887
tags question: http://stackoverflow.com/q/48953032
tags question: http://stackoverflow.com/q/48847934
tags question: http://stackoverflow.com/q/48828173
tags question: http://stackoverflow.com/q/48823152
tags question: http://stackoverflow.com/q/48928026
tags question: http://stackoverflow.com/q/48854269
tags question: http://stackoverflow.com/q/48930068
tags question: http://stackoverflow.com/q/48809240
tags question: http://stackoverflow.com/q/48936132
tags question: http://stackoverflow.com/q/48827285
tags question: http://stackoverflow.com/q/48895370
tags question: http://stackoverflow.com/q/48916089
tags question: http://stackoverflow.com/q/48897215
tags question: http://stackoverflow.com/q/48812580

http://stackoverflow.com/a/48896943
has body: # Dummy DataFrame df = pd.DataFrame({'col1': [1,2,3], 'col2': [4,5,6]}) # Extract second row (index: 1) df.iloc[1].values
answers question: http://stackoverflow.com/q/48896900
downvote count: 0
has comment: http://stackoverflow.com/comment/121151178
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/84783347
score: 0
type: QuestionComment
type: Comment
has text: Can you add an example of the `POST` data?
comment on: http://stackoverflow.com/q/48887001

http://stackoverflow.com/comment/84801408
type: AnswerComment
has text: @AndrewK, whatever you insert into a tree automatically makes it a child of the tree. [this](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/ttk-Treeview.html) may help for better understanding.
comment on: http://stackoverflow.com/a/48897772
type: Comment
score: 1

http://stackoverflow.com/q/48962343
has title: Python if attribute is not found statement
score: 0
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48962372
has comment: http://stackoverflow.com/comment/84932014
has comment: http://stackoverflow.com/comment/84930706
tagged with: python
accepted answer: http://stackoverflow.com/a/48962372
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84930742
type: Question
has body: For now my script won't run because some of the items in my list does not contain the attribute img. for container in containers: brand = container.div.div.a.img["title"] How can I write an if-statement in which my script will return a default value if the attribute img does not exist and keep running the script for the items that have the attribute img.
has comment: http://stackoverflow.com/comment/84930878

http://stackoverflow.com/q/48913910
possible better answer: http://stackoverflow.com/a/48915050
has body: How can I update data_template automatically using data from result? My idea is to map fields like this: map_fields = { "item_name": "itemName", "background_image": "backgroundImage", "back_item": "backItem" } but I'm not sure how to iterate over dict in this case to get excepted result result = { "id": 10, "item_name": "name", "background_image": "" "back_item": "test", } data_template = { "itemName": "", "backgroundImage": "", "backItem": "" } My try: for i in result.items(): for field in map_fields.items(): if i[0] == field[0]: data_template[field[1]] = i[1] print data_template
accepted answer: http://stackoverflow.com/a/48914286
has answer: http://stackoverflow.com/a/48915050
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84834480
type: AnsweredQuestion
has title: Update dict/json using date from other dict/json
score: 1
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48914286
favorite count: 0
has comment: http://stackoverflow.com/comment/84834081
tagged with: python

http://stackoverflow.com/comment/84908429
has text: @SreeramTP If the delimiter repeats then that is a requirement the OP should mention in the question.
score: 3
comment on: http://stackoverflow.com/a/48950866
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48901925
has title: Returning Number of affected rows from SQL Server with SQLAlchemy
has body: I use sqlalchemy to make changes to a table in SQL Server database, and would like to get back number of affected rows. I know there is .rowcount attribute to ResultProxy, but as, for example, this answer is demonstrating .rowcount is not necessarily the same as number of affected rows. SQL Server uses @@ROWCOUNT to access number of affected rows from the previous statement execution. Is there a way to modify an sqlalchemy expression that uses insert / update statement to end with SELECT @@ROWCOUNT? For example, given: from sqlalchemy import Table, Column, Integer, String, MetaData, create_engine url = 'mssql+pyodbc://dsn' engine = create_engine(url) metadata = MetaData() users = Table('users', metadata, Column('id', Integer, primary_key=True), Column('name', String), Column('fullname', String), ) ins = users.insert().values(name='jack', fullname='Jack Jones') upd1 = users.update().values(fullname='Jack Doe').where(users.c.name == 'jack') upd2 = users.update().values(fullname='Jack Doe').where(users.c.name == 'jack') I could prepend SELECT @@ROWCOUNT to an update statement: sel = select([text('@@ROWCOUNT')]) sql1 = sel.suffix_with(upd2) print(sql1.compile(engine, compile_kwargs={"literal_binds": True})) Yielding "wrong" query: SELECT @@ROWCOUNT UPDATE users SET fullname='Jack Doe' WHERE users.name = 'jack' Trying to do the "right" thing: sql2 = upd2.suffix_with(sel) Raises AttributeError since 'Update' object has no attribute 'suffix_with'. So is there a way to get desired sql query: UPDATE users SET fullname='Jack Doe' WHERE users.name = 'jack'; SELECT @@ROWCOUNT Using sql expression language without fully textual constructs.
tagged with: sqlalchemy
type: Question
score: 5
downvote count: 0
favorite count: 0
tagged with: sql-server
upvote count: 5
linked to: http://stackoverflow.com/q/702342
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84676093
comment on: http://stackoverflow.com/q/48835595
score: 1
has text: This is a warning, not an error, you can just ignore it.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48887232
upvote count: 2
has comment: http://stackoverflow.com/comment/84779269
tagged with: python-requests
type: Question
tagged with: timeout
has answer: http://stackoverflow.com/a/48915320
answer count: 1
downvote count: 0
has title: How to wait less for connection timeout in Python3 requests?
favorite count: 0
tagged with: exception
tagged with: python
has body: I have something like this for requests error exception: try: r = requests.get(url, stream=True) r.raise_for_status() except requests.exceptions.HTTPError as err: print("HTTP exception error: {}".format(err)) return except requests.exceptions.RequestException as e: print("Exception error {}".format(e)) return To get an error like this I have to wait more than 2 minutes: Exception error HTTPConnectionPool(host='192.168.137.67', port=8000): Max retries exceeded with url: /python-3.4.3.msi (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 110] Connection timed out',)) Is it possible to faster get timeout error? Try one or two times and then continue if something is wrong?
accepted answer: http://stackoverflow.com/a/48915320
score: 2
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/8464391

http://stackoverflow.com/q/48832200
has body: Wrote code to scrape a website which lists daycares. Code able to get the relevant information one first of 100+ pages. No clue how to accommodate code to scrape the site past page 1. Each page lists only 25 daycares and there are 150+ pages to scrape. I read something about looking for Post or Get methods that are referenced when clicking on page numbers, but wasn't able to fix my code using that information (believe it was a user named "manhattan" who shared a solution.) Here's a copy of the current code. Appreciate some help: import requests, bs4, re cc=requests.get('https://data.nj.gov/childcare_results?center=&amp;phone=&amp;capacity_low=&amp;capacity_high=&amp;county=&amp;city=&amp;addr1=&amp;zip=') cc1=bs4.BeautifulSoup(cc.text,"html.parser") #Trying to get all instances of &lt;a href ="[website for inspection report for each daycare]&gt; &lt;a&gt;, but line below returns many more instances of href. Will have to fix that. #Code below does that for the first page in the above website, but no idea how to make it do the same for the remaining 150+ pages of listings cc2 = cc1.select('div a') print(len(cc2)) print (cc2)
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48835883
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84669003
type: Question
accepted answer: http://stackoverflow.com/a/48835883
answer count: 2
possible better answer: http://stackoverflow.com/a/48833802
has comment: http://stackoverflow.com/comment/84669144
has answer: http://stackoverflow.com/a/48833802
has title: Webscraping script in Python3.4/BeatuifulSoup
tagged with: beautifulsoup
score: 0

http://stackoverflow.com/a/48874966
upvote count: 2
answers question: http://stackoverflow.com/q/48874769
downvote count: 0
type: Answer
has body: You could do assertEqual([sum, dif], [expected_sum, expected_dif]) According to the Python documentation, this will actually run assertListEqual because two lists are being passed in. https://docs.python.org/3/library/unittest.html#unittest.TestCase.assertListEqual
score: 2

http://stackoverflow.com/a/48913938
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/48913801
has comment: http://stackoverflow.com/comment/84834538
has comment: http://stackoverflow.com/comment/84834372
answers question: http://stackoverflow.com/q/48913801
has body: A slightly modified df for this example. Added the 10 in Area to fill in the gap: Area Classification Samples 88 500m-1bi 34 94 500m-1bi 112 09 500m-1bi 912 10 &gt;1bi 31 81 &lt;1m 6574 87 100-500m 12 You need to set the index then unstack: df.set_index(['Area', 'Classification']).unstack() Output: Samples Classification 100-500m 500m-1bi &lt;1m &gt;1bi Area 9 NaN 912.0 NaN NaN 10 NaN NaN NaN 31.0 81 NaN NaN 6574.0 NaN 87 12.0 NaN NaN NaN 88 NaN 34.0 NaN NaN 94 NaN 112.0 NaN NaN
upvote count: 2
type: AcceptedAnswer
downvote count: 1
has comment: http://stackoverflow.com/comment/84834229

http://stackoverflow.com/q/48870590
answer count: 1
score: 0
accepted answer: http://stackoverflow.com/a/48870961
tagged with: apache-spark
has title: Could not convert string to float on NaiveBayes Spark example
tagged with: python
has comment: http://stackoverflow.com/comment/84744983
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48870961
tagged with: pyspark
has body: I'm following this tutorial on Spark 1.6. I've copy the same code as follow: from pyspark.mllib.classification import NaiveBayes, NaiveBayesModel from pyspark.mllib.linalg import Vectors from pyspark.mllib.regression import LabeledPoint from pyspark import SparkContext, SparkConf def parseLine(line): parts = line.split(',') label = float(parts[0]) features = Vectors.dense([float(x) for x in parts[1].split(' ')]) return LabeledPoint(label, features) conf= SparkConf() conf.setAppName("NaiveBaye") conf.set('spark.driver.memory','6g') conf.set('spark.executor.memory','6g') conf.set('spark.cores.max',156) sc = SparkContext(conf= conf) data = sc.textFile('sample_naive_bayes_data.txt').map(parseLine) # Split data aproximately into training (60%) and test (40%) training, test = data.randomSplit([0.6, 0.4], seed=0) # Train a naive Bayes model. model = NaiveBayes.train(training, 1.0) # Make prediction and test accuracy. predictionAndLabel = test.map(lambda p: (model.predict(p.features), p.label)) accuracy = 1.0 * predictionAndLabel.filter(lambda (x, v): x == v).count() / test.count() # Save and load model model.save(sc, "model") sameModel = NaiveBayesModel.load(sc, "model") sample_naive_bayes_data.txt contain this: 0, 1.0 0.0 0.0 0, 2.0 0.0 0.0 1, 0.0 1.0 0.0 1, 0.0 2.0 0.0 2, 0.0 0.0 1.0 2, 0.0 0.0 2.0 This is a very basic tutorial but still not working. It give me this error: could not convert string to float on this line: features = Vectors.dense([float(x) for x in parts[1].split(' ')]) Can anyone explain me why and how fix it? Edit 1 I'm trying some changes to work with string values: label = str(parts[0]) features = Vectors.dense([str(x) for x in parts[1].split('')]) and with this dataset: positive, happy food food positive, dog food food negative, food happy food negative, food dog food neutral, food food happy neutral, food food dog There are the same values but with string instead of float values. In the previous example accuracy was: 1.0. Now if I try to run this cod…

http://stackoverflow.com/q/48957309
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python
upvote count: 0
has comment: http://stackoverflow.com/comment/84989851
has comment: http://stackoverflow.com/comment/84922374
type: Question
has answer: http://stackoverflow.com/a/48957392
has body: So I am trying to make a script to tell you how long you have been alive. It al went good but I can’t find out how to subtract a birthday from the current date as shown in the total variable. import time ## dd/mm/yyyy format times=(time.strftime("%d/%m/%Y")) day=(time.strftime("%d")) month=(time.strftime("%m")) year=(time.strftime("%Y")) ##questions born_y=input('what year were you born') born_m=input('what month') born_d=input('what day') ##convert to decimal current_time=int(year+'.'+month+'.'+day) current_age=int(born_y+'.'+born_m+'.'+born_d) ##find age total=current_time-current_age print(total)
downvote count: 3
has comment: http://stackoverflow.com/comment/84921723
answer count: 1
has title: I need To find how to subtract the current date by another date

http://stackoverflow.com/a/48896620
has body: &gt;&gt;&gt; L = ['a', 'b', 'c', 'd', 'e'] &gt;&gt;&gt; [[L[i-j] for i in range(len(L))] for j in range(len(L), 0, -1)] [['a', 'b', 'c', 'd', 'e'], ['b', 'c', 'd', 'e', 'a'], ['c', 'd', 'e', 'a', 'b'], ['d', 'e', 'a', 'b', 'c'], ['e', 'a', 'b', 'c', 'd']]
has comment: http://stackoverflow.com/comment/84809657
score: 0
has comment: http://stackoverflow.com/comment/84836754
type: Answer
answers question: http://stackoverflow.com/q/48876888

dataframe
tags question: http://stackoverflow.com/q/48906828
tags question: http://stackoverflow.com/q/48958996
tags question: http://stackoverflow.com/q/48907175
tags question: http://stackoverflow.com/q/48874897
tags question: http://stackoverflow.com/q/48806059
tags question: http://stackoverflow.com/q/48810342
tags question: http://stackoverflow.com/q/48816594
tags question: http://stackoverflow.com/q/48852855
tags question: http://stackoverflow.com/q/48813586
tags question: http://stackoverflow.com/q/48866730
tags question: http://stackoverflow.com/q/48951492
tags question: http://stackoverflow.com/q/48956286
tags question: http://stackoverflow.com/q/48807197
tags question: http://stackoverflow.com/q/48823955
tags question: http://stackoverflow.com/q/48816457
tags question: http://stackoverflow.com/q/48947557
tags question: http://stackoverflow.com/q/48915816
tags question: http://stackoverflow.com/q/48811096
tags question: http://stackoverflow.com/q/48847799
tags question: http://stackoverflow.com/q/48928947
tags question: http://stackoverflow.com/q/48899051
tags question: http://stackoverflow.com/q/48816717
tags question: http://stackoverflow.com/q/48873887
tags question: http://stackoverflow.com/q/48814051
tags question: http://stackoverflow.com/q/48832687
tags question: http://stackoverflow.com/q/48934313
tags question: http://stackoverflow.com/q/48858952
tags question: http://stackoverflow.com/q/48869257
tags question: http://stackoverflow.com/q/48888272
tags question: http://stackoverflow.com/q/48907532
tags question: http://stackoverflow.com/q/48867941
tags question: http://stackoverflow.com/q/48947194
tags question: http://stackoverflow.com/q/48825644
tags question: http://stackoverflow.com/q/48813906
tags question: http://stackoverflow.com/q/48911531
tags question: http://stackoverflow.com/q/48929349
tags question: http://stackoverflow.com/q/48897535
tags question: http://stackoverflow.com/q/48838354
tags question: http://stackoverflow.com/q/48904448
tags question: http://stackoverflow.com/q/48951380
tags question: http://stackoverflow.com/q/48842639
tags question: http://stackoverflow.com/q/48891436
tags question: http://stackoverflow.com/q/48856584
tags question: http://stackoverflow.com/q/48832364
tags question: http://stackoverflow.com/q/48862979
tags question: http://stackoverflow.com/q/48864923
tags question: http://stackoverflow.com/q/48883401
tags question: http://stackoverflow.com/q/48849539
tags question: http://stackoverflow.com/q/48822897
tags question: http://stackoverflow.com/q/48818340
tags question: http://stackoverflow.com/q/48873499
tags question: http://stackoverflow.com/q/48879813
tags question: http://stackoverflow.com/q/48920638
tags question: http://stackoverflow.com/q/48811596
tags question: http://stackoverflow.com/q/48917052
tags question: http://stackoverflow.com/q/48876289
tags question: http://stackoverflow.com/q/48809166
tags question: http://stackoverflow.com/q/48849497
tags question: http://stackoverflow.com/q/48896522
tags question: http://stackoverflow.com/q/48943297
tags question: http://stackoverflow.com/q/48948534
tags question: http://stackoverflow.com/q/48841842
tags question: http://stackoverflow.com/q/48855400
tags question: http://stackoverflow.com/q/48899550
tags question: http://stackoverflow.com/q/48830324
tags question: http://stackoverflow.com/q/48941345
tags question: http://stackoverflow.com/q/48955521
tags question: http://stackoverflow.com/q/48871043
tags question: http://stackoverflow.com/q/48867518
tags question: http://stackoverflow.com/q/48869922
tags question: http://stackoverflow.com/q/48869904
tags question: http://stackoverflow.com/q/48956392
tags question: http://stackoverflow.com/q/48918847
tags question: http://stackoverflow.com/q/48877958
tags question: http://stackoverflow.com/q/48872516
tags question: http://stackoverflow.com/q/48823024
tags question: http://stackoverflow.com/q/48853355
tags question: http://stackoverflow.com/q/48919005
tags question: http://stackoverflow.com/q/48947248
tags question: http://stackoverflow.com/q/48895335

http://stackoverflow.com/comment/84955036
has text: Is this an answer or a comment? Please be more descriptive.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48975070

http://stackoverflow.com/q/48885955
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48962826
has title: How to get adwords conversions along with gclids via python adwords API?
has body: am wondering which of the reports from https://developers.google.com/adwords/api/docs/appendix/reports/ I should query to get conversion_name, count, value and gclid? Doubleclick search has https://developers.google.com/doubleclick-search/v2/reference/conversion/get , cannot find something similar for Adwords API. Thanks a lot in advance!
downvote count: 0
answer count: 1
tagged with: google-ads-api
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48962826

http://stackoverflow.com/q/48880646
has answer: http://stackoverflow.com/a/63158088
has comment: http://stackoverflow.com/comment/84781999
downvote count: 0
has comment: http://stackoverflow.com/comment/84765468
favorite count: 0
accepted answer: http://stackoverflow.com/a/48886496
answer count: 5
has comment: http://stackoverflow.com/comment/84767156
linked to: http://stackoverflow.com/q/45417335
possible better answer: http://stackoverflow.com/a/48882214
has answer: http://stackoverflow.com/a/48882214
tagged with: python
linked to: http://stackoverflow.com/q/47393292
tagged with: selenium-webdriver
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84790003
has answer: http://stackoverflow.com/a/64681325
tagged with: selenium
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/47861813
score: 26
has answer: http://stackoverflow.com/a/48886496
has answer: http://stackoverflow.com/a/69395617
has title: How to use browser that is already open and logged in with login credentials
upvote count: 26
has body: Is there a way that for different runs of a python program that uses selenium I keep the browser that I have opened and logged in with my credentials, open and use in later runs? I am debugging a code. On the browser each time I need to log in using my credentials. Currently, everytime I stop the code, the web-browser gets closed. Is there a way to keep a copy of browser that I have already open and logged in open and use it for my later debug so every time I don't need to enter my login credentials again? My code that opens the browser looks like this: driver = webdriver.Chrome(executable_path="/the_path/chromedriver", chrome_options=chrome_options) driver.get(url) EDIT: Actually, the way this website asks for authentication is as follows: First, it asks for the username, then I need to press the continue button, then it asks for the password, after entering the password, it sends an SMS to my phone, I need to enter it before it goes to the intended page.
type: Question

http://stackoverflow.com/a/48947063
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48946651
downvote count: 0
has body: In python dicts accept immutable types as keys, so use tuple instead of list. EDIT Example: In [1]: d = {(1, 2,): 'a', (1, 1): 'b', (2, 1): 'c', (2, 2): 'd'} In [2]: d[(1, 1)] Out[2]: 'b'

http://stackoverflow.com/comment/109912727
type: AnswerComment
has text: On PowerShell, add `conda activate $env:CONDA_ENV` to your `profile.ps1` to activate the conda environment
type: Comment
comment on: http://stackoverflow.com/a/55658404
score: 0

http://stackoverflow.com/q/48926881
has comment: http://stackoverflow.com/comment/84861195
has comment: http://stackoverflow.com/comment/84861303
downvote count: 1
type: Question
upvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48928024
score: -1
has body: I created pickle file using version pandas 0.22.2 py 3.6 but when im trying to use in pandas 0.18.1 version ca't able to load follwing error , mportError: No module named 'pandas.core.indexes' even i tried using pd.read_pickle please help on this issue
tagged with: pandas
has comment: http://stackoverflow.com/comment/84861069
has title: Issue reading pickle file created from higher version but need to use in lower version
favorite count: 0
has comment: http://stackoverflow.com/comment/84860546
has comment: http://stackoverflow.com/comment/84860007
type: UnansweredQuestion
tagged with: pickle
tagged with: python

http://stackoverflow.com/comment/84776393
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48885706
has text: no first way is not in my code.I will debug using the way you mentioned
type: Comment

http://stackoverflow.com/comment/84626984
type: QuestionComment
has text: @exsnake: beware! `/usr/bin/python` is Python 2 on macOS.
score: 0
comment on: http://stackoverflow.com/q/48811568
type: Comment

http://stackoverflow.com/q/48928293
tagged with: python
has comment: http://stackoverflow.com/comment/84863212
downvote count: 3
has title: Instantiate class based on ini config in python
type: Question
has comment: http://stackoverflow.com/comment/84863045
has comment: http://stackoverflow.com/comment/85136511
upvote count: 0
has comment: http://stackoverflow.com/comment/84863368
answer count: 1
has comment: http://stackoverflow.com/comment/84864088
has answer: http://stackoverflow.com/a/48928583
has body: I have a situation in python, I need to Load a module and Instantiate a class based on value provided in INI config. [providers] provider=bsnl ; provider may be bsnl/airtel/vodafone/etc.. In my class I am reading this value and in a class method I have to load bsnl_provider.py and has to instantiate BSNLClass. If provider changes to airtel then I have to load airtel_provider.py and has to instantiate AIRTElClass. How can I load relevant module and instantiate relevant class?
tagged with: python-2.7
linked to: http://stackoverflow.com/q/301134
linked to: http://stackoverflow.com/q/3862310
has comment: http://stackoverflow.com/comment/84863923
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84863085
has comment: http://stackoverflow.com/comment/84863309
has comment: http://stackoverflow.com/comment/84863282
has comment: http://stackoverflow.com/comment/84862929
type: UnansweredQuestion
score: -3

http://stackoverflow.com/q/48848815
has comment: http://stackoverflow.com/comment/84701390
has answer: http://stackoverflow.com/a/48848930
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84701441
score: -2
has comment: http://stackoverflow.com/comment/84701348
has title: python version 3: how to ask user to add item to dictionary and print a message that updates with their input?
downvote count: 2
tagged with: for-loop
answer count: 1
has comment: http://stackoverflow.com/comment/84701541
favorite count: 0
tagged with: python-3.x
has body: I'm a beginner learning Python and I'm stuck on this problem: Ask the user to add one topping to the pizza. Modify the dictionary to have that item. Print out every topping the pizza contains, such as: This pizza contains Topping 1,Topping 2... and include the topping that the user added. Given example of dictionary: toppings = {‘pepperoni’:True,’olives':False,'pineapple':True, ‘sausage’:False,’jalapenos’:False} This is what I have so far for the solution: toppings= {'pepperoni':True, 'olives':False,'pineapple':True, 'sausage':False, 'jalapenos': False} while True: pizza = input("Add one topping to the pizza:" ) toppings[pizza] = input break print ("You ordered a pizza with the following toppings: " + [toppings]) for toppings in pizza ['toppings']: print("\t" + topping)
tagged with: while-loop
tagged with: python
accepted answer: http://stackoverflow.com/a/48848930
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84701502
upvote count: 0
has comment: http://stackoverflow.com/comment/84701455

http://stackoverflow.com/comment/84921607
type: Comment
has text: @davinellulinvega can't agree more! your solution is much clean and short!
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48957163

http://stackoverflow.com/comment/84721188
type: QuestionComment
comment on: http://stackoverflow.com/q/48858878
has text: So `/tmp/vmuser_yafetikvhw/decisionTreeAccuracyQuiz.py` does not have the word “float” on line 34? Or are you editing some other file and submitting it to something that rewrites your code? =/
score: 0
type: Comment

http://stackoverflow.com/q/48951639
has comment: http://stackoverflow.com/comment/84911153
score: 0
has comment: http://stackoverflow.com/comment/84910070
answer count: 1
linked to: http://stackoverflow.com/q/2891790
type: UnansweredQuestion
tagged with: python
tagged with: formatting
has title: How to format a list of multiple dimensional arrays?
type: Question
has comment: http://stackoverflow.com/comment/84910300
has body: I have a list, cntrs, which are co-ordinates for the number of centres in a cluster. Basically, the first element is an array of 2 co-ordinates, followed by an array with 3 co-ordinates and so forth. Its contents with print cntrs is: [array([[ 1.95149888, 1.95403504], [ 6.98414983, 6.9892335 ]]), array([[ 0.98186521, 0.97763684], [ 7.01523632, 7.01965819], [ 3.02779515, 3.04964209]]), array([[ 0.97749825, 0.97886934], [ 7.01564811, 7.01963124], [ 2.90672846, 2.86009831], [ 3.16718753, 3.27143671]]), array([[ 3.16520274, 3.27132643], [ 6.72910999, 6.94502491], [ 0.97715149, 0.97907607], [ 2.90738599, 2.85892006], [ 7.29924758, 7.11088622]]), array([[ 7.29993897, 7.11152081], [ 3.16770976, 3.27348032], [ 6.72987889, 6.94502259], [ 1.32396815, 0.92670203], [ 0.74383915, 0.99317788], [ 2.90918296, 2.86325108]]), array([[ 3.04767311, 2.74427507], [ 0.74433306, 0.99277782], [ 2.75432472, 3.02288522], [ 1.32445471, 0.92522911], [ 7.30035779, 7.11196209], [ 6.73027771, 6.94494962], [ 3.19404203, 3.2858904 ]]), array([[ 3.16693842, 3.27337917], [ 0.71526946, 0.97641053], [ 1.19666632, 1.15407263], [ 1.41534598, 0.70413407], [ 7.3898936 , 7.23016845], [ 6.62321659, 6.95167364], [ 7.06769041, 6.94257899], [ 2.90896473, 2.8637164 ]]), array([[ 7.30000058, 7.111688 ], [ 2.93568071, 2.76502603], [ 1.19635564, 1.15350525], [ 3.17086746, 3.28597849], [ 2.73214961, 3.05243834], [ 1.41510711, 0.70335533], [ 3.28473941, 2.82685228], [ 6.72963674, 6.94498021], [ 0.71540198, 0.97553514]]), array([[ 3.04671636, 2.74375001], [ 3.19246634, 3.28516669], [ 7.42117955, 7.25403886], [ 7.12337213, 6.72896363], [ 6.80853771, 6.82932201], [ 6.56014649, 6.96719779], [ 2.75383971, 3.02254777], [ 1.32533361, 0.92380979], [ 7.10911346, 7.07564848], [ 0.74497763, 0.99293499]])] I would like to format that output to 2 decimal places. However, I'm not sure how as the typical print "{:.2f}".format(cntrs[i]) does not work. This is what I have so far: for i in range(len(cntrs)): print "Number of Centres: "…
has answer: http://stackoverflow.com/a/48952455

http://stackoverflow.com/comment/84697232
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48844563
score: 0
has text: So where does the program get stuck? Is it stuck sending or stuck receiving?

http://stackoverflow.com/comment/84762559
type: AnswerComment
comment on: http://stackoverflow.com/a/48859085
score: 0
type: Comment
has text: @ HYRY Could you advise how would i go about if one of my axis has categorical values... Would i still use .values ?

http://stackoverflow.com/q/48884280
tagged with: matplotlib
has body: I'm trying to extens this example and plot 2 3d surface plots side by side. Here is the code, it works, but for some reason plots displayed cropped and squeezed. How to fix it? #Plot side by side def plot_xyz_data(): n_radii = 8 n_angles = 36 radii = np.linspace(0.125, 1.0, n_radii) angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False) angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) x = np.append(0, (radii*np.cos(angles)).flatten()) y = np.append(0, (radii*np.sin(angles)).flatten()) z1 = np.sin(-x*y) z2 = np.cos(x**2) print('x.shape', x.shape) print('y.shape', y.shape) print('z1.shape', z1.shape) print('z2.shape', z2.shape) fig = plt.figure() ax1 = fig.add_subplot(121,projection='3d') surf1 = ax1.plot_trisurf(x, y, z1, cmap=cm.jet, antialiased=True) ax1.set_xlabel('x label') ax1.set_ylabel('y label') ax1.set_zlabel('z1 label') ax2 = fig.add_subplot(122,projection='3d') surf2 = ax2.plot_trisurf(x, y, z2, cmap=cm.jet, antialiased=True) ax2.set_xlabel('x label') ax2.set_ylabel('y label') ax2.set_zlabel('z2 label') plt.savefig("sample.png",bbox_inches='tight',dpi=100) plt.show() plot_xyz_data() Update: Looks like setting fig = plt.figure(figsize=(16, 12)) helps, but still not perfect: 'y label' overlaps with numbers. Any way to fix it?
has comment: http://stackoverflow.com/comment/84773382
type: Question
has comment: http://stackoverflow.com/comment/84791459
tagged with: 3d
answer count: 1
linked to: http://stackoverflow.com/q/332289
score: 0
has title: Plot 2 3d surface side by side using matplotlib
tagged with: python
has comment: http://stackoverflow.com/comment/84773015
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48885777

http://stackoverflow.com/comment/84952157
comment on: http://stackoverflow.com/a/48972445
type: Comment
score: 1
has text: It is much MUCH better the official Fortran to C interoperability. See [tag:fortran-iso-c-binding]. **Only** if you use `bind(C)` you can count with the fact that optional arguments use NULL pointers. Without `bind(C)` the compiler can do whatever it wants. It can alse change the weird mangeled name `__test_module_MOD_fstr_test` to whatever it wants, it may differ between compiler versions and it **will** differ between different compilers. You can read about passing-by-reference and similar there as well.
type: AnswerComment

http://stackoverflow.com/comment/84707813
score: 0
has text: Might be a permissions issue. Can you try running your server as root and see if it still occurs? If it does then it is definitely a permissions issue
comment on: http://stackoverflow.com/q/48840076
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84804206
type: Comment
comment on: http://stackoverflow.com/q/48899448
type: QuestionComment
has text: The range is only calculate once
score: 0

http://stackoverflow.com/a/48914582
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48914481
answers question: http://stackoverflow.com/q/48914481
type: Answer
has body: Your match list should be: matchlist = ['.csv', '.txt', '.jpg', '.png'] Then change your: for entry in matchlist: if file.endswith(entry): filearray[TheAppropriateSubArray].append(os.path.join(root, file)) To: for i, entry in enumerate(matchlist): if file.endswith(entry): filearray[i].append(os.path.join(root, file))
upvote count: 1
score: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48961268
has answer: http://stackoverflow.com/a/48961591
has body: I am having two lists list1 and list2 as: list1 = [4, 3, 20, 10] list2 = ['a', 'f', 'd', 'b'] I want to create a new list result based on the condition that if my condition num==10 is True, then result should be holding the content from list1 else it should be holding the content from list2. Below is the code I tried: num = 10 result = [element for element in list1 if num == 10 else list2] But this is raising SyntaxError. How should I achieve this? Expected output for above code is: [4, 3, 20, 10] # stored in `result`
accepted answer: http://stackoverflow.com/a/48961591
tagged with: list
upvote count: 3
has title: List Comprehension but on list selected for iteration based on condition
type: AnsweredQuestion
score: 3
possible better answer: http://stackoverflow.com/a/48961294
tagged with: list-comprehension
type: Question
answer count: 2
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48961294
tagged with: python

http://stackoverflow.com/comment/84918586
comment on: http://stackoverflow.com/q/48947290
score: 0
type: Comment
type: QuestionComment
has text: There is probably a typo in here: `results = [j.result() for j in jobs()]`. You call a list `jobs`.

http://stackoverflow.com/q/48887461
has answer: http://stackoverflow.com/a/49006837
has comment: http://stackoverflow.com/comment/84789072
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84793731
has comment: http://stackoverflow.com/comment/84984115
answer count: 2
has comment: http://stackoverflow.com/comment/84796643
has body: I need to create a boolean mask by thresholding a 3D data array: mask at locations where data are smaller than lower acceptable limit or data are larger than upper acceptable limit must be set to True (otherwise False). Succinctly: mask = (data &lt; low) or (data &gt; high) I have two versions of the code for performing this operation: one works directly with entire 3D arrays in numpy while the other method loops over slices of the array. Contrary to my expectations, the second method seems to be faster than the first one. Why??? In [1]: import numpy as np In [2]: import sys In [3]: print(sys.version) 3.6.2 |Continuum Analytics, Inc.| (default, Jul 20 2017, 13:14:59) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] In [4]: print(np.__version__) 1.14.0 In [5]: arr = np.random.random((10, 1000, 1000)) In [6]: def method1(arr, low, high): ...: """ Fully vectorized computations """ ...: out = np.empty(arr.shape, dtype=np.bool) ...: np.greater_equal(arr, high, out) ...: np.logical_or(out, arr &lt; low, out) ...: return out ...: In [7]: def method2(arr, low, high): ...: """ Partially vectorized computations """ ...: out = np.empty(arr.shape, dtype=np.bool) ...: for k in range(arr.shape[0]): ...: a = arr[k] ...: o = out[k] ...: np.greater_equal(a, high, o) ...: np.logical_or(o, a &lt; low, o) ...: return out ...: First of all, let's make sure that both methods produce identical results: In [8]: np.all(method1(arr, 0.2, 0.8) == method2(arr, 0.2, 0.8)) Out[8]: True And now some timing tests: In [9]: %timeit method1(arr, 0.2, 0.8) 14.4 ms ± 111 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [10]: %timeit method2(arr, 0.2, 0.8) 11.5 ms ± 241 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) What is going on here? EDIT 1: A similar behavior is observed in an older environment: In [3]: print(sys.version) 2.7.13 |Continuum Analytics, Inc.| (default, Dec 20 2016, 23:05:08) [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)] In [4]: print(np.__version__…
has comment: http://stackoverflow.com/comment/84797153
has comment: http://stackoverflow.com/comment/84781325
has comment: http://stackoverflow.com/comment/84793881
has comment: http://stackoverflow.com/comment/84782414
score: 8
favorite count: 0
has comment: http://stackoverflow.com/comment/84786446
has title: Why Python loops over slices of numpy arrays are faster than fully vectorized operations
has comment: http://stackoverflow.com/comment/84782673
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48888971
tagged with: python
has comment: http://stackoverflow.com/comment/84797464
has comment: http://stackoverflow.com/comment/84781168
has comment: http://stackoverflow.com/comment/84797175
upvote count: 9

http://stackoverflow.com/a/77608677
has body: Given your definition of path can skip steps to find the frequently visited nodes in order, you'd be able to use the PrefixSpan algorithm: https://github.com/chuanconggao/PrefixSpan-py It works pretty similarly to the Frequent Itemset
has comment: http://stackoverflow.com/comment/136839812
answers question: http://stackoverflow.com/q/48919839
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/51930213
score: 1
upvote count: 1
has body: #Send a text from bot to channel by forward @bot.message_handler(func=lambda message: True) def main(message): if message.forward_from_chat: apiuz=message.forward_from_chat count = bot.get_chat_members_count(apiuz.id) bot.send_message(chat_id, count)
answers question: http://stackoverflow.com/q/48945023
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/90810632

http://stackoverflow.com/comment/84960179
type: QuestionComment
has text: Notice that library recommendation questions are explicitly disallowed on Stack Overflow. A quick search on PyPi should be your first stop, ideally before asking others for help.
score: 0
comment on: http://stackoverflow.com/q/48937131
type: Comment

http://stackoverflow.com/comment/85113016
type: Comment
score: 0
type: AnswerComment
has text: @a.buyer as stated before by jfs, there is no need to execute the command in 'cmd'. Popen supports opening a process with an **interactive shell** which is the same as launching the process in 'cmd'. I'll edit with a suggestion for how you'd do this. Now, if you're trying to write your own shell, calling command prompt is the wrong way to do it.
comment on: http://stackoverflow.com/a/48849086

http://stackoverflow.com/comment/84640012
type: QuestionComment
comment on: http://stackoverflow.com/q/48817141
score: 0
type: Comment
has text: @juanpa.arrivillaga Thanks! This was actually the first time I used lambda in Python. Corrected it. This nearly doubled the time needed for the lambda lookup.

http://stackoverflow.com/q/48895035
tagged with: profiling
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3
has title: Tensorboard-- Compute time of a High-level node is not the same as the summation of compute times of its sub-nodes
answer count: 0
upvote count: 3
tagged with: tensorflow
type: Question
has body: Following the tutorial on TensorFlow, I am trying to understand run-time statistics using tensorboard. I find that the compute time of a High-level node representing a name scope is not equal to the sum of compute times of its sub-nodes. Why isn't it the same? For example, in the attached snapshot: Compute time of ConvLayer2 = 75.5 ms, while the Sub-nodes compute time = 55.2 (conv) + 1.73 (add) + 1 (other nodes) = 57.9 ms Snapshot of ConvLayer2 import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data g = tf.Graph() with g.as_default(): def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding = "SAME") def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides = [1, 2, 2, 1], padding = "SAME") mnist = input_data.read_data_sets('MNIST_data', one_hot=True) x = tf.placeholder(tf.float32, shape=[100, 784], name = "X_input") # Input layer y_= tf.placeholder(tf.float32, shape=[100, 10], name = "Y_labels") # Reshape input vector into a 4d tensor x_image = tf.reshape(x, [-1, 28, 28, 1]) # Layer 1 with tf.name_scope('ConvLayer1'): W_conv1 = tf.Variable(tf.truncated_normal([5, 5, 1, 32], stddev=0.1), name = "Weights_L1") b_conv1 = tf.Variable(tf.constant(0.1, shape = [32]), name = "Bias_L1") h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) # Layer 2 with tf.name_scope('ConvLayer2'): W_conv2 = tf.Variable(tf.truncated_normal([5, 5, 32, 64], stddev=0.1), name = "Weights_L2") b_conv2 = tf.Variable(tf.constant(0.1, shape = [64]), name = "Bias_L2") h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) # Layer 3 : Fully Connected Layer with tf.name_scope('FullyConnectLayer1'): w_fc1 = tf.Variable(tf.truncated_normal([7*7*64, 1024], stddev=0.1), name = "Weights_fc1") b_fc1 = tf.Variable(tf.constant(0.1, shape = [1024]), name = "Bias_fc1") # Flatten h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_f…

http://stackoverflow.com/comment/85004960
has text: It's because when using `zc.buildout`, it will create a `./bin/python` script as an interpreter of the project and adds `./eggs` modules to python path. But if I set `./bin/python` of the vscode interpreter, then pylint won't work. I don't know how to config vscode...
comment on: http://stackoverflow.com/q/48945744
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48918354
tagged with: django
has answer: http://stackoverflow.com/a/65320258
type: Question
has comment: http://stackoverflow.com/comment/84844356
tagged with: mongoengine
tagged with: mongodb
answer count: 2
score: 5
downvote count: 0
has body: I have a django project, defautly testing on Django only works on sql database, but I need to work on mongodb and mongoengine. I use Django 1.9, mongoengine 0.9 cause it supports django. I follow the docs here https://mongoengine.readthedocs.io/en/v0.9.0/django.html and django docs for test https://docs.djangoproject.com/en/1.8/topics/testing/tools/ The problem is how I can config the test file to tell it I want to use mongodb database. Without any setup, the test file look like this: import unittest from django.test import Client from .models import User class UserTests(unittest.TestCase): def setUp(self): self.client = Client() def test_create_user(self): self.client.post('/users/', {'first_name': 'aaa', 'last_name': 'bbb', 'username': 'xxx', 'email': 'abc@gmail.com'}) ... The error when run python manage.py test will be: raise ImproperlyConfigured("settings.DATABASES is improperly configured. " ImproperlyConfigured: settings.DATABASES is improperly configured. Please supply the ENGINE value. Check settings documentation for more details. In settings.py: from mongoengine import connect DATABASES = { 'default': { 'ENGINE': 'django.db.backends.dummy', }, } connect( host='mongodb://localhost/book' )
favorite count: 0
has title: Testing django with mongoengine
upvote count: 5
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84844516
has answer: http://stackoverflow.com/a/50470352

http://stackoverflow.com/q/48877134
accepted answer: http://stackoverflow.com/a/48877153
tagged with: python
has title: Compare strings after removing extra whitespace in an efficient way
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48877149
has answer: http://stackoverflow.com/a/48877149
type: Question
has answer: http://stackoverflow.com/a/48877153
has body: &gt;&gt;&gt; oranges = "10 100 200" &gt;&gt;&gt; oranges == "10 100 200" False &gt;&gt;&gt; apples = "10 20 30" &gt;&gt;&gt; apples == "10 20 30" True Expecting output for oranges is True for "10 100 200" in my case. I am looking for whether 10 100 200 are present in order wise . I tried striping but it will do only start of the string and end of the string.
tagged with: python-2.7
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48881434

http://stackoverflow.com/q/48807841
has comment: http://stackoverflow.com/comment/84618494
tagged with: machine-learning
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84618709
score: 1
has body: I am trying to excute this piece of pythoncode.But this is showing an error.Help me to resolve this error. import numpy as np import matplotlib.pyplot as pt import pandas as pd from sklearn.tree import DecisionTreeClassifier data=pd.read_csv('train.csv').as_matrix() clf=DecisionTreeClassifier() xtrain=data[0:21000,1:] train_label=data[0:21000,0] clf.fit(xtrain,train_label) xtest=data[21000:,1:] actual_label=data[21000:,0] d=xtest[8] d.shape(28,28) pt.imshow(255-d,cmap='gray') print(clf.predict([xtest[8]])) pt.show() ERROR IS SHOWING LIKE THIS TypeError: 'tuple' object is not callable
has answer: http://stackoverflow.com/a/48807996
has comment: http://stackoverflow.com/comment/84618859
answer count: 2
has title: Getting an error while executing this python code related to the shape of the matrix
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84618736
possible better answer: http://stackoverflow.com/a/48808065
accepted answer: http://stackoverflow.com/a/48807996
has answer: http://stackoverflow.com/a/48808065
tagged with: python
tagged with: jupyter
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84619029
upvote count: 2

http://stackoverflow.com/comment/84700014
comment on: http://stackoverflow.com/a/48840608
score: 0
type: AnswerComment
has text: I was worried about the performance since in this case a new Future has to be created quite often—but I guess if it's so low-level, implemented in C and is used under whole asyncio, it souldn't really be an issue. Do you have any tips on how to avoid those errors you've seen? Read the docs carefully, I guess?
type: Comment

http://stackoverflow.com/comment/84743869
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48869775
has text: Also, provide your code.

http://stackoverflow.com/comment/84666468
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48814291
has text: @mrfreester, I believe it is not specific to the website. But yes I am not sure.

http://stackoverflow.com/q/48804907
has comment: http://stackoverflow.com/comment/84667723
tagged with: fipy
tagged with: python
linked to: http://stackoverflow.com/q/29863958
accepted answer: http://stackoverflow.com/a/48831816
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84851393
has comment: http://stackoverflow.com/comment/84777526
has body: I am modeling electrical current through various structures with the help of FiPy. To do so, I solve Laplace's equation for the electrical potential. Then, I use Ohm's law to derive the field and with the help of the conductivity, I obtain the current density. FiPy stores the potential as a cell-centered variable and its gradient as a face-centered variable which makes sense to me. I have two questions concerning face-centered variables: If I have a two- or three-dimensional problem, FiPy computes the gradient in all directions (ddx, ddy, ddz). The gradient is a FaceVariable which is always defined on the face between two cell centers. For a structured (quadrilateral) grid, only one of the derivates should be greater than zero since for any face, the position of the two cell-centers involved should only differ in one coordinate. In my simulations however, it occurs frequently that more than one of the derivates (ddx, ddy, ddz) is greater than zero, even for a structured grid. The manual gives the following explanation for the FaceGrad-Method: Return gradient(phi) as a rank-1 FaceVariable using differencing for the normal direction(second-order gradient). I do not see, how this differs from my understanding pointed out above. What makes it even more problematic: Whenever "too many" derivates are included, current does not seem to be conserved, even in the simplest structures I model... Is there a clever way to access the data stored in the face-centered variable? Let's assume I would want to compute the electrical current going through my modeled structure. As of right now, I save the data stored in the FaceVariable as a tsv-file. This yields a table with (x,y,z)-positions and (ddx, ddy, ddz)-values. I read the file and save the data into arrays to use it in Python. This seems counter-intuitive and really inconvenient. It would be a lot better to be able to access the FaceVariable along certain planes or at certain points.
type: Question
has comment: http://stackoverflow.com/comment/84789584
has comment: http://stackoverflow.com/comment/84837029
answer count: 1
has answer: http://stackoverflow.com/a/48831816
score: 0
has comment: http://stackoverflow.com/comment/84716487
has title: FaceVariables in FiPy
tagged with: simulation

http://stackoverflow.com/comment/84691052
type: QuestionComment
comment on: http://stackoverflow.com/q/48843380
has text: What exactly do you want the output file to look like? Student names and "You received an F" in separate columns?
score: 0
type: Comment

http://stackoverflow.com/a/48805769
has body: The problem you're having is that getchildren() returns a list of the child elements, not a single element. So this list doesn't have the .text attribute. To access this, you now need to loop over this list (of child elements) and retrieve the text for each of them. You can do this really easily with the ElementTree package, as it lets you treat the element like a list containing its child elements. So you don't need to use .getchildren to make a list of child elements - elem itself is already one. (Since this feature was introduced, .getchildren is deprecated, and you're encouraged to use the list-like features instead). So your code should look something like this: import xml.etree.ElementTree as ET tree = ET.parse('sample.xml') root = tree.getroot() # find each alarmTime element for elem in root.iter(tag ='alarmTime'): # loop over its child elements for child_elem in elem: # print the tag and text print(child_elem.tag) print(child_elem.text) Obviously, you might want to store this information, rather than just printing it. If you're expecting to find multiple copies of the alarmTime element, each with child elements whose tag and text you want to retrieve, I'd use a list of lists, with each child element stored as a tuple of its tag and text. I also normally use the term subelement rather than child element: import xml.etree.ElementTree as ET tree = ET.parse('sample.xml') root = tree.getroot() # main list for alarmTime data alarmTime_list = [] for elem in root.iter(tag ='alarmTime'): # create a list for data from this alarmTime element data = [] # loop over subelements for subelem in elem: # add the subelement tag and text as a tuple data.append((subelem.tag, subelem.text)) # add the set of data for this alarmTime element to the main list alarmTime_list.append(data) These references might be helpful for you: I found this quite helpful as an introduction when I was learning to use ElementTree: http://effbot.org/zone/element.htm This is more detailed, and also cove…
type: Answer
accepted answer of: http://stackoverflow.com/q/48804937
answers question: http://stackoverflow.com/q/48804937
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48918095
has comment: http://stackoverflow.com/comment/84842727
has comment: http://stackoverflow.com/comment/84843008
tagged with: location
has title: Python: How to find trip based on location of people
type: UnansweredQuestion
tagged with: repeat
tagged with: python
has body: I have a dataset like this: use_id time lat-lon bin repeated 1335 08:05:00 (87,78) 20 1 1335 08:10:00 (87,78) 20 2 1335 08:15:00 (87,78) 20 3 1335 08:20:00 (88,78) 22 1 1335 08:25:00 (88,78) 22 2 1335 08:30:00 (89,78) 23 1 1335 08:35:00 (89,70) 25 1 1335 08:40:00 (80,78) 26 1 1335 08:45:00 (80,78) 26 2 1335 08:50:00 (80,78) 26 3 1335 08:55:00 (80,78) 26 4 .... ........ ....... .. . I want to find trips based on bins. Here is the idea: The trip will start when the current bin is different from the next bin.And, after seeing four repeated bin the trip should end on the first repeated bin. For each trip I want to extract the "lat-lon" and "time" of the start point and end point of the trip. At the end I want to have a list of trips for each distinct "user_id". For example, here, the trip should start from the last 20 and should finish on the first 26. So, at the end I should have something like this: [20,26]=[((87,78), 08:15:00), ((80,78), 08:40:00)] (I my dataset I have more "user_id". Here you can see just one.) I added the "repeated" column to find the repetition of the bin. I taught maybe it can help me in the process but I don't know how to continue. Please tell me if it needs more information. Thanks
has comment: http://stackoverflow.com/comment/84842816
has comment: http://stackoverflow.com/comment/84844055
has comment: http://stackoverflow.com/comment/84842780
answer count: 0
has comment: http://stackoverflow.com/comment/84843046
score: 0
has comment: http://stackoverflow.com/comment/84842891
type: Question
has comment: http://stackoverflow.com/comment/84878723

http://stackoverflow.com/comment/84661514
type: QuestionComment
comment on: http://stackoverflow.com/q/48828658
score: 0
type: Comment
has text: If you really want to hide a method you can create a Cython extension with a cdef method. Take note, that there is no need to use any C semantics in Cython extensions, so it might as well be an exact copy of your class, except for `cdef`.

http://stackoverflow.com/comment/84739788
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48867660
type: Comment
has text: your solution works fine but i still have an issue with the value contained in another string. For example ‘manpower’ contains ‘man’ and I didn't want to match it.

http://stackoverflow.com/q/48814575
downvote count: 1
has answer: http://stackoverflow.com/a/48814833
type: AnsweredQuestion
has title: Verify simple human readable urls in Python - validate domain name offline
linked to: http://stackoverflow.com/q/44644501
linked to: http://stackoverflow.com/q/7160737
linked to: http://stackoverflow.com/q/2532053
has comment: http://stackoverflow.com/comment/84641943
accepted answer: http://stackoverflow.com/a/48814833
type: Question
has comment: http://stackoverflow.com/comment/84641435
score: 0
has body: I found a lot of questions for this, but I found no practical answer. I don't need http or www, users should be allowed to enter e.g. example.com Allowed: http://www.example.berlin https://example.de/more www.sub.example.de example.de Not allowed: example 1 ::::: ..... problem with other questions: Python - How to validate a url in python ? (Malformed or not) (does not accept "example.com") http://validators.readthedocs.io/en/latest/ (does not accept "example.com") https://stackoverflow.com/a/2532344/1907997 (allows "example") ^([a-z0-9]+(-[a-z0-9]+)*.)+[a-z]{2,}$ (does not allow http or sub domains) urlparse (does not accept "example.com") So I think I need regular expression for this like in the last example above but a little bit extended. https://docs.python.org/3.6/library/re.html With this code all examples are working but not "example.de/more" def verify_url(self, url): url = url.strip() if url[-1] == ".": url = url[:-1] if url[-1] == "/": url = url[:-1] url = url.replace("https://", "") url = url.replace("http://", "") if url.startswith("www."): url = url.replace("www.", "") result = re.match( "^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$", url) if result: return url
has comment: http://stackoverflow.com/comment/84641463
has comment: http://stackoverflow.com/comment/84641477
answer count: 1
has comment: http://stackoverflow.com/comment/84632904
favorite count: 0
has comment: http://stackoverflow.com/comment/84641422
tagged with: python
upvote count: 1

http://stackoverflow.com/q/48893369
has answer: http://stackoverflow.com/a/48895423
answer count: 2
has body: I need to take lines from a file and append it to the end of lines in another file, IF they have a commonality (the same path, in my case). Example lines from the first file ('out.txt'): \vol\vol1\path1: The inherited access control list (ACL) or access control entry (ACE) could not be built. (119) \vol\path2: Access is denied. (2) \vol\vol24\path27: Access is denied. (401) Could not convert the name of inner file or directory (111) Example lines from the file I'd like to append to ('fixed_inv.txt') in the form of a new file called 'concat.txt': 42 sggisnap013.example.com xskld_$FOLw \vol\vol1\path1 42 sggisnap013.example.com /vol/vol7 /vol/vol7 42 sggisnap013.example.com HOME \vol\vol0\home As you can see in both files, there is a commonality. It happens to be the path: \vol\vol1\path1 Sometimes you'll see the same paths with a different server name (sggisnap013.example.com) like: 44 tkgisnstor012.nomura.com /vol/vol1 42 sggisnap013.example.com xskld_$FOLw /vol/vol1 It must have the same server AND path before executing the append. However, in other cases, the commonality will be a different path. I've written this code: err = [] inv = [] with open('out.txt', 'r') as f1: for line in f1: #for each line split_line = line.split(' ') index_f1 = split_line[0] err = index_f1 with open('fixed_inv.txt', 'r') as f2: for line in f2: #for each line split_line = line.split('\t') #split the line by each tab, call that split_line index_f2 = split_line[3] #key2 will hold the item occuring at split index 3 inv.append(index_f2) with open('concat.txt', 'w') as file_out: for line in err: for line in inv: if err == inv: file_out.write(line) else: continue NOTE: 'out.txt' is the file I'm appending to 'fixed_inv.txt'. The result will be a new file. However, when I run this, I get something interesting, but not what I want: \\\\\\\\aappppsssss__33\\\\ttrrssssspprrsssss I would appreciate any ideas for how to go about doing this properly. Thank you.
has title: How to append a file's line to a different file's line based on a commonality?
has answer: http://stackoverflow.com/a/48893478
score: 0
has comment: http://stackoverflow.com/comment/84793707
tagged with: python
has comment: http://stackoverflow.com/comment/84793935
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84794174
has comment: http://stackoverflow.com/comment/84794883
type: Question

http://stackoverflow.com/q/48881292
has answer: http://stackoverflow.com/a/48881464
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48881464
tagged with: web-scraping
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48881507
type: AnsweredQuestion
score: 1
possible better answer: http://stackoverflow.com/a/48881507
type: Question
answer count: 2
has body: My code below gives a list of urls.If I want any specific url how to resolve this: My code is given below: import bs4, requests index_pages = ('https://www.tripadvisor.in/Hotels-g60763-oa{}-New_York_City_New_York-Hotels.html#ACCOM_OVERVIEW'.format(i) for i in range(0, 180, 30)) urls = [] with requests.session() as s: for index in index_pages: r = s.get(index) soup = bs4.BeautifulSoup(r.text, 'lxml') url_list = [i.get('href') for i in soup.select('.property_title')] urls.append(url_list) print(url_list) Now the output I am getting as a list of Urls.Output is given below: New_York_City_New_York.html', '/Hotel_Review-g60763-d93543-Reviews-Shelburne_NYC_an_Affinia_hotel-New_York_City_New_York.html', '/Hotel_Review-g60763-d1485603-Reviews-Comfort_Inn_Times_Square_West-New_York_City_New_York.html', '/Hotel_Review-g60763-d93340-Reviews-Hotel_Elysee_by_Library_Hotel_Collection-New_York_City_New_York.html', '/Hotel_Review-g60763-d1641016-Reviews-The_Chatwal_A_Luxury_Collection_Hotel_New_York-New_York_City_New_York.html', '/Hotel_Review-g60763-d93585-Reviews-Lowell_Hotel-New_York_City_New_York.html'] D:\anaconda3\lib\site-packages\requests\packages\urllib3\connectionpool.py:852: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning) ['/Hotel_Review-g60763-d277882-Reviews-Hampton_Inn_Manhattan_Seaport_Financial_District-New_York_City_New_York.html', '/Hotel_Review-g60763-d3529145-Reviews-Holiday_Inn_Express_Manhattan_Times_Square_South-New_York_City_New_York.html', '/Hotel_Review-g60763-d208453-Reviews-Hilton_Times_Square-New_York_City_New_York.html', '/Hotel_Review-g60763-d249711-Reviews-The_Hotel_at_Times_Square-New_York_City_New_York.html', '/Hotel_Review-g60763-d1158753-Reviews-Kimpton_Ink48_Hotel-New_York_City_New_York.html', '/Hotel_Review-g60763-d1186070-Reviews-Marriott_Vacation_Club_Pulse_New_York_City-New…
tagged with: fuzzy-search
downvote count: 0
has title: Unable to findout an Url from an output url list

http://stackoverflow.com/comment/84703284
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48826372
type: QuestionComment
has text: [The API doc](https://www.tensorflow.org/api_docs/python/tf/metrics/accuracy) seems to answer your question. ``` The accuracy function creates two local variables, total and count that are used to compute the frequency with which predictions matches labels. This frequency is ultimately returned as accuracy: an idempotent operation that simply divides total by count. ```

http://stackoverflow.com/q/48820118
has title: Variables not recognized after importing function from second script (Python)
tagged with: variables
has comment: http://stackoverflow.com/comment/84643982
favorite count: 0
has answer: http://stackoverflow.com/a/48820135
has body: I am calling a function from a second script but the variable from the first script is not recognized. script1 selection = int(raw_input("Enter Selection: ")) if selection == 1: import script2 script2.dosomething() script2 def dosomething(): while selection == 1: ...... ...... It displays "NameError: global name 'selection' is not defined" Is it something to do with global variables?
upvote count: 2
has comment: http://stackoverflow.com/comment/84643878
has comment: http://stackoverflow.com/comment/84644037
tagged with: python
accepted answer: http://stackoverflow.com/a/48820135
linked to: http://stackoverflow.com/q/291978
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48820199
score: 1
has comment: http://stackoverflow.com/comment/84644071
has answer: http://stackoverflow.com/a/48820199
downvote count: 1
has comment: http://stackoverflow.com/comment/84643985
type: Question
has comment: http://stackoverflow.com/comment/84644004
linked to: http://stackoverflow.com/q/3400525
answer count: 2
linked to: http://stackoverflow.com/q/4693120

http://stackoverflow.com/comment/84841684
score: 0
has text: Hmm wait, you need to clarify. So flask is running on a remote server, correct? And you want to access it from your local machine? Is the proxy server, the same as the one running the flask app?
comment on: http://stackoverflow.com/q/48917310
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84917018
has text: returns `wrong_list_fixed = [[0, <itertools._grouper object at 0x7f03ceef6550>], ...`
type: Comment
comment on: http://stackoverflow.com/a/48955090
score: 3
type: AnswerComment

http://stackoverflow.com/q/48937957
tagged with: django
answer count: 1
has title: Combine 2 Django Querysets
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48938006
downvote count: 0
has comment: http://stackoverflow.com/comment/84882908
has body: I want to merge two queryset in Django using operand "|" but it don't work. I know that to do it you must have querysets from the same model. This is exactly what I'm trying to do. The loop is because I want to get random objects and merge it into one. Anyone have idea why Django throw "TypeError: unsupported operand type(s) for |: 'Sentence' and 'Sentence'" error? According to below source this is how to make it happen: https://simpleisbetterthancomplex.com/tips/2016/06/20/django-tip-5-how-to-merge-querysets.html from random import randint from sentences.models import Sentence sentence_number = 3 first_pk = Sentence.objects.first().pk last_pk = Sentence.objects.last().pk for i in range(sentence_number): next_pk = randint(first_pk, last_pk) sentence_qs = Sentence.objects.get(pk=next_pk) type(sentence_qs) if i &gt; 1: sentence_qs = sentence_qs | Sentence.objects.get(pk=next_pk)
favorite count: 0
accepted answer: http://stackoverflow.com/a/48938006
type: Question
tagged with: python
upvote count: 2

http://stackoverflow.com/a/48963758
score: 10
accepted answer of: http://stackoverflow.com/q/48962594
upvote count: 10
answers question: http://stackoverflow.com/q/48962594
type: AcceptedAnswer
downvote count: 0
has body: np.arange(2) gives array([0, 1]), so only two values. If you try to plot three values (in y1 or y2) against this, that won't work and it will throw the ValueError (telling you exactly this): ValueError: shape mismatch: objects cannot be broadcast to a single shape Try using np.arange(3).
type: Answer

http://stackoverflow.com/q/48957769
answer count: 1
has comment: http://stackoverflow.com/comment/84922680
favorite count: 0
has comment: http://stackoverflow.com/comment/84922717
has comment: http://stackoverflow.com/comment/84922638
tagged with: random
has comment: http://stackoverflow.com/comment/84922752
has comment: http://stackoverflow.com/comment/84922615
linked to: http://stackoverflow.com/q/240178
has comment: http://stackoverflow.com/comment/84922762
tagged with: python
has title: Mysterious Bug Within Python Loop?
duplicate of: http://stackoverflow.com/q/240178
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84922646
score: -3
downvote count: 3
has comment: http://stackoverflow.com/comment/84922745
has body: So, I was working on some basic finance, trying to simulate a number of random stock price paths, when I encountered this inscrutable bug in the code. I try to print out a single number many times in a nested loop, but for some reason the number varies. My code so far: # Imports. %matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt from math import * # Error-producing section - randnorm holds a 10x10 vector of normally distributed # random numbers, used in calculating my price path. sims = 5 intervals = 5 r=.02 T=1 sigma=.15 paths = [[1]*intervals]*sims randnorm = [[np.random.normal() for x in range(10)] for y in range(10)] # print(randnorm) for i in range(sims): for j in range(1,intervals): paths[i][j] = paths[i][j-1] * exp((r - .5*sigma**2)*(T/intervals) + sqrt(T/intervals)*randnorm[i][j-1]) print(paths[0][1]) I knew something was wrong with my previous code, so I tried debugging by printing in each loop, and I get this, 0.5937221173702402 0.5937221173702402 0.5937221173702402 0.5937221173702402 1.4849274521869171 1.4849274521869171 1.4849274521869171 1.4849274521869171 0.860018700453769 0.860018700453769 0.860018700453769 0.860018700453769 1.0709782525755074 1.0709782525755074 1.0709782525755074 1.0709782525755074 0.7184834195858915 0.7184834195858915 0.7184834195858915 0.7184834195858915 What gives? I seriously do not know where I could be wrong here. It's not my random numbers, which are all different, or an index issue.
has comment: http://stackoverflow.com/comment/84922529
has comment: http://stackoverflow.com/comment/84922857
has answer: http://stackoverflow.com/a/48957956
tagged with: loops
has comment: http://stackoverflow.com/comment/84922756
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/84922740
upvote count: 0

http://stackoverflow.com/q/48817174
possible better answer: http://stackoverflow.com/a/48823087
tagged with: django-1.11
has body: So, I'm trying to do a little bit of compression of images as well as some other operations. I had a few questions...I have the following save() method for my user class: class User(AbstractBaseUser, PermissionsMixin): ... avatar = models.ImageField(storage=SITE_UPLOAD_LOC, null=True, blank=True) def save(self, *args, **kwargs): if self.avatar: img = Img.open(BytesIO(self.avatar.read())) if img.mode != 'RGB': img = img.convert('RGB') new_width = 200 img.thumbnail((new_width, new_width * self.avatar.height / self.avatar.width), Img.ANTIALIAS) output = BytesIO() img.save(output, format='JPEG', quality=70) output.seek(0) self.avatar= InMemoryUploadedFile(file=output, field_name='ImageField', name="%s.jpg" % self.avatar.name.split('.')[0], content_type='image/jpeg', size=, charset=None) super(User, self).save(*args, **kwargs) I had two questions: Best way for deleting the old avatar file on save, if a previous avatar exists What do I pass into InMemoryUploadedFile for the size kwarg? Is this the size of the file? in what unit/(s)?
favorite count: 0
tagged with: django
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/48823087
has title: Custom save method for images/avatars in Django - how to use
score: 1
has comment: http://stackoverflow.com/comment/84649916
accepted answer: http://stackoverflow.com/a/48822880
linked to: http://stackoverflow.com/q/2878490
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48822880
has comment: http://stackoverflow.com/comment/84649924

http://stackoverflow.com/q/48909600
has comment: http://stackoverflow.com/comment/84825333
score: 20
has answer: http://stackoverflow.com/a/51628603
answer count: 3
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: numpy
has body: I need to solve a set of simultaneous equations of the form Ax = B for x. I've used the numpy.linalg.solve function, inputting A and B, but I get the error LinAlgError: Last 2 dimensions of the array must be square Here's my code: A = numpy.matrix([(-0.56, -0.52), (0.44, 0.46), (0.69, 0.71)]) B = [(-0.38, -24.09, 0.0)] x = numpy.linalg.solve(A, B) x should have the form (x1,x2,0). How do I fix this?
has answer: http://stackoverflow.com/a/48911789
upvote count: 20
has title: LinAlgError: Last 2 dimensions of the array must be square
has comment: http://stackoverflow.com/comment/84829817
tagged with: linear-algebra
has comment: http://stackoverflow.com/comment/84830363
has answer: http://stackoverflow.com/a/76659075

http://stackoverflow.com/a/48818502
has body: This is a plain vanilla concat pd.concat([A, B, C]) 1 2 3 4 5 6 7 8 9 10 0 1 1 1 1 1 1 1 0 0 1 1 1 0 1 1 1 1 1 1 0 0 1 0 2 0 1 1 1 0 0 0 0 0 1 0
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/48818406
answers question: http://stackoverflow.com/q/48818406
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84925602
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48937262
has text: @Lacri Mosa, have you tried this script? Whats the feedback?

http://stackoverflow.com/q/48827155
type: Question
tagged with: matplotlib
has title: subplot in matplotlib.pyplot from function
upvote count: 1
has comment: http://stackoverflow.com/comment/84658328
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48827201
accepted answer: http://stackoverflow.com/a/48827201
type: AnsweredQuestion
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84658233
has body: I tried to create subplot by using some defined function, which returns directly plot. But I can't figure out why this is not working. for example: my plot function is something like: def plot_data(data): plt.plot(data) return plt.show() suppose my data are: data1 = np.random.rand(50) data2 = np.random.rand(50) data3 = np.random.rand(50) data4 = np.random.rand(50) and I am trying to create subplot with: fig, ax = plt.subplots(nrows=2, ncols=2) plt.subplot(2, 2, 1) plot_data(data) plt.subplot(2, 2, 2) plot_data(data) plt.subplot(2, 2, 3) plot_data(data) plt.subplot(2, 2, 4) plot_data(data) plt.tight_layout() plt.show() it returns :

http://stackoverflow.com/comment/84950331
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48942624
has text: You have a typo - `endcode_base64` should be `encode_base64`
type: Comment

http://stackoverflow.com/a/76246779
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48851558
has body: In the last layer, instead of one output, you should use two outputs: model.add(keras.layers.Dense(2, activation='sigmoid'))
has comment: http://stackoverflow.com/comment/134495453

http://stackoverflow.com/q/48906481
has body: I understand that the below command jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10 would let me set the data rate. But on Colab, I cannot run this command since the notebook is already open. Is there any way I can avoid getting the IOPub error in an active notebook on Colab? I am running keras code and I get this error when I train my neural network. I really need to see the output since it lets me know how many epochs have been completed and the accuracy.
possible better answer: http://stackoverflow.com/a/68402701
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76234240
downvote count: 0
score: 7
type: Question
has title: IOPub Error on Google Colaboratory in Jupyter Notebook
accepted answer: http://stackoverflow.com/a/49023380
has answer: http://stackoverflow.com/a/68402701
tagged with: google-colaboratory
answer count: 3
has answer: http://stackoverflow.com/a/49023380
upvote count: 7
tagged with: keras
tagged with: jupyter-notebook
favorite count: 0

http://stackoverflow.com/comment/84615606
score: 0
has text: text type. session.execute(""" CREATE TABLE IF NOT EXISTS Model ( ModelId text PRIMARY KEY, data text)""")
type: Comment
comment on: http://stackoverflow.com/q/48806085
type: QuestionComment

http://stackoverflow.com/comment/84722023
comment on: http://stackoverflow.com/q/48859312
has text: Try first uninstalling, `pip uninstall selenium`, and then reinstall.
type: Comment
score: 0
type: QuestionComment

http://stackoverflow.com/a/48887727
answers question: http://stackoverflow.com/q/48887674
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84780366
upvote count: 2
has body: First, you need to reverse your dictionary and then use re.findall to search for each word in the string: import re d = {0:'this', 1:'is', 2:'a', 3:'sentence', 4:'another'} new_dict = {b:a for a, b in d.items()} sentence = 'this is a sentence. this is another' final_words = [new_dict[i] for i in re.findall('[a-zA-Z]+', sentence)] Output: [0, 1, 2, 3, 0, 1, 4] Also, dict is a builtin function and when used to store a variable, will have its original functionality overwritten. Thus, it is best to not use the names of the builtin functions to avoid shadowing.
has comment: http://stackoverflow.com/comment/84780303
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48887674
type: Answer

http://stackoverflow.com/a/48912321
answers question: http://stackoverflow.com/q/48911576
accepted answer of: http://stackoverflow.com/q/48911576
has body: Using self object you are attaching those variable with the class object, where it can accessible throughout the class. If self is omitted then the scope of those variable in only inside the size function.
type: AcceptedAnswer
score: 0
type: Answer

http://stackoverflow.com/a/48867937
downvote count: 0
answers question: http://stackoverflow.com/q/48867800
has body: ttk.treeview.focus() returns the current focus item. That means the item that was last selected. The function you are looking for is ttk.treeview.selection(). This returns a tuple of the selected items.
score: 10
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/84740703

http://stackoverflow.com/comment/84697373
type: QuestionComment
comment on: http://stackoverflow.com/q/48846517
has text: Images come in all sorts of formats, e.g. JPEG, PNG etc. You seem to be talking about some sort of 16-bit monochromatic bitmap. But in which format is it? Windows bitmap perhaps? I'm sure there is a specification of the format somewhere which has the answers you are looking for.
score: 0
type: Comment

http://stackoverflow.com/comment/84635863
comment on: http://stackoverflow.com/a/48815258
score: 0
type: AnswerComment
type: Comment
has text: i only used python to convert floats to integer - and my answer is just a standpoint how to solve. other than this, i think, representation of p in python and p itself are different things, `print(p)` or `p` outputs 1e-06, on shell, but 1/p is still 10^6 and when we multiply with another number, it still acts as we expect.

http://stackoverflow.com/comment/84836313
comment on: http://stackoverflow.com/q/48914705
has text: @Leo65 to use `re.sub` you would need `re.sub(r"\\\|"," ", line)`, note, I'm *escaping* **both** the backslash to get an acual backslash, i.e. \\-> \ as well as the pipe, because the pipe is also an alternation operator in regex: `\|` -> `|`. However, what you **really** should use is simply `line.replace('\|',' ')` as others have pointed out
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/a/48890422
upvote count: 5
score: 5
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48890397
has body: You need to call str.replace() with maxreplace parameter. For just replacing the first character in the string, you need to pass maxreplace as 1. For example: >>> s = "Python is programming language" >>> s.replace('n', 'o', 1) 'Pythoo is programming language' # ^ Here first "n" is replaced with "o" From the str.replace document: string.replace(s, old, new[, maxreplace]) Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

flask
tags question: http://stackoverflow.com/q/48832639
tags question: http://stackoverflow.com/q/48938945
tags question: http://stackoverflow.com/q/48877298
tags question: http://stackoverflow.com/q/48901319
tags question: http://stackoverflow.com/q/48941101
tags question: http://stackoverflow.com/q/48936687
tags question: http://stackoverflow.com/q/48822760
tags question: http://stackoverflow.com/q/48903395
tags question: http://stackoverflow.com/q/48932404
tags question: http://stackoverflow.com/q/48927600
tags question: http://stackoverflow.com/q/48869903
tags question: http://stackoverflow.com/q/48817093
tags question: http://stackoverflow.com/q/48876711
tags question: http://stackoverflow.com/q/48904160
tags question: http://stackoverflow.com/q/48851170
tags question: http://stackoverflow.com/q/48936139
tags question: http://stackoverflow.com/q/48891681
tags question: http://stackoverflow.com/q/48946442
tags question: http://stackoverflow.com/q/48912133
tags question: http://stackoverflow.com/q/48888661
tags question: http://stackoverflow.com/q/48811095
tags question: http://stackoverflow.com/q/48909280
tags question: http://stackoverflow.com/q/48837063
tags question: http://stackoverflow.com/q/48917869
tags question: http://stackoverflow.com/q/48896993
tags question: http://stackoverflow.com/q/48891610
tags question: http://stackoverflow.com/q/48865453
tags question: http://stackoverflow.com/q/48954319
tags question: http://stackoverflow.com/q/48867212
tags question: http://stackoverflow.com/q/48942256
tags question: http://stackoverflow.com/q/48958072
tags question: http://stackoverflow.com/q/48936322
tags question: http://stackoverflow.com/q/48934578
tags question: http://stackoverflow.com/q/48818833
tags question: http://stackoverflow.com/q/48900149
tags question: http://stackoverflow.com/q/48963018
tags question: http://stackoverflow.com/q/48954128
tags question: http://stackoverflow.com/q/48858449
tags question: http://stackoverflow.com/q/48836493
tags question: http://stackoverflow.com/q/48890955
tags question: http://stackoverflow.com/q/48889965
tags question: http://stackoverflow.com/q/48936003
tags question: http://stackoverflow.com/q/48820336
tags question: http://stackoverflow.com/q/48963178
tags question: http://stackoverflow.com/q/48827166
tags question: http://stackoverflow.com/q/48892343
tags question: http://stackoverflow.com/q/48817723
tags question: http://stackoverflow.com/q/48940519
tags question: http://stackoverflow.com/q/48832112
type: Tag
tags question: http://stackoverflow.com/q/48811905
tags question: http://stackoverflow.com/q/48873242
tags question: http://stackoverflow.com/q/48825775
tags question: http://stackoverflow.com/q/48818824
tags question: http://stackoverflow.com/q/48825957
tags question: http://stackoverflow.com/q/48951285
tags question: http://stackoverflow.com/q/48831482
tags question: http://stackoverflow.com/q/48923230
tags question: http://stackoverflow.com/q/48912526
tags question: http://stackoverflow.com/q/48861286
tags question: http://stackoverflow.com/q/48874432
tags question: http://stackoverflow.com/q/48897310
tags question: http://stackoverflow.com/q/48833443
tags question: http://stackoverflow.com/q/48936843
tags question: http://stackoverflow.com/q/48826680
tags question: http://stackoverflow.com/q/48948840
tags question: http://stackoverflow.com/q/48893546
tags question: http://stackoverflow.com/q/48942721
tags question: http://stackoverflow.com/q/48963348
tags question: http://stackoverflow.com/q/48817898
tags question: http://stackoverflow.com/q/48956909
tags question: http://stackoverflow.com/q/48819513
tags question: http://stackoverflow.com/q/48846288
tags question: http://stackoverflow.com/q/48948876
tags question: http://stackoverflow.com/q/48875781
tags question: http://stackoverflow.com/q/48853088
tags question: http://stackoverflow.com/q/48917056
tags question: http://stackoverflow.com/q/48860223
tags question: http://stackoverflow.com/q/48836082
tags question: http://stackoverflow.com/q/48902795

http://stackoverflow.com/q/48830763
tagged with: python
has title: Full/Infinite Set in Python
has comment: http://stackoverflow.com/comment/84665621
type: AnsweredQuestion
downvote count: 2
type: Question
accepted answer: http://stackoverflow.com/a/48830848
upvote count: 4
has comment: http://stackoverflow.com/comment/84672877
score: 2
has comment: http://stackoverflow.com/comment/84672954
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48830848
has body: i really can't found anything about this, the idea is this, the intersection of any alement with it returns the element: val == val &amp; InfiniteFullSet True The Full/Infinite set the idea is "simulate" all elements. And a note, the set can contain anything, can be a set of tuples, or Ints, etc. If python don't have any set to to this, how can i do something like this?

http://stackoverflow.com/q/48901854
linked to: http://stackoverflow.com/q/29260686
has body: I'm wondering if it is possible by clicking and dragging a Tab to open a new window with what was in that Tab. If it's possible, I would like to also do the reverse: dragging the new window inside the Tabs (where it was in the first place). I don't know how should I start. I read in some forums that all must be coded but I don't know if Qt allows some facilities to do that? Here a code as a starting point: from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys class SurfViewer(QMainWindow): def __init__(self, parent=None): super(SurfViewer, self).__init__() self.parent = parent self.centralTabs= QTabWidget() self.setCentralWidget(self.centralTabs) self.setFixedWidth(200) self.setFixedHeight(200) #tab 1 self.tab_1 = QWidget() self.centralTabs.addTab(self.tab_1,"Label") vbox = QVBoxLayout() Label = QLabel('Tab1') Label.setFixedWidth(180) LineEdit = QLineEdit('Tab1') LineEdit.setFixedWidth(180) vbox.addWidget(Label) vbox.addWidget(LineEdit) vbox.setAlignment(Qt.AlignTop) self.tab_1.setLayout(vbox) #tab 2 self.tab_2 = QWidget() self.centralTabs.addTab(self.tab_2,"Label") vbox = QVBoxLayout() Label = QLabel('Tab2') Label.setFixedWidth(180) LineEdit = QLineEdit('Tab2') LineEdit.setFixedWidth(180) vbox.addWidget(Label) vbox.addWidget(LineEdit) vbox.setAlignment(Qt.AlignTop) self.tab_2.setLayout(vbox) if __name__ == '__main__': app = QApplication(sys.argv) ex = SurfViewer(app) ex.setWindowTitle('window') ex.show() sys.exit(app.exec_( )) This is far from my Qt level, so I'm asking some help. If I well understood, I need to reimplement the mousePressEvent() and the dragMoveEvent() of the QTabWidget? Their is this topic: In PyQt4, is it possible to detach tabs from a QTabWidget? but it is with PYQT4 and I'm using PYQT5. update So, according to In PyQt4, is it possible to detach tabs from a QTabWidget? and after conversion toward pyqt5 from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import sys class Detac…
tagged with: pyqt
tagged with: window
linked to: http://stackoverflow.com/q/47267195
answer count: 3
has answer: http://stackoverflow.com/a/48902281
possible better answer: http://stackoverflow.com/a/72962082
has answer: http://stackoverflow.com/a/72962082
tagged with: tabs
accepted answer: http://stackoverflow.com/a/48902281
score: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/76563663
has title: Is it possible to drag a QTabWidget and open a new window containing what's in this Tab in pyqt5?
type: Question

http://stackoverflow.com/comment/84829939
has text: It still doesn't work... manage.py makemessages -l es. CommandError: Can't find msguniq. Make sure you have GNU gettext tools 0.15 or newer installed.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48911452

http://stackoverflow.com/comment/84848598
type: AnswerComment
type: Comment
score: 0
has text: This is a great answer! Thanks Daniel (I work at Twilio). I'd add one other thing, calling `client.sms.messages.create` uses an old and deprecated API. I would update to just `client.messages.create` and you might get better results.
comment on: http://stackoverflow.com/a/48865259

http://stackoverflow.com/q/48888271
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
tagged with: docker
has comment: http://stackoverflow.com/comment/95949674
downvote count: 0
answer count: 1
favorite count: 0
has body: I am having a docker container with an Autoencoder that can be started via a Flask-Server. All the scripts are copied into the /root of the Docker and it also gains access to the shared volume /data which looks like this: /data -/images -/models --/Autoenc.exe.ckpt.data-00000-of-00001 --/Autoenc.exe.ckpt.index --/Autoenc.exe.ckpt.meta --/checkpoint and /root -MyServer.py The server can successfully write images into the /data/images folder, but fails to write into the /data/models directory. I instantiated the tensorflow Saver like this: saver = tf.train.Saver() and tried each of the following ways of writing the save-file saver.save(sess, '/data/models/Autoenc.exe.ckpt') saver.save(sess, '../data/models/Autoenc.exe.ckpt') Fun fact: it works without errors, when I do this saver.save(sess, './Autoenc.exe.ckpt') but this would write the file to the wrong spot, where it would be deleted on rebuilding the docker container. When building the docker container and already serving the checkpoints in the mentioned directory, a restore via saver.restore(sess, "../data/models/Autoenc.exe.ckpt") works without any issues.. No let me show you the error message: 2018-02-20 15:00:52.868566: W tensorflow/core/framework/op_kernel.cc:1198] Unknown: ../data/models/Autoenc.exe.ckpt.data-00000-of-00001.tempstate17405837231896083449; Input/output error 2018-02-20 15:00:53.339357: W tensorflow/core/kernels/queue_base.cc:277] _0_input_producer: Skipping cancelled enqueue attempt with queue not closed [2018-02-20 15:00:53,590] ERROR in app: Exception on /train/ [POST] Traceback (most recent call last): File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1350, in _do_call return fn(*args) File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1329, in _run_fn status, run_metadata) File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 473, in __exit__ c_api.TF_GetCode(self.status.statu…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48898160
has title: Tensorflow Saver.save can't write to docker shared volume
tagged with: autoencoder

http://stackoverflow.com/a/48929549
answers question: http://stackoverflow.com/q/48928973
downvote count: 3
score: 5
has comment: http://stackoverflow.com/comment/130236415
has body: I think, generateDS is the solution to your problem. Starting from chapter 5, the command python generateDS.py -o people.py -s peoplesubs.py people.xsd reads the XSD file and creates several classes and subclasses. It generates many data structures and getters and setters for accessing and using data :) If there is any XML file that complies with that XSD, it can be read straight away by using import people rootObject = people.parse('people.xml') within the code. More information is given in chapter 12. The aforementioned classes also provide methods to export data as an XML format. The level of documentation is good and it is highly suggested to use this for any future project.
type: Answer
has comment: http://stackoverflow.com/comment/92458958
upvote count: 8

http://stackoverflow.com/comment/84634758
type: Comment
has text: Not really true what you say about `groupby`... with an appropriate key, you *don't* get separate groups you need to combine: https://eval.in/957101
comment on: http://stackoverflow.com/a/48814637
type: AnswerComment
score: 1

http://stackoverflow.com/q/48853311
has title: How to find missing combinations/sequences in a 2D array with finite element values
has comment: http://stackoverflow.com/comment/84710175
upvote count: 2
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48862172
has comment: http://stackoverflow.com/comment/84710310
downvote count: 1
tagged with: arrays
favorite count: 0
has answer: http://stackoverflow.com/a/48862172
answer count: 5
has comment: http://stackoverflow.com/comment/84756071
has answer: http://stackoverflow.com/a/48854050
tagged with: python
has comment: http://stackoverflow.com/comment/84710074
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48854050
score: 1
has body: In the case of the set np.array([1, 2, 3]), there are only 9 possible combinations/sequences of its constituent elements: [1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 1], [3, 2], [3, 3]. If we have the following array: np.array([1, 1], [1, 2], [1, 3], [2, 2], [2, 3], [3, 1], [3, 2]) What is the best way, with NumPy/SciPy, to determine that [2, 1] and [3, 3] are missing? Put another way, how do we find the inverse list of sequences (when we know all of the possible element values)? Manually doing this with a couple of for loops is easy to figure out, but that would negate whatever speed gains we get from using NumPy over native Python (especially with larger datasets).
has answer: http://stackoverflow.com/a/48854141
linked to: http://stackoverflow.com/q/16970982
tagged with: scipy
type: Question
tagged with: combinations
has answer: http://stackoverflow.com/a/48855537
has answer: http://stackoverflow.com/a/48862544

http://stackoverflow.com/a/48922336
has comment: http://stackoverflow.com/comment/84851406
has body: tight_layout() is just a useful tool for most common plots, but it cannot deal with every situation. In your particular case, I think you are better off calling tight_layout() before creating your inset axes, and using the resulting axes position to find the correct coordinates for your insets import matplotlib.pyplot as plt import numpy as np import os import shutil import time import sys #Simplest working example of tight_layout and plots problem def two_scales(ax1, time, data1, data2, c1, c2, xlabel, y1label, y2label): ax2 = ax1.twinx() ax1.plot(time, data1, color=c1) ax1.set_xlabel(xlabel) ax1.set_ylabel(y1label) ax2.plot(time, data2, color=c2) ax2.set_ylabel(y2label) return ax1, ax2 # Change color of each axis def color_y_axis(ax, color): """Color your axes.""" for t in ax.get_yticklabels(): t.set_color(color) return None def insetPlots(): t = np.arange(0.01, 10.0, 0.01) #Figure stuff fig, baseAxes = plt.subplots(2,2,figsize=(10, 6)) baseAxesFlattened = baseAxes.flatten() for i, ax in enumerate(baseAxesFlattened): s1 = np.exp((i+1)*t) s2 = .3*np.sin((i+1)*.2 * np.pi * t) #Plotting them together tempAx1, tempAx2 = two_scales(ax, t, s1, s2, 'b', 'r','heyheyhey','yayaya','woopwoop') #Changing the color of the axes color_y_axis(tempAx1, 'b') color_y_axis(tempAx2, 'r') fig.tight_layout() for i, ax in enumerate(baseAxesFlattened): pos = ax.get_position() #print(pos) mainPlotW = pos.x1 - pos.x0 mainPlotH = pos.y1 - pos.y0 w, h = 0.3*mainPlotW, 0.25*mainPlotH left, bottom, width, height = [pos.x0 + .15*mainPlotW, pos.y0 + .7*mainPlotH, w, h] insetAx = fig.add_axes([left, bottom, width, height]) insetAx.plot(range(6)[::-1], color='green') s3 = np.sin(.2 * np.pi * t/(i+1)) insetAx.plot(t,s3, color='green') insetPlots() PS You're doing some pretty weird things with the pos variable, transforming it to str before casting it back to float. I've simplified your code in the second loop in my code
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48922150
score: 1
downvote count: 0

http://stackoverflow.com/a/48897451
downvote count: 0
has comment: http://stackoverflow.com/comment/84801334
has comment: http://stackoverflow.com/comment/84801000
type: Answer
score: 3
has body: try this: index = pd.date_range("2000/01/01", "2016/01/01") s = index.to_series() s[(s.dt.month * 100 + s.dt.day).between(415, 615)]
answers question: http://stackoverflow.com/q/48897329
has comment: http://stackoverflow.com/comment/84800968
upvote count: 3

http://stackoverflow.com/q/48940859
has comment: http://stackoverflow.com/comment/84888794
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48940944
has answer: http://stackoverflow.com/a/48940969
type: Question
linked to: http://stackoverflow.com/q/1132941
score: 0
possible better answer: http://stackoverflow.com/a/48941149
answer count: 3
has comment: http://stackoverflow.com/comment/84888839
accepted answer: http://stackoverflow.com/a/48940969
has answer: http://stackoverflow.com/a/48941149
has body: The idea behind this is, simply said, I want to have: def test (a,b): a += b return a &gt;&gt;&gt;test(0,1) &gt;&gt;&gt;1 So it records that a = 1, and saves it as its new parameter for a. So if I return to this function again and run it again, the result should be 2. Also I was wondering, is there any way to check the contents of a parameter? Apologies about noob questions, I'm literally just starting to learn python. Thank you!
has comment: http://stackoverflow.com/comment/84888790
tagged with: python
has title: How do I update function parameters based on input in python?

http://stackoverflow.com/comment/84788113
comment on: http://stackoverflow.com/q/48875474
score: 0
type: QuestionComment
has text: Sorry for not being clear... I trying to find a way to update the list below: backups = [ (200,"WIN_7", "active", 4096, 320, 1), (201,"WIN_7_sp1", "active", 4096, 320, 2), (210,"WIN_Java", "inactive", 8019, 8), (230,"Linux_C78", "active", 4096, 90), (241,"Linux2_B78", "active", 4096, 80) ] because everytime the 'listbk' runs the radiobutton should be updated. Because the backup list changes from system to system. Thank you for your quick prompts.
type: Comment

http://stackoverflow.com/q/48808277
has title: SQL error with sqlite in python
has comment: http://stackoverflow.com/comment/84619826
upvote count: 1
has answer: http://stackoverflow.com/a/48808715
has comment: http://stackoverflow.com/comment/84619840
type: Question
has comment: http://stackoverflow.com/comment/84619799
has body: i have a hopefully simple Problem with an SQL-command Code: c.execute("SELECT MAX(pic_num) FROM Pictures WHERE id = "+str(user_id)) pic_num is a column in the database and user_id is an Integer in the database I thought everything would be right but i get this Error: sqlite3.OperationalError: near ")": syntax error this Information doesn't help me at all
has comment: http://stackoverflow.com/comment/84619745
has comment: http://stackoverflow.com/comment/84620041
has answer: http://stackoverflow.com/a/48808512
answer count: 3
has comment: http://stackoverflow.com/comment/84620145
tagged with: sql
tagged with: sqlite
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48808514
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84619773
has comment: http://stackoverflow.com/comment/84619771
score: 1

http://stackoverflow.com/comment/84703538
comment on: http://stackoverflow.com/a/48842793
score: 0
type: AnswerComment
has text: Yup; just emphasizing that some ideas that could come up from reading this are particularly bad.
type: Comment

google-cloud-pubsub
tags question: http://stackoverflow.com/q/48910477
type: Tag
tags question: http://stackoverflow.com/q/48834419
tag name: google-cloud-pubsub

http://stackoverflow.com/a/48923439
has body: Worked with the following code: # Adding Data Labels for i, label in enumerate(list(industry_split.index.values)): score1 = industry_split.loc[label]['Retail'] if score1 == 0: None else: ax.annotate(str(score1), (i, score1 - 0.7), color='white', fontsize=12, weight='semibold') score2 = industry_split.loc[label]['Services'] if score2 == 0: None else: ax.annotate(str(score2), (i, score1 + score2 - 0.7), color='white', fontsize=12, weight='semibold') score3 = industry_split.loc[label]['Manufacturing'] if score3 == 0: None else: ax.annotate(str(score3), (i, score1 + score2 + score3 - 0.7), color='white', fontsize=12, weight='semibold') score4 = industry_split.loc[label]['Distribution'] if score4 == 0: None else: ax.annotate(str(score4), (i, score1 + score2 + score3 + score4 - 0.7), color='white', fontsize=12, weight='semibold')
has comment: http://stackoverflow.com/comment/84858239
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48922328
answers question: http://stackoverflow.com/q/48922328
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48846564
type: Answer
has body: An arguably more robust way of doing this if you wanted to limit your character set is to read in a file object with the encoding that you want while ignoring errors with open('your_csv_file.csv', encoding='ascii', errors='ignore') as infile: df = pd.read_csv(infile)
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48842639

http://stackoverflow.com/q/48915146
has comment: http://stackoverflow.com/comment/84851633
has title: Time passed to celery beat schedule from model object
has comment: http://stackoverflow.com/comment/84880248
downvote count: 0
tagged with: scheduled-tasks
favorite count: 0
tagged with: model
has comment: http://stackoverflow.com/comment/84962247
has comment: http://stackoverflow.com/comment/84920730
type: UnansweredQuestion
tagged with: django
has body: I wonder how can I pass the time from the model object to the celery beat schedule in settings.py? Do I need to import the model in settings.py and iterate over all objects? model.py class Note(models.Model): user = models.ForeignKey(User, related_name='notes') status = models.TextField(max_length=500) publish_time = models.DateTimeField() is_publish = models.BooleanField(default=False) Task in my app: @task() def task_number_one(): // do something return something celery part in settings.py CELERY_BROKER_URL = 'amqp://localhost' from celery.schedules import crontab CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'noteapp.tasks.task_number_one', 'schedule': '', # crontab(minute=put here min from model, hour=put here hour from model), }, }
tagged with: python
has comment: http://stackoverflow.com/comment/84951264
answer count: 0
score: 1
upvote count: 1
tagged with: celery
type: Question
has comment: http://stackoverflow.com/comment/85042583
has comment: http://stackoverflow.com/comment/84839851
has comment: http://stackoverflow.com/comment/84932290
has comment: http://stackoverflow.com/comment/84997272

http://stackoverflow.com/a/48900146
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48899924
type: Answer
upvote count: 2
has body: Pyomo's (LP file-based) CPLEX interface passes options using CPLEX's "Interactive" API. In this case, the interactive version of that option is "mip limits solutions": from pyomo.environ import * opt = SolverFactory("cplex") opt.options['mip limits solutions'] = 1

android
tags question: http://stackoverflow.com/q/48882128
tags question: http://stackoverflow.com/q/48820940
tags question: http://stackoverflow.com/q/48949726
tag name: android
type: Tag

http://stackoverflow.com/comment/84711948
type: AnswerComment
type: Comment
has text: You don't have to call `.save` explicitly. We're overriding default behaviour to add our custom logic. The method is defined (overriding the default method) under the model class.
comment on: http://stackoverflow.com/a/48852883
score: 0

http://stackoverflow.com/q/48876798
upvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48876937
has comment: http://stackoverflow.com/comment/84781986
has body: I have a RDD that has data that looks like this: [‘ID: &lt;166.1079&gt;\nDate: 7 Dec 2010 16:06:42\nOwner: Mary Jones\nLab-Techs: Bob Chandra\nHarry Alley\n Julie Stevens\nNotes: West Position\nTemp: 1.0 C\nX-FileName: temp-g\nX-Storage: 3544-ABC X-Location: Building-A’] It's a lab record, a text file. I have this python code that is not working correctly. It is not splitting the fields properly and then taking each field and placing them in their respected RDDs. Here is the code: lab_data = sc.textFile('data_file') fields = lab_data.map(lambda x: x.split('Notes:')(0).split('\n') ID_field = fields(0).map(lambda x: x.split(':')(1).trim()) date_field = fields(1).map(lambda x: x.split(':')(1).trim()) owner_field = fields(2).map(lambda x: x.split(':')(1).trim()) Basically, I tried to grab the top 3 fields like ID, Date and Owner, but leave out all other fields. So, the field RDDs would have values like: ID field = &lt;166.1079&gt; Date field = 7 Dec 2010 16:06:42 Owner field = Marry Jones Can you help me correct the code?
tagged with: python
has comment: http://stackoverflow.com/comment/84757756
has title: How to use map and split to parse a text file with python?
downvote count: 2
has comment: http://stackoverflow.com/comment/84789102
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48876937
score: -2
tagged with: pyspark

http://stackoverflow.com/comment/107481830
comment on: http://stackoverflow.com/a/48829798
type: Comment
score: 1
type: AnswerComment
has text: This is incorrect. After `readlines()` the file cursor is at the end of the file, so all writes append to the end, thus the final file will have _more_ lines than it originally had. Also, `startwith()` should be `startswith()`.

http://stackoverflow.com/a/48841129
has body: For you ref:- cr = 0 for i in datacenters: for m in numberofVNFs: value = cm * qm cr +=value print (cr) return
score: 0
answers question: http://stackoverflow.com/q/48840881
type: Answer

http://stackoverflow.com/q/48886494
favorite count: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/84777779
tagged with: serial-port
tagged with: python
has title: Serial USB device with Windows drivers. Want to use it with linux
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48892239
score: 1
has body: I have a GPS unit I can connect with USB, which is said by the manufacturer to be used with Windows. It has a CD with some drivers. Something about USB to Serial PL2303. But I need to be able to use it with linux and python. How can I go on about trying to achieve this? Is it a lost cause when I have no documentation from manufacturer about which registers to read and such? When I connect it is being recognized in dmesg, it gets a name /dev/ttyUSB1 What is the next step in trying to get this to work?
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48892239
has comment: http://stackoverflow.com/comment/84777906
has comment: http://stackoverflow.com/comment/84777982
has comment: http://stackoverflow.com/comment/84781479
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/84846581
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48919652
type: Comment
has text: can you explain for what is the attributes limit=1?

http://stackoverflow.com/q/48814480
has comment: http://stackoverflow.com/comment/84633052
has comment: http://stackoverflow.com/comment/84632952
has comment: http://stackoverflow.com/comment/84633183
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84632787
type: Question
has answer: http://stackoverflow.com/a/48814644
has title: Python to .exe --> no module named numpy
answer count: 1
has comment: http://stackoverflow.com/comment/84632872
has body: as understandable from the title, I converted a .py into .exe using pyinstaller, now that I am trying running it it tells me: Traceback (most recent call last): File "PredictiveDemand_Final_V2.0.3_SQL.py", line 1, in &lt;module&gt; import numpy as np ModuleNotFoundError: No module named 'numpy' Needless to say I import numpy in my code. Before importing numpy I also import pandas but that does not seem to be a problem. Thanks
score: 0

http://stackoverflow.com/a/48896459
accepted answer of: http://stackoverflow.com/q/48891791
type: Answer
answers question: http://stackoverflow.com/q/48891791
has body: I would suggest you read some material on how import works in python here. to get what you have working properly quickly, you should not import Main in your login function. Try passing the driver as an argument in your login function as so (Note: after passing the browser as an argument and not importing Main, you will no longer need to use Main.browser, just browser): from time import sleep def login(browser): browser.get('https://www.instagram.com') Then when you go to call login from your main, you will want to pass browser as an argument: Login.login(browser) This should fix the problem you were having with two browsers opening. If the issue is still occurring with the Log in link not found please read this and ask a new question if you have a clear understanding of how it works and require more help.
type: AcceptedAnswer
score: 0

http://stackoverflow.com/comment/84781741
score: 1
type: AnswerComment
has text: You're welcome! :-) you can pass params which you would've passed to figure, so use `figsize=(20,20)` or similar if you want that bigger.
type: Comment
comment on: http://stackoverflow.com/a/48887311

http://stackoverflow.com/comment/84911366
has text: Something seems wrong with the formatting. Could you fix it?
comment on: http://stackoverflow.com/q/48952228
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/123963645
has text: @joaquin please ask a new question and include your code, hopefully you’ll get an answer
comment on: http://stackoverflow.com/a/48901893
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84747736
score: 2
has text: After a few hours of messing around it was a pretty simple mistake. My tasks were configured as `ignore_result=True` making they `AsyncResult` instance never update its `.state` attribute
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48827412

http://stackoverflow.com/comment/84636734
comment on: http://stackoverflow.com/q/48810018
score: 0
type: QuestionComment
has text: Thank you so much, that explains a lot.
type: Comment

http://stackoverflow.com/q/48914851
type: Question
type: AnsweredQuestion
has title: Python Regular Expression for Gene Name Extraction
has comment: http://stackoverflow.com/comment/84836088
has body: I have a text file: Chr1 0 100 gene49 Gnomon gene ID=gene49;Name=LOC101947233;Dbxref=GeneID:101947233;gbkey=Gene;gene=LOC444342;part=1%2F1 I am trying to extract only the gene name from each line (so I want to extract gene=LOC444342, and that's it.) I've been using the following regular expression: gene=.*; However, it keeps extracting the following: gene=LOC444342;part=1%2F1 Obviously I dont want anything after the ;. Any help?
has comment: http://stackoverflow.com/comment/84836576
answer count: 2
possible better answer: http://stackoverflow.com/a/48914890
has answer: http://stackoverflow.com/a/48914890
favorite count: 0
has answer: http://stackoverflow.com/a/48914914
score: 0
tagged with: python
tagged with: regex
upvote count: 1
accepted answer: http://stackoverflow.com/a/48914914
downvote count: 1

http://stackoverflow.com/comment/84895114
has text: How exactly *is* the expression parsed without parentheses? If I run `1 in (range(2) == True)`, it throws `TypeError: argument of type 'bool' is not iterable`.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48944298
type: AnswerComment

http://stackoverflow.com/q/48812506
answer count: 1
has comment: http://stackoverflow.com/comment/84628623
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84628927
tagged with: python
has comment: http://stackoverflow.com/comment/84628843
has comment: http://stackoverflow.com/comment/84628596
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84629796
has comment: http://stackoverflow.com/comment/84629561
has comment: http://stackoverflow.com/comment/84628567
type: Question
has comment: http://stackoverflow.com/comment/84629426
has title: convert list of strings to dictionary python
has comment: http://stackoverflow.com/comment/84628883
has comment: http://stackoverflow.com/comment/84628681
upvote count: 2
score: 0
has comment: http://stackoverflow.com/comment/84629895
downvote count: 2
has body: Is it possible to convert a string representation of a dictionary where the keys aren't encapsulated in double quotes e.g. '{output:{OUTPUT_PATH:hdfs://x.x.x.x:X/tmp/x/x,OUTPUT_TYPE:hdfs},''input:{INPUT_TEMPTABLE:sample,INPUT_TYPE:hdfs,INPUT_PATH:hdfs://x.x.x.x:X/sparkStream/sample1/},''process:{query.param:${http.query.param.name},PROCESS_SQL:1,PROCESS_TYPE:sql},''attributes:{path:./,restlistener.remote.source.host:127.0.0.1,filename:1211999192960535,restlistener.remote.user.dn:none,uuid:2b025f49-7d53-49db-8063-24ddda29fc4a}}' into a dictionary like: {"output":{"OUTPUT_PATH":"hdfs://x.x.x.x:X/tmp/x/x","OUTPUT_TYPE":"hdfs"},"input":{"INPUT_TEMPTABLE":"sample","INPUT_TYPE":"hdfs","INPUT_PATH":"hdfs://x.x.x.x:X/sparkStream/sample1/"},"process":{"query.param":"${http.query.param.name}","PROCESS_SQL":"1","PROCESS_TYPE":"sql"},"attributes":{"path":"./","restlistener.remote.source.host":"127.0.0.1","filename":"1211999192960535","restlistener.remote.user.dn":"none","uuid":"2b025f49-7d53-49db-8063-24ddda29fc4a"}} The data can't be pickled or converted into a serialized format like JSON because it is coming from another process in the current format.
has answer: http://stackoverflow.com/a/48813862
accepted answer: http://stackoverflow.com/a/48813862
has comment: http://stackoverflow.com/comment/84629625
has comment: http://stackoverflow.com/comment/84628665

http://stackoverflow.com/q/48869185
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48869397
type: AnsweredQuestion
has title: Creating a DataFrame from list of Series
tagged with: dataframe
type: Question
tagged with: pandas
has body: I have below list of series: import pandas as pd my_series_a = pd.Series([1,2,2,4,5], name='Group_A') my_series_b = pd.Series([50,50,70], name='Group_B') my_series_c = pd.Series([333,222,111,111], name='Group_C') my_list = [my_series_a, my_series_b, my_series_c] I need to create a DataFrame with 2 columns [Group, Sub-Group]: Group: Name of the Series Sub-Group: Unique values from each Series Result should be: Group Sub-Group Group_A 1 Group_A 2 Group_A 4 Group_A 5 Group_B 50 Group_B 70 Group_C 333 Group_C 222 Group_C 111
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48869397
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/comment/84817100
comment on: http://stackoverflow.com/q/48893589
has text: My company is G Suite, so everything is hosted in my corporate Google Drive.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84697004
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48846457
type: Comment
has text: `not all(...)` instead of `not any(...)`.

http://stackoverflow.com/comment/84621923
has text: I edited it. Thanks for the help!
comment on: http://stackoverflow.com/q/48808912
score: 0
type: QuestionComment
type: Comment

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

http://stackoverflow.com/a/48824079
score: 1
answers question: http://stackoverflow.com/q/48823986
type: Answer
upvote count: 1
has body: Use set_index with unstack: df1 = df.set_index('column1', append=True).unstack() print (df1) v1 v2 column1 'a' 'b' 'c' 'a' 'b' 'c' ind1 1.0 2.0 NaN 3.0 4.0 NaN ind2 3.0 4.0 NaN 5.0 6.0 NaN indN NaN NaN 5.0 NaN NaN 7.0 Then in dict comprehension select by first level of MultiIndex by xs: output = {x:df1.xs(x, axis=1) for x in df1.columns.levels[0]} print (output) {'v2': column1 'a' 'b' 'c' ind1 3.0 4.0 NaN ind2 5.0 6.0 NaN indN NaN NaN 7.0, 'v1': column1 'a' 'b' 'c' ind1 1.0 2.0 NaN ind2 3.0 4.0 NaN indN NaN NaN 5.0} print (output['v1']) column1 'a' 'b' 'c' ind1 1.0 2.0 NaN ind2 3.0 4.0 NaN indN NaN NaN 5.0 But also is possible generate output from df1 by xs without comprehension: print (df1.xs('v1', axis=1)) column1 'a' 'b' 'c' ind1 1.0 2.0 NaN ind2 3.0 4.0 NaN indN NaN NaN 5.0 Similar solution: df1 = df.set_index('column1', append=True) print (df1) v1 v2 column1 ind1 'a' 1 3 'b' 2 4 ind2 'a' 3 5 'b' 4 6 indN 'c' 5 7 output = {x:df1.unstack().xs(x, axis=1) for x in df1.columns} print (output) {'v2': column1 'a' 'b' 'c' ind1 3.0 4.0 NaN ind2 5.0 6.0 NaN indN NaN NaN 7.0, 'v1': column1 'a' 'b' 'c' ind1 1.0 2.0 NaN ind2 3.0 4.0 NaN indN NaN NaN 5.0} print (output['v1']) column1 'a' 'b' 'c' ind1 1.0 2.0 NaN ind2 3.0 4.0 NaN indN NaN NaN 5.0
accepted answer of: http://stackoverflow.com/q/48823986
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84746107
type: QuestionComment
has text: Please [edit] the code in your question and [create a minimal, complete, and verifiable example](https://stackoverflow.com/help/mcve).
comment on: http://stackoverflow.com/q/48870758
score: 0
type: Comment

http://stackoverflow.com/q/48897137
tagged with: importerror
has title: Import Error Symbol not found: __PySlice_AdjustIndices
score: 2
has answer: http://stackoverflow.com/a/48899278
upvote count: 2
tagged with: selenium
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/48267633
accepted answer: http://stackoverflow.com/a/48899278
has body: I am doing some beginner Selenium to automate a task in the browser. I have installed Selenium using pip install selenium and I know it installed successfully because I saw the following message: Successfully installed selenium-3.9.0. Okay so that's clear Selenium is up and working. I want to run this python file: from selenium import webdriver browser = webdriver.Firefox() type(browser) browser.get('http://inventwithpython.com') However, when I run this using the terminal, I get the following error: mustafas-mbp:PlayDivya mustafahoda$ python playDivya.py Traceback (most recent call last): File "playDivya.py", line 4, in &lt;module&gt; from selenium import webdriver File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/__init__.py", line 18, in &lt;module&gt; from .firefox.webdriver import WebDriver as Firefox # noqa File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 22, in &lt;module&gt; import httplib as http_client File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 69, in &lt;module&gt; from array import array ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/array.so, 2): Symbol not found: __PySlice_AdjustIndices Referenced from: /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/array.so Expected in: flat namespace in /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/array.so Any help would be super helpful. This is a very simple script and I have no idea why this is happening! Thanks in advance!
type: Question
linked to: http://stackoverflow.com/q/34386527
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-2.7

http://stackoverflow.com/a/48924316
has comment: http://stackoverflow.com/comment/84855154
has body: &gt;&gt;&gt; a = "ram" &gt;&gt;&gt; filename = 'mani.csv' &gt;&gt;&gt; absolute_path = os.path.join('E:', '4', a, filename) &gt;&gt;&gt; my_list.to_csv(absolute_path)
has comment: http://stackoverflow.com/comment/84854994
type: Answer
answers question: http://stackoverflow.com/q/48924029
score: 0

http://stackoverflow.com/q/48843887
has answer: http://stackoverflow.com/a/62038586
favorite count: 0
tagged with: aggregate
tagged with: python
linked to: http://stackoverflow.com/q/33576932
has title: Passing argument in groupby.agg with multiple functions
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48843971
type: Question
answer count: 2
score: 5
tagged with: group-by
upvote count: 5
downvote count: 0
accepted answer: http://stackoverflow.com/a/48843971
possible better answer: http://stackoverflow.com/a/62038586
has body: Anyone knows how to pass arguments in a groupby.agg() with multiple functions? Bottom line, I would like to use it with a custom function, but I will ask my question using a built-in function needing an argument. Assuming: import pandas as pd import numpy as np import datetime np.random.seed(15) day = datetime.date.today() day_1 = datetime.date.today() - datetime.timedelta(1) day_2 = datetime.date.today() - datetime.timedelta(2) day_3 = datetime.date.today() - datetime.timedelta(3) ticker_date = [('fi', day), ('fi', day_1), ('fi', day_2), ('fi', day_3), ('di', day), ('di', day_1), ('di', day_2), ('di', day_3)] index_df = pd.MultiIndex.from_tuples(ticker_date, names=['lvl_1', 'lvl_2']) df = pd.DataFrame(np.random.rand(8), index_df, ['value']) How would I do this: df.groupby('lvl_1').agg(['min','max','quantile']) with, as argument for 'quantile': q = 0.22
tagged with: pandas

http://stackoverflow.com/comment/84708286
score: 0
type: Comment
type: QuestionComment
has text: @lu.koerfer I changed file extension as a .doc and tried textract, but it returns "it's not a doc file"
comment on: http://stackoverflow.com/q/48851971

http://stackoverflow.com/a/48952229
has comment: http://stackoverflow.com/comment/125209091
type: Answer
answers question: http://stackoverflow.com/q/48951981
has comment: http://stackoverflow.com/comment/84912142
has comment: http://stackoverflow.com/comment/84911481
has comment: http://stackoverflow.com/comment/84912041
score: 20
upvote count: 21
type: AcceptedAnswer
downvote count: 1
has body: Per the doc, the format of your Oracle connection string with SQLAlchemy should be oracle+cx_oracle://user:pass@host:port/dbname[?key=value&amp;key=value...]. But based on your former connection string, the db value might actually be the TNS service name, so in this case, you want to use engine = sqlalchemy.create_engine('oracle+cx_oracle://' + user + ':' + pw + '@' + host + ':' + port + '/?service_name=' + db)
accepted answer of: http://stackoverflow.com/q/48951981
has comment: http://stackoverflow.com/comment/130576724

http://stackoverflow.com/a/62044428
type: Answer
has body: I was searching to do the exact same thing and found this topic which helped me for the first part. Here is how I solved the second part: worksheet.conditional_formatting.add('A1:'+get_column_letter(worksheet.max_column)+str(worksheet.max_row),\ CellIsRule(operator='equal', formula=['"Option 1"'], fill=PatternFill(bgColor="FF0000"))) worksheet.conditional_formatting.add('A1:'+get_column_letter(worksheet.max_column)+str(worksheet.max_row),\ CellIsRule(operator='equal', formula=['"Option 2"'], fill=PatternFill(bgColor="FFFF00"))) worksheet.conditional_formatting.add('A1:'+get_column_letter(worksheet.max_column)+str(worksheet.max_row),\ CellIsRule(operator='equal', formula=['"Option 3"'], fill=PatternFill(bgColor="00FF00"))) (You could adjust the formatting area if you dont need the entire sheet to be conditionnal formatted)
score: 0
answers question: http://stackoverflow.com/q/48824919

http://stackoverflow.com/a/48856572
downvote count: 0
answers question: http://stackoverflow.com/q/48856357
has body: Define a custom form for the page, and add your validation logic in a clean method there: http://docs.wagtail.io/en/v1.13.1/advanced_topics/customisation/page_editing_interface.html#customising-generated-forms
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48856357
type: AcceptedAnswer

http://stackoverflow.com/comment/84804275
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48899389
has text: Hi, thank you for your kind reply. I just tried to make x to "str(x)" and it worked! So I guess the x_label of pygal.Bar() chart should be string, instead of the integer.
score: 0

http://stackoverflow.com/a/48868197
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48868097
type: Answer
has body: I think you need reindex with join or concat: mux = pd.MultiIndex.from_tuples([('rec-1','rec-1-b'),('rec-2','rec-3-b')]) df = df1.reindex(mux, level=0).join(df2.reindex(mux, level=1)) Or: df = pd.concat([df1.reindex(mux, level=0), df2.reindex(mux, level=1)], axis=1) print (df) column test rec-1 rec-1-b foo baz rec-2 rec-3-b bar quux
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48868097
type: AcceptedAnswer

http://stackoverflow.com/q/48833562
has comment: http://stackoverflow.com/comment/84746284
score: 0
has comment: http://stackoverflow.com/comment/84714940
tagged with: curses
answer count: 0
type: UnansweredQuestion
has body: I have a piece of code that uses curses in Python 2.7. What I can understand is that getch() is giving me SIGINT's value as -1. But I want to understand following behaviour in bit more detail: Case #1 Consider this piece of code: myscreen = curses.initscr() def end(sig,frame): myscreen.addstr(1,0,'sigint') c=myscreen.getch() myscreen.addstr(2,0,str(c)) myscreen.getch() curses.endwin() sys.exit(0) signal.signal(signal.SIGINT,end) myscreen.addstr('waiting...') myscreen.getch() curses.endwin() The output I get is: waiting... sigint #This I get after first SIGINT -1 #This I get after second SIGINT After another key press, the program ends. So it took 3 key press. Case #2 Consider this code: myscreen = curses.initscr() myscreen.keypad(1) def end(sig,frame): myscreen.addstr(1,0,'sigint') c=myscreen.getch() myscreen.addstr(2,0,str(c)) myscreen.getch() curses.endwin() sys.exit(0) signal.signal(signal.SIGINT,end) myscreen.addstr('waiting...') myscreen.getch() curses.endwin() Output is: waiting... sigint -1 #This I get after first SIGINT After another key press, program ends. This took only 2 inputs and we had -1 in output right after first SIGINT, which means first getch() in end() automatically got input of -1 (which seems to be SIGINT from case #1) somehow. Can anyone please explain what presence of keypad() function is doing? Is this something related to how escape character is treated with keypad()?
tagged with: python
type: Question
has title: Python curses confusing keypad() SIGINT behaviour

http://stackoverflow.com/q/48886569
has comment: http://stackoverflow.com/comment/84780650
has comment: http://stackoverflow.com/comment/84778010
tagged with: arduino
has comment: http://stackoverflow.com/comment/84780248
answer count: 1
has title: Arduino Maya Pythoncode
has comment: http://stackoverflow.com/comment/84777855
has comment: http://stackoverflow.com/comment/84778022
downvote count: 5
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/606191
upvote count: 0
score: -5
tagged with: maya
has comment: http://stackoverflow.com/comment/84789458
has answer: http://stackoverflow.com/a/48926558
has comment: http://stackoverflow.com/comment/84777943
favorite count: 0
type: Question
has body: Me and my friend is trying to implement an Arduinoboard controller into Maya. We did not write the code ourselves, and we cannot get hold of the person who wrote it. We're not programmers but we know how to read and edit Python code. Our problem is probably really simple, but we can't figure out how to solve it. We have Googled it and read on multiple forums without any luck. Basically we don't have knowledge enough to know how other peoples problems/solutions would be applicable to our specific code. Error message: This is the code: import socket import serial import time MAYA_ADDR = ('127.0.0.1', 1923) ARDUINO_PORT = 'COM3' if __name__ == '__main__': print('Welcome to the arduino-maya serial driver.') print('Press CTRL-C to exit.') print('') print('[INFO] Maya address: {0}:{1}'.format(*MAYA_ADDR)) print('[INFO] Arduino port: {0}'.format(ARDUINO_PORT)) mayaconn = None while mayaconn is None: try: mayaconn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) mayaconn.connect(MAYA_ADDR) except: mayaconn = None print('[ERROR] Maya connection refused.') print('[ERROR] (Maybe you didn\'t load the plugin in Maya?)') print('[INFO] Trying again in 5 seconds...') time.sleep(5) print('[INFO] Maya connection established.') arduinoconn = serial.Serial(ARDUINO_PORT) print('[INFO] Arduino connection established.') oldValues = [-1]*3 print("Hellu") while True: values = arduinoconn.readline().split() for i, v in enumerate(values): vInt = 0 try: vInt = int(v) except: pass else: if oldValues[i] != vInt: cmd = 'arduinoUpdateChannel ' + str(i) + ' ' + v mayaconn.send(cmd) time.sleep(.002) oldValues[i] = vInt arduinoconn.close() print('[INFO] Arduino connection closed.') mayaconn.close() print('[INFO] Maya connection closed.')
tagged with: python

http://stackoverflow.com/a/48881306
has comment: http://stackoverflow.com/comment/84767705
has comment: http://stackoverflow.com/comment/84768272
has comment: http://stackoverflow.com/comment/84766781
type: Answer
has comment: http://stackoverflow.com/comment/106121581
has comment: http://stackoverflow.com/comment/84767144
answers question: http://stackoverflow.com/q/48881228
score: 17
upvote count: 18
downvote count: 1
has comment: http://stackoverflow.com/comment/84767053
has body: Yes, it is certainly possible to do so. Check out Azure Storage SDK for Python from azure.storage.blob import BlockBlobService block_blob_service = BlockBlobService(account_name='myaccount', account_key='mykey') block_blob_service.get_blob_to_path('mycontainer', 'myblockblob', 'out-sunset.png') You can read the complete SDK documentation here: http://azure-storage.readthedocs.io.
has comment: http://stackoverflow.com/comment/84767270
has comment: http://stackoverflow.com/comment/100599843

http://stackoverflow.com/q/48913014
answer count: 1
has comment: http://stackoverflow.com/comment/84833456
favorite count: 0
has comment: http://stackoverflow.com/comment/84833546
has comment: http://stackoverflow.com/comment/84833518
has comment: http://stackoverflow.com/comment/84832435
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has title: How to create a numpy array filled with differences of elements of another array
has comment: http://stackoverflow.com/comment/84833584
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84832811
upvote count: 2
has answer: http://stackoverflow.com/a/48913286
accepted answer: http://stackoverflow.com/a/48913286
has body: I have a numpy array X. I need to create another array (say Y) of the same size, which has elements Y[i] = X[i+1]-X[i-1] Can I do that without looping over array elements?

http://stackoverflow.com/a/48962440
answers question: http://stackoverflow.com/q/48959221
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/85171354
has body: { "query": { "bool": { "must": [ { "bool": { "minimum_should_match": 1, "should": [ { "wildcard": { "demodata": { "value": "*ell*" } } }, { "wildcard": { "demodata": { "value": "*orld*" } } } ] } }, { "bool": { "minimum_should_match": 1, "should": [ { "wildcard": { "demodata": { "value": "*yellow*" } } }, { "wildcard": { "field1": { "value": "*red*" } } } ] } } ] } } } The above is one way of doing it (I'm using ES 5.3.3). This will yield no results for your provided dataset. Try playing with it a little. There are other ways of accomplishing the same behaviour, but this one the most straightforward
has comment: http://stackoverflow.com/comment/85163240

http://stackoverflow.com/comment/84858061
type: AnswerComment
comment on: http://stackoverflow.com/a/48922383
type: Comment
has text: @pylearner - OK, then simply remove `.query('cluster == 1') `
score: 0

http://stackoverflow.com/comment/84762255
has text: In fact, this message in Russian, without special characters like " ' ". So yeah, my bad - incorrect example
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48879131
type: AnswerComment

http://stackoverflow.com/comment/84674668
type: Comment
comment on: http://stackoverflow.com/a/48834765
has text: @AlexWhite: no, the same rules apply. `init_alarm_gui` is a class. You need to be calling the method on an _instance_ of the class.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/92593129
comment on: http://stackoverflow.com/a/52451527
has text: Please can you post it the problem
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84786916
score: 0
comment on: http://stackoverflow.com/q/48890003
type: Comment
type: QuestionComment
has text: You can use "selection.setBackground(0, QtGui.QBrush(QtGui.QColor("#FFFF00")))"

http://stackoverflow.com/a/48859034
accepted answer of: http://stackoverflow.com/q/48859027
answers question: http://stackoverflow.com/q/48859027
type: Answer
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84721516
has body: You're looping in the wrong way, here's how you should do it: SIZE = ('too small', 'just right', 'too large') A_TABLE = {} A_TABLE['size'] = SIZE for x in A_TABLE['size']: # change here print "size is " + x # and here
type: AcceptedAnswer

http://stackoverflow.com/comment/84729727
score: 0
type: QuestionComment
type: Comment
has text: @khelwood a temporary variable just to stop multi-line code? Does not seem necessary to me. I like the 1st one, but I could move the final parentheses to the line above
comment on: http://stackoverflow.com/q/48863091

http://stackoverflow.com/comment/84802211
comment on: http://stackoverflow.com/q/48898359
score: 0
type: Comment
type: QuestionComment
has text: There's an answer in that post that explains how to spawn variables dynamically. Just scroll down a bit.

http://stackoverflow.com/q/48887404
upvote count: 1
downvote count: 1
type: Question
score: 0
has answer: http://stackoverflow.com/a/48888559
answer count: 1
favorite count: 0
has title: ManyToManyField returns empty string in template
has body: So I have these 2 models. My Course model is linked with a ManytoMany field to TeacherData. When I try to render teacher in a template, no result appears. What is wrong ? class TeacherData(models.Model): name = models.CharField(max_length=30) surname = models.CharField(max_length=50) teacher_ID = models.CharField(unique=True, max_length=14) notes = models.CharField(max_length=255, default=None, blank=True) class Meta: verbose_name = "Teacher Data" verbose_name_plural = "Teachers Data" def __str__(self): return self.surname class Course(models.Model): study_programme = models.ForeignKey('StudyProgramme', on_delete=models.CASCADE, default='') name = models.CharField(max_length=50, unique=True) ects = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) description = models.TextField() year = models.PositiveSmallIntegerField(validators=[MaxValueValidator(99)]) semester = models.IntegerField(choices=((1, "1"), (2, "2"), ), default=None) teacher = models.ManyToManyField('TeacherData', verbose_name="Taught By") slug = models.SlugField(max_length=140, unique=True) def __str__(self): return self.name {% for c in courses.all %} {{ c.study_programme }} {{ c.name }} {{ c.ects }} {{ c.description }} {{ c.year }} {{ c.semester }} {{ c.teacher }} {% endfor %} def courses(request, slug): query = Course.objects.get(slug=slug) context = {'courses': Course.objects.filter(slug=slug), 'lectures': query.lectures.order_by('lecture_category'), } return render(request, 'courses/courses.html', context)
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/48888559
type: AnsweredQuestion

http://stackoverflow.com/comment/84642735
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48817723
type: Comment
has text: Also 0.12.2, maybe it's a Windows thing?

http://stackoverflow.com/comment/92352438
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.
comment on: http://stackoverflow.com/a/52713086
type: AnswerComment
type: Comment
score: 2

http://stackoverflow.com/comment/84614440
comment on: http://stackoverflow.com/q/48805801
has text: Is there an equivalent of ‘run as admin’ or ‘sudo’ on Mac? That’s probably what you want to do when installing your package.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84803002
has text: Thank you very much! Turns out I got wrong what my boss told me so there is no necessity to do the context menu anymore. But the PS was really useful! And the example will definitely be helpful for my own projects.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48894280
type: AnswerComment

http://stackoverflow.com/comment/84831535
type: QuestionComment
score: 0
has text: If you are specifically talking about Websites you can use selenium.
comment on: http://stackoverflow.com/q/48911864
type: Comment

http://stackoverflow.com/comment/85038640
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48956740
type: AnswerComment
has text: @I_love_Norway Welcome! It surprised me that header (or something similar) seems to come into play when hitting the URL directly in a browser. Curl at least worked without any extra header details for me, so it seems likely it is something the browser is handling. If this worked out, feel free to accept the answer. I'll still watch for any comments you have.

http://stackoverflow.com/comment/84912912
type: QuestionComment
has text: Possible duplicate of [How do I filter ForeignKey choices in a Django ModelForm?](https://stackoverflow.com/questions/291945/how-do-i-filter-foreignkey-choices-in-a-django-modelform)
comment on: http://stackoverflow.com/q/48951648
score: 0
type: Comment

http://stackoverflow.com/a/48953541
has comment: http://stackoverflow.com/comment/84917203
has comment: http://stackoverflow.com/comment/84916906
has comment: http://stackoverflow.com/comment/84923228
score: 0
has body: There are a couple issues with your code. The first is that you are trying to call plt.scatter with only an x argument. What are you trying to plot group['MATCH'] against? Next, you are trying to index your list symbols and/or your list colors by a float, which is not possible. I believe that the float you are using is the PRETEST and POSTTEST score (represented by i and k in your code). I can't see the data, but let's assume that score is a number such as 1.25; you can't select index 1.25 in your list of 2 symbols, as that doesn't mean anything to python. Are you trying to have different symbols and colors to represent different things? If so, to represent what? If not, simply take out the marker=symbols[j] and color=colors[i-k] arguments. FYI, In your code, j is not defined; you must mean either i or k when you typed symbols[j]
has comment: http://stackoverflow.com/comment/84915738
has comment: http://stackoverflow.com/comment/84915519
type: Answer
has comment: http://stackoverflow.com/comment/84920770
answers question: http://stackoverflow.com/q/48953189
has comment: http://stackoverflow.com/comment/84995694

http://stackoverflow.com/q/48945308
has answer: http://stackoverflow.com/a/48945354
type: Question
tagged with: list-comprehension
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48945447
upvote count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I am creating a simple card game and decided to implement list comprehension well try to. I don't really know how to approach this because I have only dealt with 1 for loop. def __init__(self): self.cards = [] for suit in range(1, 5): for value in range(2, 11): self.cards.append(Card(value, suit)) for value in ['Ace', 'King', 'Queen', 'Jack']: self.cards.append(Card(value, suit)) This is the nested for loop that I want to possibly put into a list comprehension, if possible. Any ideas?
tagged with: python
has title: List comprehension for nested for loops

http://stackoverflow.com/q/48845207
answer count: 1
linked to: http://stackoverflow.com/q/33757316
favorite count: 0
tagged with: tkinter
tagged with: python
has title: Tkinter Canvas polygon object issues
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48845534
has body: I saw this post: How to draw a polygon on a tkinter canvas using a class? but when I tried to draw a square: from Tkinter import* root = Tk() class GUI(Canvas): '''inherits Canvas class (all Canvas methodes, attributes will be accessible) You can add your customized methods here. ''' def __init__(self,master,*args,**kwargs): Canvas.__init__(self, master=master, *args, **kwargs) polygon = GUI(root) polygon.create_polygon([0, 0, 100, 100, 100, 0, 100], outline='gray', fill='gray', width=2) polygon.pack() root.mainloop() i got this: expected even number: got 7 Iv'e tried everything that i can think about but I can't get this to work!
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/84696618
tagged with: polygon
has answer: http://stackoverflow.com/a/48845534
score: 0
downvote count: 2

http://stackoverflow.com/a/48891758
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48890736
has comment: http://stackoverflow.com/comment/84859662
answers question: http://stackoverflow.com/q/48890736
has comment: http://stackoverflow.com/comment/84856820
type: AcceptedAnswer
downvote count: 0
has body: Calling .items on keys will probably raise an error because they are strings and I don't know what data holds, however assuming it is sent to template in your view like: return render(request, "myapp/index.html", {"data": dict}) then you can check if key equals to "videos", and iterate through the set as well: {% for key, value in data.items %} {% ifequal key "videos" %} &lt;iframe ...&gt; {% for url in value %} &lt;a class="thumbnail" href="{{ url }}"&gt;{{ url }}&lt;/a&gt; {% endfor %} &lt;/iframe&gt; {% endifequal %} {% endfor %}
type: Answer
has comment: http://stackoverflow.com/comment/84902272
has comment: http://stackoverflow.com/comment/84901679

http://stackoverflow.com/q/48962205
type: UnansweredQuestion
tagged with: difflib
tagged with: python
tagged with: list
answer count: 0
has comment: http://stackoverflow.com/comment/84931686
type: Question
tagged with: twitter
has body: I've a very long list of tweets stored in a python list (more than 50k). I'm in the stage of comparing every item verses the rest to find the similarity between tweets by using difflib (to remove those who are 755 similar while just keeping one tweet of those who are similar). I used itertools.combinations to loop over all items but it took very long time (i.e. days). Here is my code: import pandas as pd from difflib import SequenceMatcher import itertools import re import time def similar(a, b): return SequenceMatcher(None, a, b).ratio() df1=pd.read_csv("50k_TweetSheet.csv") data = df1['text'].tolist() orginalData = data outList = [] data[:] = [re.sub(r"http\S+", "", s) for s in data] data[:] = [re.sub(r"@\S+", "", s) for s in data] data[:] = [re.sub(r"RT|rt\S+", "", s) for s in data] data[:] = [s.replace('\r+', ' ') for s in data] data[:] = [s.replace('\n+', ' ') for s in data] data[:] = [s.replace(' +', ' ') for s in data] numOfRows = len(data) start_time = time.time() for a, b in itertools.combinations(range(numOfRows), 2): if len(data[a].split()) &lt; 4: continue if a in outList: continue similarity = similar(data[a],data[b]) if similarity &gt; 0.75: if len(data[a].split()) &gt; len(data[b].split()): outList.append(b) print(data[a]) else: outList.append(a) print(data[b]) Is there a faster way to do so?
score: 0
has comment: http://stackoverflow.com/comment/84930778
tagged with: sequencematcher
has title: The fastest way to compare items in a very large list in python

http://stackoverflow.com/comment/84855123
comment on: http://stackoverflow.com/a/48924090
type: AnswerComment
has text: IOError: [Errno 2] No such file or directory:
score: 0
type: Comment

http://stackoverflow.com/comment/84943312
type: Comment
type: QuestionComment
score: 0
has text: @DanielF it needs to be the surrounding cells because I need to convert a point in continuous space into the weights of the surrounding grid cells.
comment on: http://stackoverflow.com/q/48913913

http://stackoverflow.com/comment/84909552
comment on: http://stackoverflow.com/a/48944048
type: AnswerComment
has text: Thank you! I've added an example of a company that doesn't have that info (in my original post), if you wouldn't mind including that in your example. No problem if not, you've already been very helpful.
score: 0
type: Comment

http://stackoverflow.com/a/48835643
type: Answer
accepted answer of: http://stackoverflow.com/q/48835586
has comment: http://stackoverflow.com/comment/84676275
has body: if you want that a variable can be accessed in all parts of the class as in your case is the button_clicked method you must make it a member of the class for it you must use self when you create it. class Example(QWidget): [...] def initUI(self): label = QLabel('Keyword') button = QPushButton('OK') self.textbox = QLineEdit() # change this line hbox = QHBoxLayout() hbox.addWidget(label) hbox.addWidget(self.textbox) # change this line
answers question: http://stackoverflow.com/q/48835586
upvote count: 1
has comment: http://stackoverflow.com/comment/84676254
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/a/66523735
answers question: http://stackoverflow.com/q/48924787
has body: Mixing a few answers from here, I figured out a solution for Git Bash in Windows: Go to File -> Settings -> Tools -> Terminal. Replace the value in "Shell path" with "C:\Program Files\Git\bin\bash.exe" --login && conda activate myenv
type: Answer
has comment: http://stackoverflow.com/comment/129454769
downvote count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/84706223
type: Comment
comment on: http://stackoverflow.com/a/48851258
score: 0
type: AnswerComment
has text: Just tried the first one! Didn't need to try the second one! Works fine! :)

http://stackoverflow.com/q/48946682
has answer: http://stackoverflow.com/a/48946969
accepted answer: http://stackoverflow.com/a/48946969
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48946794
type: Question
answer count: 2
has body: How can I explicitly access the excellent Series string formatting built-in to Pandas, to format my numbers like so: &gt;&gt;&gt; pd.Series([0.000034, 0.000035, 0.000038]) 0 0.000034 1 0.000035 2 0.000038 dtype: float64 The astype only results in Python's plain float-to-string conversion: &gt;&gt;&gt; pd.Series([0.000034, 0.000035, 0.000038]).astype(str) 0 3.4e-05 1 3.5e-05 2 3.8e-05 dtype: object (I realize I could parse the string generated by pd.Series.__str__, but looking for something less hackish.) Edit: the reason I'd like to use the built-in Pandas formatting is that I don't know the range of the floats in advance.
score: 0
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48946794
has title: How to utilize pandas string formatting

http://stackoverflow.com/comment/84841274
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48917250
has text: Agreed. Was hoping I could use the lib, but you're right. Easiest way is just work around this method and call the API directly. I'll go ahead and do that. As for UTF-8, my understanding is that that's only for txt files, not images.
score: 0

http://stackoverflow.com/comment/84841362
comment on: http://stackoverflow.com/a/48917429
has text: Is there a way to do this so that It isn't necessary for me to know the size of the string to pin point what I need. Because the strings will be different and wont use the same positions for characters
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48868312
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48850537
type: Answer
answers question: http://stackoverflow.com/q/48850537
has body: It seems that we can (or need to?) use the session from Keras (which has the associated loaded graph with weights) instead of creating a new session in Tensorflow and using the graph obtained from Keras model like below VGG = model.graph I think the graph got above has no weights in it (and that is the reason predictions are wrong) and the graph from Keras session as the proper weights (so those two graph instances should be different) Below is the full code: import tensorflow as tf import numpy as np from PIL import Image from tensorflow.python.keras._impl.keras.applications import imagenet_utils from tensorflow.python.keras._impl.keras import backend as K model = tf.keras.applications.VGG16() sess = K.get_session() VGG = model.graph #Not needed and also doesnt have weights in it VGG.get_operations() input = VGG.get_tensor_by_name("input_1:0") output = VGG.get_tensor_by_name("predictions/Softmax:0") print(input) print(output) I = Image.open("Elephant.jpg") new_img = I.resize((224,224)) image_array = np.array(new_img)[:, :, 0:3] image_array = np.expand_dims(image_array, axis=0) image_array = image_array.astype(np.float32) image_array = tf.keras.applications.vgg16.preprocess_input(image_array) pred = (sess.run(output,{input:image_array})) print(imagenet_utils.decode_predictions(pred)) And this gives the expected result: ('n02504458', 'African_elephant', 0.8518132), ('n01871265', 'tusker', 0.1398836), ('n02504013', 'Indian_elephant', 0.0082286), ('n01704323', 'triceratops', 6.965483e-05), ('n02397096', 'warthog', 1.8662439e-06) Thanks Idavid for the tip about using preprocess_input() function and Nicolas for tips about unloaded weights.

http://stackoverflow.com/q/48874148
tagged with: exception
tagged with: python
has comment: http://stackoverflow.com/comment/84752217
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
score: 3
upvote count: 3
has answer: http://stackoverflow.com/a/48874199
type: Question
has answer: http://stackoverflow.com/a/62145022
has body: I'm parsing an XML file using Beautiful Soup. Sometimes I have entries that are missing one or more of the keys I'm parsing. I want to setup exceptions to handle this. My code looks something like this: for entry in soup.findAll('entry_name'): try: entry_dict = dict(entry.attrs) x = entry_dict["x"] y = entry_dict["y"] z = entry_dict["z"] d[x] = [y, z] except KeyError: y = "0" d[x] = [y, z] The problem is I can have "y", "z" or both "y and z" missing depending on the entry. Is there a way to handle specific KeyErrors? Something like this: except KeyError "y": except KeyError "z": except KeyError "y","z":
has answer: http://stackoverflow.com/a/48874353
possible better answer: http://stackoverflow.com/a/48874199
answer count: 3
has title: Python Except Specific Key Error
downvote count: 0
favorite count: 0
tagged with: keyerror
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/48874353

http://stackoverflow.com/q/48839454
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84683182
has title: Creating combination of different elements in a list
type: Question
has comment: http://stackoverflow.com/comment/84683625
tagged with: python-2.7
has body: I have a list of words: ['The', 'president', 'control'...]. And I have different POS tags for each word. For example: {The: {DT}, president: {NP}, control: {NP, VB}...}. Now I need to compute all combinations possible for the statement, for example: [The_DT, president_NP, control_NP] --&gt; Ist Combination [The_DT, president_NP, control_VB] --&gt; 2nd Combination Any help on how can I do so?
has comment: http://stackoverflow.com/comment/84683595
has comment: http://stackoverflow.com/comment/84683488
score: 0
tagged with: python
tagged with: nlp
answer count: 0

http://stackoverflow.com/comment/107840179
has text: More generally, I'd worry a lot about the distribution because since N>>k for many distributions it will be easy to rule out many points as being part of the set.
comment on: http://stackoverflow.com/q/48925086
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48814781
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/48893906
answer count: 1
favorite count: 0
tagged with: python
has body: I am trying to train a fully convolutional model which can take images of any input resolution using tensorflow 1.5. Currently I am doing something like this: image, segmentation = \ D.get_training_dataset_data_provider() image, segmentation = \ tf.train.batch([image, segmentation], batch_size=16) # Define the model: predictions, loss, end_points = M.model_w_batch_norm( image, segmentation ) Then I go on to use a tf.train.MonitoredTrainingSession to train the model. Everything works really nicely, except that I am getting a model that has an fixed input shape (i.e. image_in has the shape I am feeding from my dataset data provider). The get_training_dataset_data_provider loads images from a tfrecord and augments them. The output is a constant resolution, which is fine for training. For testing / prediction, however I would like to be able to pass images of any shape. The model itself is fully convolutional (in M.model_w_batch_norm) has the tensor image_in defined: def model_w_batch_norm(in_image, trainable=True): in_image = tf.identity(in_image, name="image_in") ... If I were not to use tf.train.batch, I would just define a Placeholder with shape (None, None, None, x), but I think I cannot link tf.train.batch to a placeholder, can I? How do can I define an input tensor for the model of the shape (None, None, None, x)?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48893906
score: 1
has title: Retain [None, None, None, x] input shape when using `tf.train.batch`
upvote count: 1
tagged with: tensorflow

http://stackoverflow.com/q/48834565
tagged with: tuples
tagged with: python
has title: Extract inner tuple and count number of items?
possible better answer: http://stackoverflow.com/a/48834647
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84675268
upvote count: 0
has answer: http://stackoverflow.com/a/48834961
has answer: http://stackoverflow.com/a/48834691
has comment: http://stackoverflow.com/comment/84673797
accepted answer: http://stackoverflow.com/a/48834691
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84673766
has body: I am trying to plot a histogram for the number of items in an itemset list. The itemset list freq_itemsets has 1500+ elements which look somewhat like this: ((' Spouse', ' Min.Edu', ' United-States'), 0.12281563834034581) ((' Male',), 0.6692054912318418) ((' United-States', ' Uni.Edu'), 0.1463714259390068) In all of these itemsets, I am only concerned with the elements of the inner container (The stuff inside the nested '()' parens). The float with the trailing decimals after aren't important. What I am trying to do is extract the inner parentheses as a temporary list, store the lengths of each inner itemset in a list freq_itemset_lengths. The end goal here is to be able to plot a histogram of the lengths of the itemsets found in freq_itemsets. Below is the code I am running: freq_itemset_lengths = [] for instance in freq_itemsets: freq_itemset_lengths.append(len(instance)) print "\nHistogram for the lengths of frequent itemsets" hist_create(freq_itemset_lengths, "Histogram of lengths of frequent itemsets", "Itemset Lengths", "Blue") The method hist_create works fine, and is as follows: def hist_create(feature, title, label, color): plt.hist(feature, facecolor=color, edgecolor='black') plt.title(title) plt.xlabel(label) plt.ylabel("Frequency/Amount") plt.show() The output of this is a histogram with only one bar that is plotted at 2 on the x-axis (Presumably because the itemset holds items as a tuple), and goes to 1500+ in the y-axis (Number of instances). How do I fix this so that the histogram plots the various lengths of the itemsets themselves?
score: -1
has answer: http://stackoverflow.com/a/48834647
answer count: 3
favorite count: 0

http://stackoverflow.com/comment/84717122
score: 0
type: AnswerComment
type: Comment
has text: Thanks for your help, but I don't understand how to use the .get() command to get the text value within.
comment on: http://stackoverflow.com/a/48854553

http://stackoverflow.com/comment/84801092
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48897502
has text: @nikhil It is commentary1, forgot to change that from where I was making it

http://stackoverflow.com/tag/csv
tags question: http://stackoverflow.com/q/48824516
tags question: http://stackoverflow.com/q/48847210
tags question: http://stackoverflow.com/q/48852898
type: Tag
tags question: http://stackoverflow.com/q/48889914
tags question: http://stackoverflow.com/q/48859333
tags question: http://stackoverflow.com/q/48852855
tags question: http://stackoverflow.com/q/48943430
tags question: http://stackoverflow.com/q/48918137
tags question: http://stackoverflow.com/q/48899051
tags question: http://stackoverflow.com/q/48816717
tags question: http://stackoverflow.com/q/48900923
tags question: http://stackoverflow.com/q/48853461
tags question: http://stackoverflow.com/q/48861325
tags question: http://stackoverflow.com/q/48880222
tags question: http://stackoverflow.com/q/48931927
tag name: csv
tags question: http://stackoverflow.com/q/48893773
tags question: http://stackoverflow.com/q/48930609
tags question: http://stackoverflow.com/q/48894864
tags question: http://stackoverflow.com/q/48874610
tags question: http://stackoverflow.com/q/48841474
tags question: http://stackoverflow.com/q/48929929
tags question: http://stackoverflow.com/q/48956621
tags question: http://stackoverflow.com/q/48827226
tags question: http://stackoverflow.com/q/48862979
tags question: http://stackoverflow.com/q/48811910
tags question: http://stackoverflow.com/q/48884116
tags question: http://stackoverflow.com/q/48860934
tags question: http://stackoverflow.com/q/48854768
tags question: http://stackoverflow.com/q/48949121
tags question: http://stackoverflow.com/q/48816109
tags question: http://stackoverflow.com/q/48828954
tags question: http://stackoverflow.com/q/48905856
tags question: http://stackoverflow.com/q/48892475
tags question: http://stackoverflow.com/q/48953177
tags question: http://stackoverflow.com/q/48886849
tags question: http://stackoverflow.com/q/48873457
tags question: http://stackoverflow.com/q/48890393
tags question: http://stackoverflow.com/q/48903008
tags question: http://stackoverflow.com/q/48892601
tags question: http://stackoverflow.com/q/48810701
tags question: http://stackoverflow.com/q/48960159
tags question: http://stackoverflow.com/q/48908772
tags question: http://stackoverflow.com/q/48917135
tags question: http://stackoverflow.com/q/48843322
tags question: http://stackoverflow.com/q/48946892
tags question: http://stackoverflow.com/q/48817981
tags question: http://stackoverflow.com/q/48909471
tags question: http://stackoverflow.com/q/48924730
tags question: http://stackoverflow.com/q/48927727
tags question: http://stackoverflow.com/q/48819578
tags question: http://stackoverflow.com/q/48888168
tags question: http://stackoverflow.com/q/48908353
tags question: http://stackoverflow.com/q/48914161
tags question: http://stackoverflow.com/q/48945460
tags question: http://stackoverflow.com/q/48863790
tags question: http://stackoverflow.com/q/48911523
tags question: http://stackoverflow.com/q/48945594
tags question: http://stackoverflow.com/q/48960107
tags question: http://stackoverflow.com/q/48960049
tags question: http://stackoverflow.com/q/48825011
tags question: http://stackoverflow.com/q/48812441
tags question: http://stackoverflow.com/q/48847264
tags question: http://stackoverflow.com/q/48818434
tags question: http://stackoverflow.com/q/48906098
tags question: http://stackoverflow.com/q/48913153
tags question: http://stackoverflow.com/q/48846417
tags question: http://stackoverflow.com/q/48902830
tags question: http://stackoverflow.com/q/48852382
tags question: http://stackoverflow.com/q/48834872
tags question: http://stackoverflow.com/q/48956892
tags question: http://stackoverflow.com/q/48852354
tags question: http://stackoverflow.com/q/48889465
tags question: http://stackoverflow.com/q/48887720
tags question: http://stackoverflow.com/q/48815646
tags question: http://stackoverflow.com/q/48853867
tags question: http://stackoverflow.com/q/48892348
tags question: http://stackoverflow.com/q/48954080
tags question: http://stackoverflow.com/q/48843120

http://stackoverflow.com/a/48844296
downvote count: 0
answers question: http://stackoverflow.com/q/48844295
has comment: http://stackoverflow.com/comment/138491281
type: Answer
has comment: http://stackoverflow.com/comment/84697172
upvote count: 1
has comment: http://stackoverflow.com/comment/137763975
score: 1
has body: I'm posting the answer here in case someone else will need it, since it took me quite some time to figure out a viable approach. I ended up solving this by defining the following function def vector_autocorrelate(t_array): n_vectors = len(t_array) # correlate each component indipendently acorr = np.array([np.correlate(t_array[:,i],t_array[:,i],'full') for i in xrange(3)])[:,n_vectors-1:] # sum the correlations for each component acorr = np.sum(acorr, axis = 0) # divide by the number of values actually measured and return acorr = np.array( [ val / (n_vectors - i) for i,val in enumerate(acorr)]) return acorr If anybody has a better idea, I would really like to hear that since I think the current one is still not as compact as it should be. It's better than nothing though, which is why I'm posting it here.

http://stackoverflow.com/q/48825011
has comment: http://stackoverflow.com/comment/84667876
has comment: http://stackoverflow.com/comment/84654099
has answer: http://stackoverflow.com/a/68471772
type: Question
has comment: http://stackoverflow.com/comment/84653833
possible better answer: http://stackoverflow.com/a/48826461
has answer: http://stackoverflow.com/a/48826461
score: 0
accepted answer: http://stackoverflow.com/a/48826559
answer count: 3
has title: csv file from yaml in python
tagged with: yaml
has comment: http://stackoverflow.com/comment/84654475
has answer: http://stackoverflow.com/a/48826559
has body: 4: - a: [0.6511928334730416, -0.6444996859128429, 0.40070930065859994] b: [-70.26386506067132, 19.563101216582368, 315.91419304402643] c: [462, 429, 401, 389] d: 1 5: - e: [0.6511928334730416, -0.6444996859128429, 0.40070930065859994] f: [-70.26386506067132, 19.563101216582368, 315.91419304402643] g: [462, 429, 401, 389] h: 1 This is my yml format and I have to extract only the values of key c and g from it and create a csv file. I am new to python. Can anyone guide me here thanks in advance
has comment: http://stackoverflow.com/comment/84654568
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84653754
tagged with: python
has comment: http://stackoverflow.com/comment/84655117
type: AnsweredQuestion

http://stackoverflow.com/comment/84677728
has text: @Bianca Where it comes from is irrelevant, you remove the characters the same way.
comment on: http://stackoverflow.com/a/48835819
type: AnswerComment
score: 1
type: Comment

http://stackoverflow.com/q/48844768
upvote count: 1
has body: I'm trying to make a chain of the middlewares and I have to pass data between them. I would like to have the variables that live during the request/response lifecycle. At this moment I use environ argument and add to it the data. But it seems that this is a wrong way. Example: class A(object): """First class in a sequence""" def __call__(self, app): # logic here def some_func(environ, start_response): # logic here environ['my key'] = 'some data' def custom_headers(status, headers, exc_info=None): # change headers return start_response(status, headers, exc_info) return app(environ, custom_headers) return some_func class B(object): """Second class in a sequence""" def __call__(self, app): # logic here def some_func(environ, start_response): data = environ.get('my key') # logic here def custom_headers(status, headers, exc_info=None): # change headers return start_response(status, headers, exc_info) return app(environ, custom_headers) return some_func So as you can see I would like to generate a data in one class and after that treat it in the second one(!data should be unique per each request/response not shared between them). Could you help to find the best way to do it?
tagged with: middleware
type: Question
score: 1
has title: How to pass data between wsgi middleware?
tagged with: wsgi
downvote count: 0
favorite count: 0
tagged with: python
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48899051
answer count: 6
accepted answer: http://stackoverflow.com/a/48899141
score: 78
has title: How to drop a specific column of csv file while reading it using pandas?
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/65552661
favorite count: 0
has body: I need to remove a column with label name at the time of loading a csv using pandas. I am reading csv as follows and want to add parameters inside it to do so. Thanks. pd.read_csv("sample.csv") I know this to do after reading csv: df.drop('name', axis=1)
has comment: http://stackoverflow.com/comment/84803869
tagged with: python
has comment: http://stackoverflow.com/comment/84803482
upvote count: 78
possible better answer: http://stackoverflow.com/a/70892110
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48899332
has answer: http://stackoverflow.com/a/70892110
downvote count: 0
type: Question
has answer: http://stackoverflow.com/a/61409300
has answer: http://stackoverflow.com/a/71441051
linked to: http://stackoverflow.com/q/36410287
tagged with: dataframe
has answer: http://stackoverflow.com/a/48899141

http://stackoverflow.com/q/48917704
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: uac
has answer: http://stackoverflow.com/a/61410839
has title: Request UAC Elevation From Within Python Script With ctypes.windll.shell32.ShellExecuteW
has body: myClass generates a XLSX file to the './output' folder. The following line of code in myClass requires administrator privilege: excel = win32com.client.Dispatch('Excel.Application') I followed the answer in Request UAC elevation from within a Python script?, and now I have the following script: import ctypes, sys from my_module import myClass def is_admin(): try: return ctypes.windll.shell32.IsUserAnAdmin() except: return False if is_admin(): myClass else: # Re-run the program with admin rights ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, "", None, 1) However, this seems to elevate and exit, as if I selected No in the UAC prompt. If I run the above code block in Administrator cmd, &gt;python uac_test.py, somehow it generates 2 identical files, instead of one. Am I missing something? Any help is appreciated!
linked to: http://stackoverflow.com/q/130763
type: Question
upvote count: 4
score: 4

http://stackoverflow.com/q/48845652
accepted answer: http://stackoverflow.com/a/48845736
has title: Extracting data from a meta tag beautifulsoup returning null
has comment: http://stackoverflow.com/comment/84695440
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: http://stackoverflow.com/tag/html
tagged with: python
has answer: http://stackoverflow.com/a/48845736
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84695512
tagged with: meta
has body: I trying to scrape the mileage of a car from this website https://cazana.com/uk/car/RA51GZJ The data I want is the mileage (128,375 miles) when i try to scrape this page i get nothing returned I orignally tried to scape the body of the page with no luck url = "https://cazana.com/uk/car/RA51GZJ" page2 = requests.get(url) soup2 = BeautifulSoup(page2.content, 'html.parser') result = soup2.findAll('meta', attrs={'name': 'description'}) print (result) Returns [] This is the html file &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;meta name="description" content="RA51GZJ - 2001 NISSAN ALMERA. Colour silver, 128,375 miles, 3 previous owners. Registered in Reading. Tax, MOT &amp;amp; Vehicle history check available."&gt; Thanks
upvote count: 1
type: Question

http://stackoverflow.com/comment/84680159
comment on: http://stackoverflow.com/a/48837658
type: AnswerComment
score: 0
type: Comment
has text: Python does not use parentheses nor brackets to nest code after if, while and for statements, for example. It uses indentation, that is simply some blank space in the beginning of the line (common use are 4 spaces). For further research: https://docs.python.org/3/reference/lexical_analysis.html#indentation

http://stackoverflow.com/comment/84864797
type: Comment
type: QuestionComment
has text: I think it's not
score: 0
comment on: http://stackoverflow.com/q/48925401

http://stackoverflow.com/q/48822177
answer count: 2
tagged with: pandas
has comment: http://stackoverflow.com/comment/84647675
upvote count: 1
downvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48822580
accepted answer: http://stackoverflow.com/a/48822580
tagged with: python
possible better answer: http://stackoverflow.com/a/65957957
has title: KeyError when trying to randomize a column of a dataframe
has body: Minimal Example: Consider this dataframe temp: temp = pd.DataFrame({"A":[1,2,3,4,5,6,7,8,9,10],"B":[2,3,4,5,6,7,8,9,10,11],"C":[3,4,5,6,7,8,9,10,11,12]}) &gt;&gt;&gt; temp A B C 0 1 2 3 1 2 3 4 2 3 4 5 3 4 5 6 4 5 6 7 5 6 7 8 6 7 8 9 7 8 9 10 8 9 10 11 9 10 11 12 Now, trying to shuffle each column at a time, in a for loop. &gt;&gt;&gt; for i in temp.columns: ... np.random.shuffle(temp.loc[:,i]) ... print(temp) ... A B C 0 8 2 3 1 3 3 4 2 9 4 5 3 6 5 6 4 4 6 7 5 10 7 8 6 7 8 9 7 1 9 10 8 2 10 11 9 5 11 12 A B C 0 8 7 3 1 3 9 4 2 9 8 5 3 6 10 6 4 4 4 7 5 10 11 8 6 7 5 9 7 1 3 10 8 2 2 11 9 5 6 12 A B C 0 8 7 6 1 3 9 8 2 9 8 4 3 6 10 10 4 4 4 7 5 10 11 11 6 7 5 5 7 1 3 3 8 2 2 12 9 5 6 9 This works perfectly. Specific Example: Now, if I want to get a part of this dataframe, for training and testing purposes, then I'll use the train_test_split function from sklearn.model_selection. &gt;&gt;&gt; from sklearn.model_selection import train_test_split &gt;&gt;&gt; temp = pd.DataFrame({"A":[1,2,3,4,5,6,7,8,9,10],"B":[2,3,4,5,6,7,8,9,10,11],"C":[3,4,5,6,7,8,9,10,11,12]}) &gt;&gt;&gt; y = [i for i in range(16,26)] &gt;&gt;&gt; len(y) 10 &gt;&gt;&gt; X_train,X_test,y_train,y_test = train_test_split(temp,y,test_size=0.2) &gt;&gt;&gt; X_train A B C 2 3 4 5 6 7 8 9 8 9 10 11 0 1 2 3 7 8 9 10 3 4 5 6 1 2 3 4 9 10 11 12 Now, we've obtained our X_train dataframe. In order to shuffle it's each column: &gt;&gt;&gt; for i in X_train.columns: ... np.random.shuffle(X_train.loc[:,i]) ... print(X_train) ... Which, unfortunately results in an error. Error: sys:1: 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 Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "mtrand.pyx", line 4852, in mtrand.RandomState.shuffle File "mtrand.pyx", line 4855, in mtrand.RandomState.shuffle File "C:\Users\H.P\App…
has comment: http://stackoverflow.com/comment/84667559
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84647586
linked to: http://stackoverflow.com/q/15474159
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/21463589
has comment: http://stackoverflow.com/comment/84667569
has answer: http://stackoverflow.com/a/65957957
tagged with: train-test-split
score: 0

http://stackoverflow.com/q/48948769
answer count: 2
linked to: http://stackoverflow.com/q/48291581
favorite count: 0
possible better answer: http://stackoverflow.com/a/48951968
has answer: http://stackoverflow.com/a/48951968
tagged with: python
has title: How to draw contours using opencv in Python?
has answer: http://stackoverflow.com/a/48948944
has body: I have following image preprocessed: Now I want to use findContours method in order to find cells from image and then use drawContours in order draw contour for every cell from image. I do this but nothing is shown. contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cv2.drawContours(img, contours, -1, (0, 255, 0), 3) I receive the following error. contours is not a numpy array, neither a scalar Another answers didn't helped me. I also use following solution. contours = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0] ctr = numpy.array(contours).reshape((-1,1,2)).astype(numpy.int32) cv2.drawContours(img, ctr, -1, (0, 255, 0), 3) But this solution didn't draw anything on the given image.
upvote count: 3
downvote count: 2
tagged with: computer-vision
tagged with: opencv
type: AnsweredQuestion
score: 1
tagged with: image-processing
linked to: http://stackoverflow.com/q/47855046
accepted answer: http://stackoverflow.com/a/48948944
type: Question
tagged with: numpy

http://stackoverflow.com/comment/84697892
comment on: http://stackoverflow.com/q/48845435
has text: Well nice point, it's just that i want to optimize EVERYTHING i can cuz the other parts already pretty complex =)) As to CPython - i don't sure how it works, it is a python plugin for Cinema4D i work on. It is definitely gets compiled, but i don't know if it's a bytecode or pure binary...
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48915456
has answer: http://stackoverflow.com/a/48915855
favorite count: 0
tagged with: list
answer count: 5
possible better answer: http://stackoverflow.com/a/48915593
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48915593
score: 1
has comment: http://stackoverflow.com/comment/84837458
has answer: http://stackoverflow.com/a/48915686
type: Question
upvote count: 2
has answer: http://stackoverflow.com/a/48915535
accepted answer: http://stackoverflow.com/a/48915535
downvote count: 1
has comment: http://stackoverflow.com/comment/84837373
has title: Using a dict to translate numbers to letters in python
has body: I have a string 'alphabet' with all the letters in the alphabet and a list of ints corresponding to those those letters (0-25). Ex: num_list = [5,3,1] would translate into letter_list = ['f','d','b'] I currently can translate with: letter_list = [alphabet[a] for a in num_list] However, I would like to use a dict for the same thing, retrieve 'letter' keys from dict with 'number' values. alpha_dict = {'a':0,'b':1,'c':2}... etc How do I change my statement to do this?
tagged with: python
has answer: http://stackoverflow.com/a/67960348
tagged with: dictionary

http://stackoverflow.com/q/48836620
answer count: 1
has comment: http://stackoverflow.com/comment/84678535
favorite count: 0
has comment: http://stackoverflow.com/comment/84678146
score: -3
tagged with: python
tagged with: regex
has title: Extracting a specific value from a specific xml tag using Regex in Python
duplicate of: http://stackoverflow.com/q/1327369
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/84678066
type: Question
accepted answer: http://stackoverflow.com/a/48836679
has comment: http://stackoverflow.com/comment/84682539
has body: My xml: Tove Jani Reminder Don't forget me this weekend! I need a regex to extract "Don't forget me this weekend!" in the tag and also if the tag exists in python using regex. I have written a code, but I am not able to figure out the regex expression.
linked to: http://stackoverflow.com/q/1327369
has answer: http://stackoverflow.com/a/48836679
downvote count: 3

http://stackoverflow.com/q/48844923
favorite count: 0
has comment: http://stackoverflow.com/comment/84694102
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84694458
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84694315
has comment: http://stackoverflow.com/comment/84694289
has answer: http://stackoverflow.com/a/48845399
type: Question
has body: I am building a mock terminal-like program using python, and am trying to build a login system for it. My directory setup, after going through multiple revisions, eventually came out to look like this: pythonapp-harlker/ __init__.py loginCheck.py main.py userlist.py __init__.py is empty, and main.py's main code chunk looks like this: from loginCheck import * loginFunc = Login() loginFunc.login() if loginFunc.login().checkPass == True: print("Welcome %s!" % (username)) Importing loginCheck returns no error, so naturally, I looked at loginCheck.py. import sys, platform, importlib import hashlib from userlist import * class Login: def login(self): username = input("Username: ") password = input("Password: ") password = str.encode(password) password = str(hashlib.md5(password).hexdigest()) if username in users: userPassAndIndex = users.get(username) if password == userPassAndIndex[0]: checkPass = True value = userPassAndIndex[1] else: self.login() else: self.login() Looking at a debugger, it keeps telling me that loginCheck.py is unable to import a dictionary from userlist.py. userlist.py users = { 'localAdmin10': ["086e717a4524329da24ab80e0a9255e2", 0], 'orlovm': ["505ec2b430fa182974ae44ede95ca180", 1], 'testUser10': ["90e611f269e75ec5c86694f900e7c594", 2], 'torradiRemote': ["0b841ebf6393adac25950a215aecc3d1", 3], } Additionally, while running the python code (from main.py), the code seems unable to detect if the input username and passwords are correct. I've looked at tons of stackOverflow pages and external sources but I'm at a kind of "programmer's block" now.
has comment: http://stackoverflow.com/comment/84695476
downvote count: 0
has comment: http://stackoverflow.com/comment/84694161
has title: Dictionary reference keeps throwing an unsolved reference
answer count: 1
score: 1

http://stackoverflow.com/comment/97346132
comment on: http://stackoverflow.com/a/49611289
score: 0
type: AnswerComment
has text: This one liner really very efficient. But I got stuck in one point, what is the functionality of strip? I ran that code without using strip and it had same output. Thank you in advance.
type: Comment

http://stackoverflow.com/comment/84891659
type: QuestionComment
type: Comment
has text: `pop` always removes the last element in the list.
comment on: http://stackoverflow.com/q/48942459
score: 0

http://stackoverflow.com/comment/84861122
score: 3
has text: Possible duplicate of [List of tuples to nested dictionary without overriding](https://stackoverflow.com/questions/40340133/list-of-tuples-to-nested-dictionary-without-overriding)
type: Comment
comment on: http://stackoverflow.com/q/48926974
type: QuestionComment

http://stackoverflow.com/comment/84869888
type: QuestionComment
comment on: http://stackoverflow.com/q/48931253
score: 0
has text: Do you have any concerns about writing integer values as float in the csv file? It usually don't matter too much if your integers are written as float. One way to can do is to convert everything into string and then save as csv.
type: Comment

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

http://stackoverflow.com/a/48895077
type: Answer
upvote count: 4
downvote count: 0
has body: Let's look at using groupby and transform with div: MVCE: df = pd.DataFrame({'Date':pd.date_range('2018-02-10','2018-02-12',freq='H'),'A':np.random.randint(0,100,49),'B':np.random.randint(100,200,49),'C':np.random.random(49)}) df = df.set_index('Date') print(df.head()) Output: A B C Date 2018-02-10 00:00:00 11 131 0.474226 2018-02-10 01:00:00 35 188 0.998742 2018-02-10 02:00:00 97 182 0.683685 2018-02-10 03:00:00 0 134 0.845094 2018-02-10 04:00:00 24 173 0.238379 Use groupby, transfrom and div: df'A','B','C'.div(df.groupby(df.index.floor('D')).transform('mean')) Output head(): A B C Date 2018-02-10 00:00:00 0.362637 0.866593 0.931739 2018-02-10 01:00:00 1.153846 1.243660 1.962284 2018-02-10 02:00:00 3.197802 1.203969 1.343275 2018-02-10 03:00:00 0.000000 0.886439 1.660404 2018-02-10 04:00:00 0.791209 1.144432 0.468357
score: 4
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48894899
accepted answer of: http://stackoverflow.com/q/48894899

http://stackoverflow.com/a/48881477
type: Answer
has comment: http://stackoverflow.com/comment/84767338
downvote count: 1
score: 4
has body: Use groupby with agg, last rename columns and reset_index: df = (df.groupby('Name')['Color'].agg(['nunique', lambda x: ', '.join(set(x))]) .rename(columns={'nunique':'Distinct', '&lt;lambda&gt;':'Values'}) .reset_index()) print (df) Name Distinct Values 0 Greg 2 Blue, Red 1 John 2 Blue, Yellow
answers question: http://stackoverflow.com/q/48881437
upvote count: 5
has comment: http://stackoverflow.com/comment/84767309

http://stackoverflow.com/comment/84614893
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48805441
has text: can you post the full code here, it will help to understand the problem
score: 0

http://stackoverflow.com/q/48855938
has comment: http://stackoverflow.com/comment/84715308
type: Question
has comment: http://stackoverflow.com/comment/84715350
tagged with: gpio
tagged with: python
answer count: 1
has title: Raspberry Pi SW-420 vibration sensor and Python
score: 0
has answer: http://stackoverflow.com/a/48860650
tagged with: raspberry-pi
has comment: http://stackoverflow.com/comment/84718586
has comment: http://stackoverflow.com/comment/84718673
type: UnansweredQuestion
has body: I'm trying to create an application that will sense my laundry machine turning on. Then when it's done, i want it to detect that and flash my Hue bulbs. I'm using the SW-420 vibration sensor and Python for this project. I have successfully gotten it to recognize vibration, but unfortunately, it's not what I need. The following is my current code. #!/usr/bin/python import RPi.GPIO as GPIO import time import subprocess #GPIO SETUP channel = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(channel, GPIO.IN) def start(channel): if GPIO.input(channel): print "Dryer has started!" time.sleep(1) else: print "Dryer has stopped" time.sleep(1) #f = open("status", "w") #Used to create light status file #subprocess.call(["perl", "/home/pi/huepi/huepi", "lights"], stdout=f); # creates status file #subprocess.call(["perl", "/home/pi/huepi/huepi", "for", "1 3 4 5 6 10 11 12", "do", "blinkonce"]); # blinks hue bulbs GPIO.add_event_detect(channel, GPIO.BOTH, bouncetime=300) # let us know when the pin goes HIGH or LOW GPIO.add_event_callback(channel, start) # assign function to GPIO PIN, Run function on change # infinite loop while True: time.sleep(1) The issue that I'm having is even when the machine is running the sensor registers that it has stopped. I've tried using GPIO.add_event_detect(channel, GPIO.RISING, bouncetime=300) and GPIO.add_event_detect(channel, GPIO.FALLING, bouncetime=300) both with the same results. I just need it to register that the machine has started then with it stops flash the Hue bulb and wait for the next time the machine starts back up. I'm using a Perl library called Huepl to interface with but bulbs That section of the code is working fine. If you need any more information I'll be glad to supply. Thank you in advance!
tagged with: vibration

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

inheritance
tags question: http://stackoverflow.com/q/48920795
tags question: http://stackoverflow.com/q/48908406
tags question: http://stackoverflow.com/q/48896403
tag name: inheritance
tags question: http://stackoverflow.com/q/48814211
type: Tag
tags question: http://stackoverflow.com/q/48835428
tags question: http://stackoverflow.com/q/48955933

http://stackoverflow.com/comment/84727586
type: QuestionComment
score: 0
has text: Another idea - `dframe['Product'] = dframe['Product'].fillna('')` should working.
comment on: http://stackoverflow.com/q/48862235
type: Comment

http://stackoverflow.com/q/48929299
tagged with: temporary
answer count: 2
has comment: http://stackoverflow.com/comment/84908765
has comment: http://stackoverflow.com/comment/84873264
has comment: http://stackoverflow.com/comment/84870084
has comment: http://stackoverflow.com/comment/84866112
tagged with: default
has comment: http://stackoverflow.com/comment/84905351
has body: I would like to temporarily change the default of a class. I came up with some ideas: class C(object): VALUE_DEFAULT = [1, 2, 3] def __init__(self, value=None): if value is None: value = self.VALUE_DEFAULT self._value = value @property def value(self): return self._value print("Initial default:", C().value) """ 1) Repetitious version that makes code unclear if multiple instances should be instantiated or the default should not be used. """ print("Changed default manually:", C(value=[0, 2, 4]).value) """ 2) dangerously hard coded version """ C.VALUE_DEFAULT = [0, 2, 4] print("Changed default by changing the default constant:", C().value) C.VALUE_DEFAULT = [1, 2, 3] """ 3) possibly more pythonic version still this version seems hacky """ from contextlib import contextmanager @contextmanager def tmp_default(cls, name, value): old_val = getattr(cls, name) setattr(cls, name, value) yield setattr(cls, name, old_val) with tmp_default(C, "VALUE_DEFAULT", [0, 2, 4]): print("Changed default with contextmanager:", C().value) print("Restored the default again:", C().value) From the possibilities above i strongly prefer 3). Any further ideas or improvements? Thanks in advance
favorite count: 0
has answer: http://stackoverflow.com/a/48951122
accepted answer: http://stackoverflow.com/a/48951122
tagged with: python
has title: python temporary change of class default
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/84865173
downvote count: 0
possible better answer: http://stackoverflow.com/a/48930239
has comment: http://stackoverflow.com/comment/84865705
has answer: http://stackoverflow.com/a/48930239
has comment: http://stackoverflow.com/comment/84865487
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/84907034

http://stackoverflow.com/q/48843586
score: 3
has answer: http://stackoverflow.com/a/48843769
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84691648
has answer: http://stackoverflow.com/a/54460320
answer count: 3
tagged with: pandas
downvote count: 0
favorite count: 0
has title: Joining Dataframe with multiple dates (Vlookup)
type: UnansweredQuestion
tagged with: python
upvote count: 3
has body: I have the following in a file below and was wondering how to join them together, I know how to join if they were two separate dataframe but the values range from D1 up to D20+ and will not be practical to create so many multiple dataframes. My objective is to join them based on D1 date as per below. D1 D1value D2 D2value D3 D3value 1/2/2018 21.14 1/2/2018 11.14 1/6/2018 1.55 1/3/2018 19.13 1/3/2018 51.14 1/13/2018 2.66 1/6/2018 19.89 1/14/2018 31.14 1/14/2018 3.77 1/13/2018 20.24 1/14/2018 20.91 After joining it should be D1 D1value D2value D3value 1/2/2018 21.14 11.14 NaN 1/3/2018 19.13 51.14 NaN 1/6/2018 19.89 NaN 1.55 1/13/2018 20.24 NaN 2.66 1/14/2018 20.91 31.14 3.77 Any kind advise please? For piRSquared answer add df: df = pd.concat([proc(d) for k, d in df.groupby(g, 1)], axis=1) Both piRSquared and jp_data_analysis answer works The issue is I want to select both as the right answer!
has answer: http://stackoverflow.com/a/48843937
type: Question

http://stackoverflow.com/comment/84776471
has text: @Saranaone Just do `requests.get('https://ipinfo.io/json', proxies=<test_proxy>)` and check the IP address of the response. And replace <test_proxy> with one of the proxy IP addresses from the list to test if it is working
type: AnswerComment
comment on: http://stackoverflow.com/a/48885026
score: 0
type: Comment

http://stackoverflow.com/a/48916894
score: 1
downvote count: 0
has body: You could try this. import random import requests, bs4 agents= [ 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko)', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko)', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko)', 'Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)'] headers = {"User-Agent":random.choice(agents)} response = requests.get(full_url,headers=headers) soup = BeautifulSoup(response.text, 'lxml')
answers question: http://stackoverflow.com/q/48915457
type: Answer
has comment: http://stackoverflow.com/comment/84842943
upvote count: 1

http://stackoverflow.com/comment/119292369
has text: @DanMašek Thank you for pointing that out - not sure what I was thinking 3 years ago, but I have deleted it. Thank you.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48863230

http://stackoverflow.com/comment/84729742
has text: ´cv2.imread('test.png', -cv2.IMREAD_ANYDEPTH)´ it's still not working. It's still a 8 bit array
score: 0
comment on: http://stackoverflow.com/q/48863230
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84891764
has text: Try `data = open("twoorgs.genesis.block").readlines()` or `data = open("twoorgs.genesis.block", 'rb').read()`
comment on: http://stackoverflow.com/q/48942570
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/84782414
comment on: http://stackoverflow.com/q/48887461
score: 0
type: Comment
type: QuestionComment
has text: @DennisSoemers Yeah, I was already doubting my own comment after noticing that each of the ten chunks would be 8MB in size, which is right at the limit of the biggest typcial L3 caches. If it's not caching, I have no idea – I guess the OP will need to profile the compiled code to figure out what's going on.

http://stackoverflow.com/comment/84827098
has text: @Victor I saw you edited the question to add `random_state=50` in both cases; can you confirm that the exact numbers shown in your images still hold after this modification??
comment on: http://stackoverflow.com/q/48909418
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48831279
answers question: http://stackoverflow.com/q/48830681
downvote count: 0
has body: I think like @0x5453, if you wrongly add backslash to your code. This backslash cause the comment to be concat with a. a = "Some text. " \ """Here are some multiline comments that will be added to a"""
score: 1
upvote count: 1
type: Answer

http://stackoverflow.com/comment/84765183
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48880466
score: 0
has text: post the create code so that its easier to understand, and also any tracebacck

http://stackoverflow.com/a/48814416
has body: you can use the Counter function from collection module from collections import Counter files_list = ['pic1.jpg', 'pic2.jpg', 'pic3.jpg', 'movie1.mov', 'movie2.mov', 'doc1.pdf', 'doc2.pdf', 'doc3.pdf', 'doc4.pdf'] temp = [] for item in files_list: temp.append(item[-3:]) print Counter(temp) &gt;&gt;&gt; Counter({'pdf': 4, 'jpg': 3, 'mov': 2})
answers question: http://stackoverflow.com/q/48814286
score: 0
type: Answer

http://stackoverflow.com/comment/84616311
type: Comment
comment on: http://stackoverflow.com/q/48805703
score: 0
has text: Try adding a comma to then end of the inner list: unique_together= (('field1', 'field2', 'field3',),)
type: QuestionComment

http://stackoverflow.com/q/48826740
tagged with: python
has comment: http://stackoverflow.com/comment/84657144
downvote count: 3
type: Question
tagged with: for-loop
has comment: http://stackoverflow.com/comment/84657171
answer count: 1
score: -1
tagged with: http://stackoverflow.com/tag/c
has title: two variable in for loop in python
has comment: http://stackoverflow.com/comment/84657109
has comment: http://stackoverflow.com/comment/84660056
has comment: http://stackoverflow.com/comment/84659843
has body: My question is about for loops in python. When I use C, I use two variables in the same for loop like this: for (i=0, j=5; i&lt;5, j&gt;0; i++, j--) How can I create this for loop in python?
has comment: http://stackoverflow.com/comment/84657215
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84659881
linked to: http://stackoverflow.com/q/6774980
upvote count: 2
has answer: http://stackoverflow.com/a/48826968
has comment: http://stackoverflow.com/comment/84660031
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84657263

http://stackoverflow.com/comment/84633374
type: QuestionComment
comment on: http://stackoverflow.com/q/48814375
score: 0
has text: I added my code.
type: Comment

http://stackoverflow.com/q/48897977
score: 1
has answer: http://stackoverflow.com/a/48897985
accepted answer: http://stackoverflow.com/a/48897985
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84801898
downvote count: 0
has answer: http://stackoverflow.com/a/48898055
favorite count: 0
has body: I'm looking for a one-line Python expression that performs the following search : targets = ['habble', 'norpouf', 'blantom'] entry = "Sorphie porre blantom nushblot" found=False for t in targets : if t in entry : found = True break print ("found" if found else "not found") So that we can write something like this : print("found" if entry.contains(targets) else "not found")
has title: Python : string contains NOT string in
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/48898055
type: AnsweredQuestion

http://stackoverflow.com/a/48882591
has body: If I've understood correctly, you want something like this: import pandas as pd pd.set_option("display.width", 300) # Test input data df = pd.DataFrame({ "label": ["hostname1", "hostname1", "hostname2", "hostname2"], "switch_no": ["Switch1", "Switch1", "Switch1", "Switch2"], "switch_port": [1, 1, 2, 3] }) print df # Count ports per label and ports per switch_no (unique and total, depending on what you want) df["unique_ports_per_label"] = df.groupby("label")["switch_port"].transform("nunique") df["ports_per_label"] = df.groupby("label")["switch_port"].transform(len) df["unique_ports_per_switch"] = df.groupby("switch_no")["switch_port"].transform("nunique") df["ports_per_switch"] = df.groupby("switch_no")["switch_port"].transform(len) print df Which results in: label switch_no switch_port 0 hostname1 Switch1 1 1 hostname1 Switch1 1 2 hostname2 Switch1 2 3 hostname2 Switch2 3 After: label switch_no switch_port unique_ports_per_label ports_per_label unique_ports_per_switch ports_per_switch 0 hostname1 Switch1 1 1 2 2 3 1 hostname1 Switch1 1 1 2 2 3 2 hostname2 Switch1 2 2 2 2 3 3 hostname2 Switch2 3 2 2 1 1
has comment: http://stackoverflow.com/comment/84802269
has comment: http://stackoverflow.com/comment/84775375
type: Answer
answers question: http://stackoverflow.com/q/48880222
has comment: http://stackoverflow.com/comment/84774716
score: 0
has comment: http://stackoverflow.com/comment/84778032
has comment: http://stackoverflow.com/comment/84804897
has comment: http://stackoverflow.com/comment/84774587
has comment: http://stackoverflow.com/comment/84777212
has comment: http://stackoverflow.com/comment/84777406
has comment: http://stackoverflow.com/comment/84776375
has comment: http://stackoverflow.com/comment/84776399
has comment: http://stackoverflow.com/comment/84775033
has comment: http://stackoverflow.com/comment/84775163

http://stackoverflow.com/comment/84893933
type: Comment
type: QuestionComment
score: 1
has text: You can use [pandas.Series.dt.time](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.dt.time.html) attribute to get time. `pd.to_datetime(df, format='%H:%M:%S').dt.time` like this. And you can just subtract the columns to find the timedelta. Or do something like [this answer](https://stackoverflow.com/a/22924683/826970). Can you edit in a sample input and expected output to your question?
comment on: http://stackoverflow.com/q/48943571

http://stackoverflow.com/q/48887991
tagged with: python
answer count: 0
upvote count: 2
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84783019
tagged with: pandas
score: 2
downvote count: 0
has title: Rolling data based on custom function - Pandas
has body: I am trying to create a DataFrame that contains daily entries of values that are based on a rolling 12 month slice of larger data sets (called applications and assignments). At the moment, I have not used df.rolling because I don't think it's right in this situation. I am simply looping through an index of dates, performing several functions on a 12 month slice of the larger data sets for each date. The returned values are then appended to a list for each variable, then I create a DataFrame using those lists. This is slow. I am looking for a ways to speed up the creation of my rolling_data DataFrame. This is the function that calculates the values from a rolling window: def calculate_rolling(apps, assgs, date_index): # dictionary containing lists of data - used later to create df values = {'owners':[], 'successful_owners' :[], 'applications' :[], 'assignments':[], 'filled_assignments':[], 'sitters':[], 'successful_sitters':[] } for day in date_index: twelve_months_prior = day - relativedelta(months=12) app_view = apps.loc[str(twelve_months_prior):str(day.date())] # slice of applications df assg_view = assgs.loc[str(twelve_months_prior):str(day.date())] # slice of assignments df values['owners'].append(assg_view.ouser_id.nunique()) values['sitters'].append(assg_view.ouser_id.nunique()) values['applications'].append(app_view.request_id.count()) values['assignments'].append(assg_view.is_assignment_filled.sum()) values['filled_assignments'].append(assg_view.is_assignment_filled.sum()) values['successful_sitters'].append(assg_view[assg_view.is_assignment_filled ==1].suser_id.nunique()) values['successful_owners'].append(assg_view[assg_view.is_assignment_filled ==1].ouser_id.nunique()) return pd.DataFrame(data=values, index=date_index) ..and this is how I am calling that, after creating the date range index: # create index of dates index = pd.date_range(start=start, end=applications.created_date.max()) # create df from values dictionary rolling_data = calculate_rolling(ap…
favorite count: 0
has comment: http://stackoverflow.com/comment/84782356

http://stackoverflow.com/q/48938991
type: Question
tagged with: window-resize
has body: I'm new to Python/Tkinter and I'm really stuck here... I am trying to design a fairly responsive GUI and in one of the frames I need to display a vertical list of widgets that might not fit all at the same time. If the user resizes the window, I'd like to compute the amount of items that can fit in the new size and finally redraw the "visible" list. I'm using the root.bind('&lt;Configure&gt;', do_something) to trigger the redraw. PROBLEM: binding to the &lt;configure&gt; event triggers the command many times for each single resize action. I'd like to be able to determine when the resizing have been completed (and the mouse button released), and redraw just once. I have read the answers to this previously posted question (very relevant and basically identical to my case), but the first answer doesn't provide any code and I sincerely couldn't figure out how to follow the advice, while the second answer gives the code but it doesn't solve the problem. One of the comments to this second answer already suggests that it might not work because the ButtonRelease-1 event is not inside the window (since it is a resize). And in fact on my OS doesn't work (Win10). Could someone provide me with a solution, or a workaround, to help me? If possible, I'd like the solution to be applicable to either Windows and Linux/Debian systems. Below you can see how my code looks like. Many thanks for any help. import tkinter as tk class MyListOfStuff(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.redraw() def redraw(self): # (re)populate the frame with as many widgets as possible class MyApp(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.pack(fill=tk.BOTH, expand=1) self.child_frame = MyListOfStuff(self) self.bind('&lt;Configure&gt;', self.resize_detected) def resize_detected(self, *args): self.child_frame.redraw() # HERE LIES THE PROBLEM... # This method gets called multiple times per second during the resizing # of the main window, an…
score: 3
has comment: http://stackoverflow.com/comment/84885431
answer count: 1
downvote count: 0
tagged with: event-handling
favorite count: 0
has answer: http://stackoverflow.com/a/48939334
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84923039
has title: Continuous call of the <Configure> event in tkinter (follow up)
tagged with: tkinter
linked to: http://stackoverflow.com/q/17747904
upvote count: 3

http://stackoverflow.com/a/48831909
type: Answer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/48831599
has body: Setup df = pd.DataFrame(dict( Col1=list('AAAABBBB'), Col2=range(1, 9, 1), Col3=range(9, 1, -1) )) df df.groupby('Col1').sum().eval('Col4 = Col2 / Col3') Col1 Col2 Col3 0 A 1 9 1 A 2 8 2 A 3 7 3 A 4 6 4 B 5 5 5 B 6 4 6 B 7 3 7 B 8 2 Solution Using pd.DataFrame.eval We can use eval to create new columns in a pipeline df.groupby('Col1', as_index=False).sum().eval('Col4 = Col2 / Col3') Col1 Col2 Col3 Col4 0 A 10 30 0.333333 1 B 26 14 1.857143
upvote count: 6

http://stackoverflow.com/q/48898476
tagged with: python
type: AnsweredQuestion
score: 3
has body: I wanted to use dbus in the raspberry pi with this simple script bus = dbus.SystemBus() obj = bus.get_object('org.bluez', '/') print "object" print obj manager = dbus.Interface(obj,'org.bluez.Manager') obj = bus.get_object('org.bluez',manager.DefaultAdapter()) print "Manager" print manager print "object" print obj But when i am try to run that code i am getting Traceback (most recent call last): File "/home/pi/Desktop/hangul-recog/tools/DisableICT.py", line 350, in &lt;module&gt; ge = Paint() File "/home/pi/Desktop/hangul-recog/tools/DisableICT.py", line 125, in __init__ self.test() File "/home/pi/Desktop/hangul-recog/tools/DisableICT.py", line 280, in test obj = bus.get_object('org.bluez',manager.DefaultAdapter()) File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 70, in __call__ return self._proxy_method(*args, **keywords) File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 145, in __call__ **keywords) File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in call_blocking message, timeout) DBusException: org.freedesktop.DBus.Error.UnknownMethod: Method "DefaultAdapter" with signature "" on interface "org.bluez.Manager" doesn't exist I am using bluez 5.43 version. I have checked for the solution but no luck. What should i do? Thanks in advance.
upvote count: 3
has answer: http://stackoverflow.com/a/49017827
type: Question
tagged with: raspbian
tagged with: raspberry-pi
tagged with: bluez
tagged with: bluetooth
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/85024954
favorite count: 0
accepted answer: http://stackoverflow.com/a/49017827
has title: Method "DefaultAdapter" with signature "" on interface "org.bluez.Manager" doesn't exist in raspberry pi 3

http://stackoverflow.com/comment/84671273
comment on: http://stackoverflow.com/q/48831544
has text: Have you installed all [dependencies](https://kivy.org/docs/installation/installation-windows.html#installation) correctly? `python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.angle` (Make sure to install in the interpreter / virtual environment that you are using).
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84709721
comment on: http://stackoverflow.com/q/48853140
type: QuestionComment
score: 0
has text: I am going to modify the code
type: Comment

http://stackoverflow.com/a/48816173
has body: try this in template: {% for cart in my_carts_current_entries %} {{ cart.product }} - {{ cart.quantity }} {% endfor %}
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48815848
type: AcceptedAnswer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48815848
type: Answer

http://stackoverflow.com/comment/84630856
type: QuestionComment
comment on: http://stackoverflow.com/q/48813238
type: Comment
has text: Finding the odbc.ini was not the problem, i corrected the path.
score: 0

http://stackoverflow.com/a/48879308
has comment: http://stackoverflow.com/comment/84785377
upvote count: 2
has comment: http://stackoverflow.com/comment/84785026
type: Answer
has comment: http://stackoverflow.com/comment/84762934
has comment: http://stackoverflow.com/comment/84762768
score: 2
has comment: http://stackoverflow.com/comment/84785124
has comment: http://stackoverflow.com/comment/84795027
has comment: http://stackoverflow.com/comment/84782698
has body: Base case(s), in general, serve one or more purposes, these include; preventing the function from recursing infinitely preventing the function from throwing errors on corner cases compute/return a value/result to callers higher up in the recursion tree With tree deletion, the first point isn't really a concern (because the recursion tree will only have a finite number of nodes - same as the tree you recurse over). You will be concerned with points 2 and 3 here. In your function, you do have a base case - in fact, you have two (thanks to @user2357112) - The value-not-found portion, specified by if node is None: return node and, The value-found portion, specified by your code inside the else statement, which performs the actual deletion. To keep the behaviour consistent with the recursive cases, the value-not-found base case returns None. As you see, the first base case is consistent performs the second function of a generic base case outlined above, while the second base case performs the third.
has comment: http://stackoverflow.com/comment/84765999
has comment: http://stackoverflow.com/comment/84762883
has comment: http://stackoverflow.com/comment/84798041
has comment: http://stackoverflow.com/comment/84762643
has comment: http://stackoverflow.com/comment/84763771
answers question: http://stackoverflow.com/q/48879229
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48879229

http://stackoverflow.com/q/48848635
answer count: 0
has body: I am trying to write a Python script that automates running 'dnf upgrade' on Fedora. The same process should be useful on other Linux platforms like Debian as well. To handle the prompts for the upgrade process, I am using the Python module 'pexpect'. I need to spawn the command 'sudo dnf upgrade' then enter a password if the 'Password:' prompt appears, then test for the '[y/N]' prompt and submit a 'Y' for that, and finally, if no '[y/N]' option appears, exit with a message that "No updates are available". Here is the script I have written so far, but it seems to fail at the '[y/N]' test if there are no updates. I am not sure what I have to do to continue parsing the output. import time import pexpect up = pexpect.spawn('sudo dnf update') if up.expect(['(?i)password.*']) == 0: up.sendline('crazyhardpassword') time.sleep(2) else: print("Permissions already elevated...") if up.expect(['.*\[y/N\].*']) == 0: up.sendline('Y') time.sleep(2) else: print("No upgrade approval prompt displayed!") if up.expect(['(?i)^nothing.*\r\nComplete!.*']) == 0: print("No updates available...") else: raise AssertionError("Upgrade request failed!!!") Any suggestions on successfully executing the script whether or not there are updates? Thank you.
type: Question
has comment: http://stackoverflow.com/comment/84703744
tagged with: automation
has comment: http://stackoverflow.com/comment/84800893
has title: python pexpect dnf upgrade automation
linked to: http://stackoverflow.com/q/31337924
tagged with: pexpect
score: 0
has comment: http://stackoverflow.com/comment/84803814
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48815258
type: Answer
has comment: http://stackoverflow.com/comment/84635863
score: 2
has comment: http://stackoverflow.com/comment/84643155
has comment: http://stackoverflow.com/comment/84634644
has comment: http://stackoverflow.com/comment/84646777
answers question: http://stackoverflow.com/q/48815210
has comment: http://stackoverflow.com/comment/84637204
has comment: http://stackoverflow.com/comment/84635372
downvote count: 0
has comment: http://stackoverflow.com/comment/84634875
upvote count: 2
has body: Why you just do not multiply a and b with 1/p ? int(a * 1/p) int(b * 1/p) You exactly do not need python (or its string methods) other than converting resulting floats to integer, just arithmetics -))

http://stackoverflow.com/a/50672747
type: Answer
upvote count: 15
has body: This is because you installed pyinstaller globally. Use pipenv install -d pyinstaller before packing.
score: 15
answers question: http://stackoverflow.com/q/48875894
has comment: http://stackoverflow.com/comment/137982725
downvote count: 0

http://stackoverflow.com/comment/113835435
has text: what are flex queries?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/51470089
type: Comment

http://stackoverflow.com/comment/84849854
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48921541
has text: `brew` does not seem to have installed a library with that name as part of the `boost` package itself, although the headers are included in the `boost` package. `libboost_python.{a,dylib}` does appear to be part of `boost-python`.
score: 0

http://stackoverflow.com/a/48869264
has body: Try from core.module1 import stuff. You should not import src since you are in that location with your main.py already.
accepted answer of: http://stackoverflow.com/q/48869198
has comment: http://stackoverflow.com/comment/84742408
answers question: http://stackoverflow.com/q/48869198
has comment: http://stackoverflow.com/comment/84742848
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84745683
has comment: http://stackoverflow.com/comment/84742271
score: 1
has comment: http://stackoverflow.com/comment/84742213
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84745846

http://stackoverflow.com/q/48894905
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48897827
tagged with: sqlalchemy
score: 0
has title: How to get field in sqlalchemy?
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84795937
has body: I have the following query: product = session.query(ProductTable).filter(ProductTable.image_d == 0).first() When I try to get the value of the field: print (product["sku"]) I get an error: 'ProductTable' object is not subscribable
has comment: http://stackoverflow.com/comment/84795992
tagged with: python
has answer: http://stackoverflow.com/a/48897827
type: AnsweredQuestion

http://stackoverflow.com/q/48821598
tagged with: python-2.7
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48821716
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84646559
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48821716
has comment: http://stackoverflow.com/comment/84646521
has comment: http://stackoverflow.com/comment/84646598
has title: Regular Expression for R.layout in java files
has comment: http://stackoverflow.com/comment/84646630
type: Question
has body: Requirement Regex for R.layout.anyfile in file and want the string anyfile in a variable Example in java file setContentView(R.layout.fragment) ; python variable should return fileName = fragment IN PYTHON

http://stackoverflow.com/a/48893585
type: Answer
score: 2
has body: You can use list comprehensions to extract the text from the elements: headers_30 = [i.text for i in soup.find_all("p", {"class":"s30"})] headers_33 = [i.text for i in soup.find_all("p", {"class":"s33"})] headers_20 = [i.text for i in soup.find_all("p", {"class":"s20"})] Instead of: headers_30 = soup.find_all("p", attrs={"class":"s30"}) headers_33 = soup.find_all("p", attrs={"class":"s33"}) headers_20 = soup.find_all("p", attrs={"class":"s20"})
has comment: http://stackoverflow.com/comment/84825220
answers question: http://stackoverflow.com/q/48892445
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48892445
has comment: http://stackoverflow.com/comment/84822071
upvote count: 2

http://stackoverflow.com/comment/84716514
has text: Thanks for all the help and putting in the time!! I replaced the 'isinstance' with x!="", and now it works perfectly. Apologies if my question wasn't clear -- still trying to get the basics of python down!
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48855541

http://stackoverflow.com/comment/84822861
type: QuestionComment
type: Comment
has text: Possible duplicate of [How to upgrade to Django 2.0](https://stackoverflow.com/questions/48872885/how-to-upgrade-to-django-2-0)
score: 0
comment on: http://stackoverflow.com/q/48902662

http://stackoverflow.com/a/48838235
score: 0
answers question: http://stackoverflow.com/q/48838050
type: Answer
has body: You can try this, I've upgraded a little to generate more complex password. import random lower = 'q w e r t y u i o p a s d f g h j k l z x c v b n m' nums = '1 2 3 4 5 6 7 8 9 0'.split() upper = lower.upper().split() spcl = '; ! # @ &amp; $ '.split() all = lower.split() + nums + upper + spcl def genpass(n): x = 0 if x == 0: password = '' if n &lt; 100: while n &gt; x: password = password + random.choice(all) x=x + 1 print(password) else: print('Sorry, too long') # generates a sample password genpass(10)

http://stackoverflow.com/q/48871327
has title: Can't reference widget id in Kivy
score: 0
answer count: 1
tagged with: python
tagged with: kivy
has answer: http://stackoverflow.com/a/48874203
type: AnsweredQuestion
tagged with: kivy-language
has body: Very new to Kivy and trying to dynamically add widgets, but despite all the examples I have followed, I can't get mine to work. My .kv file is... ScreenManager: MainScreen: LoginScreen: &lt;MainScreen&gt;: name: 'MainScreen' id: ms BoxLayout: id: rc_display orientation: "vertical" padding: 10 spacing: 10 Label: id: ms_label1 text: 'Oh Hell Yeah' &lt;LoginScreen&gt;: name: 'LoginScreen' id: ls Button: on_release: app.root.current text: 'Click to Login' font_size: 20 and my python code is... from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen from kivy.lang import Builder from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button import requests class MainScreen(Screen): def on_pre_enter(self, *args): show_view = self.ids.rc_display # error here show_view.clear_widgets() buttons = BoxLayout(orientation = 'vertical') pr = requests.get('http://127.0.0.1:5000/stageplanning/api/v1.0/shows') for show in pr.json(): buttons.add_widget(Button(text = show['show_title'])) show_view.add_widgets(buttons) class LoginScreen(Screen): pass class ScreenManagement(ScreenManager): pass class StagePlanningApp(App): def build(self): sm = Builder.load_file('StagePlanning.kv') # sm.add_widget(MainScreen()) # sm.add_widget(LoginScreen()) return sm sp_app = StagePlanningApp() sp_app.run() When I run the above I get the following error... File "*pathtoFile*/StagePlanning.py", line 12, in on_pre_enter show_view = self.ids.rc_display File "kivy\properties.pyx", line 839, in kivy.properties.ObservableDict.__getattr__ (kivy\properties.c:12654) AttributeError: 'super' object has no attribute '__getattr__' If I add the widgets directly to the Screen object they display, but are on top of each other. Its only when I try and reference the id I get an error. I have even printed to the console the list of ids, and they are there as expected.
accepted answer: http://stackoverflow.com/a/48874203
type: Question

http://stackoverflow.com/a/48856877
has body: One way is to use collections.defaultdict combined with itertools.combinations. There may be a pandas-specific way but this, by nature, will be library-specific. from collections import defaultdict from itertools import combinations df_grouped = df.groupby('Project_ID')['Participating_entity'].apply(list).reset_index() d = defaultdict(int) for idx, row in df_grouped.iterrows(): for comb in combinations(row['Participating_entity'], 2): d[frozenset(comb)] += 1 # defaultdict(int, # {frozenset({'a', 'b'}): 2, # frozenset({'a', 'c'}): 2, # frozenset({'b', 'c'}): 1}) d = {tuple(sorted(k)): v for k, v in d.items()} df_out = pd.DataFrame(list(d.items()))\ .rename(columns={0: 'Entities', 1: 'Num_collaborations'}) df_out = df_out.join(df_out['Entities'].apply(pd.Series))\ .drop('Entities', 1).rename(columns={0: 'Entity 1', 1: 'Entity 2'}) # Num_collaborations Entity 1 Entity 2 # 0 2 a b # 1 2 a c # 2 1 b c
accepted answer of: http://stackoverflow.com/q/48856713
answers question: http://stackoverflow.com/q/48856713
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/84759153
has text: Yes. It will count the number of windows open and print them. E.g: If 3 windows are open, it will print ("window open 3") and then close all three windows one by one.
score: 0
comment on: http://stackoverflow.com/q/48855078
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48944029
linked to: http://stackoverflow.com/q/26579248
tagged with: python
has comment: http://stackoverflow.com/comment/84908257
downvote count: 0
has comment: http://stackoverflow.com/comment/84896889
score: 1
has comment: http://stackoverflow.com/comment/84894689
type: Question
has answer: http://stackoverflow.com/a/53172925
has body: The csv file I have messy code which is supposed to be chinese characters. I want to read the file into python with the chinese characters not messy as before. How do I do that? I tried pandas.read_csv with encoding like gb2312 or gb18030, they all report error like UnicodeDecodeError: 'gb2312' codec can't decode byte 0xae in position 4: illegal multibyte sequence My data: CODE NAME LISTDATE FOUNDDATE TIME DATE EPTTM INDUSTRY LISTCITY 000001.SZ Âπ≥ÂÆâÈì∂Ë°å 3/4/1991 19871222 8 1/1/2007 0.030477768 Ω»⁄∑˛ŒÒ …Ó€⁄ 000002.SZ ‰∏áÁßëA 29/1/1991 19840530 8 1/1/2007 0.025771537 ∑øµÿ≤˙ …Ó€⁄ 000004.SZ ÂõΩÂÜúÁßëÊäÄ 14/1/1991 19860505 8 1/1/2007 -0.05297144 “Ω“©…˙ŒÔ …Ó€⁄ 000005.SZ ‰∏ñÁ∫™ÊòüÊ∫ê 10/12/1990 19870730 8 1/1/2007 -0.024968897 ∑øµÿ≤˙ …Ó€⁄ 000006.SZ Ê∑±ÊåØ‰∏öA 27/4/1992 19850525 8 1/1/2007 0.074647402 ∑øµÿ≤˙ …Ó€⁄ 000007.SZ ÂÖ®Êñ∞Â•Ω,13/4/1992 19830311 NA 8 1/1/2007 NA ∑øµÿ≤˙ …Ó€⁄ 000008.SZ Á•ûÂ∑ûÈ´òÈìÅ 7/5/1992 19891011 8 1/1/2007 -0.010574387 ◊€∫œ …Ó€⁄ 000009.SZ ‰∏≠ÂõΩÂÆùÂÆâ 25/6/1991 19830706 8 1/1/2007 0.009576133 ∑øµÿ≤˙ …Ó€⁄
has title: how to read in csv file with Chinese characters in python
has comment: http://stackoverflow.com/comment/84895659
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84896808
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84894552

http://stackoverflow.com/q/48933824
upvote count: 5
possible better answer: http://stackoverflow.com/a/48933930
tagged with: python
tagged with: merge
type: AnsweredQuestion
downvote count: 0
has body: I am concatenating all files in a directory together into one, however some files have a different number of entries - how to I place an NaN when there isn't a value for that key in the file? For example: file1.cs NUM, NAME, ORG, DATA 1,AAA,10,123.4 1,AAB,20,176.5 1,AAC,30,133.5 file2. cs NUM, NAME, ORG, DATA 1,AAA,10,111.4 1,AAC,30,122.5 2,BBA,12,156.7 Desired Output NUM, NAME, ORG, File1, File2 .... 1, AAA, 10, 123.4, 111.4 1, AAB, 20, 176.5, NaN 1, AAC, 30, 133.5, 122.5 2, BBA, 12, NaN, 156.7 ..... This is what I've tried: import pandas as pd import glob writer = pd.ExcelWriter('analysis.xlsx', engine='xlsxwriter') data = [] df1 = pd.read_csv("file1.cs", sep = ',', header = 'infer') for infile in glob.glob("*.cs"): df = pd.read_csv(infile, sep = ',', header = 'infer') name = infile[13:-7] df['filename'] = name data.append(df) result = pd.merge(df1, data.to_frame(), on= 'NAME') result.to_excel(writer, sheet_name=sheetname) writer.save() I also tried pd.concat(data, axis=1, ignore_index=False) but this doesn't add the NaN because it just concatenates the files based on the column name.
has title: Pandas - add NaN for missing values when pd.merge
has answer: http://stackoverflow.com/a/48934017
accepted answer: http://stackoverflow.com/a/48934017
type: Question
score: 5
has answer: http://stackoverflow.com/a/48933930
has answer: http://stackoverflow.com/a/48934068
answer count: 3
tagged with: pandas
favorite count: 0

http://stackoverflow.com/q/48844790
possible better answer: http://stackoverflow.com/a/49838333
tagged with: keras
has answer: http://stackoverflow.com/a/49838333
favorite count: 0
has title: Generator Stalls Keras fit_generator
has answer: http://stackoverflow.com/a/48846193
upvote count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48846193
score: 1
has body: I have a data set with 9 columns, the last is the target variable as a csv with header. I am trying to write a generator to train a model in keras. The code is below. The training run during the first epoch but stalls / hangs for ever before finishing. from sklearn.datasets import california_housing import pandas as pd import numpy as np data=california_housing.fetch_california_housing() cols=data.feature_names cols.append('y') data=pd.DataFrame(np.column_stack([data.data,data.target.reshape((data.target.shape[0],1))]),columns=cols) data.to_csv('/media/jma/DATA/calhousing.csv',index=False) Code for the generator: import csv import numpy as np def generate_arrays_from_file(file_name,batchsz): csvfile = open(file_name) reader = csv.reader(csvfile) batchCount = 0 inputs = [] targets = [] while True: #infinite loop linecounter=0 #which line the reader is reading for line in reader: if linecounter &gt;0: #is not the header inputs.append(line[0:8]) targets.append(line[8]) batchCount += 1 # we added if batchCount &gt;= batchsz: # we have our mini batch batchCount = 0 #reset batch counter X = np.array(inputs,dtype="float32") y = np.array(targets,dtype="float32") yield (X, y) #reset the lists to hold the batches inputs = [] targets = [] linecounter += 1 #increment the line read linecounter = 0 #reset Running like this: from keras.models import Sequential from keras.layers import Dense batch_size =100 train_gen=generate_arrays_from_file('/media/jma/DATA/calhousing.csv',batchsz=batch_size) model = Sequential() model.add(Dense(32, input_shape=(8,))) model.add(Dense(1, activation='linear')) model.compile(optimizer='rmsprop', loss='mse', metrics=['mse']) model.fit_generator(train_gen,steps_per_epoch=data.shape[0] / batch_size, epochs=5, verbose=1) Epoch 1/5 194/206 [===========================>..] - ETA: 0s - loss: 67100.1775 - mean_squared_error: 67100.1775
type: Question
answer count: 2
downvote count: 0

http://stackoverflow.com/q/48871694
has comment: http://stackoverflow.com/comment/84751618
has comment: http://stackoverflow.com/comment/84749148
has body: I have a docker file that copies in a bash script and a python script from the host machine to /root in the docker's file system: FROM centos RUN yum install -y nc COPY filter_text_telemetry.sh /root/ COPY read_data.py /root/ EXPOSE 8071 RUN cd /root My python script is supposed to start the bash script as a subprocess and then gather data from it as follows: p = Popen(["./filter_text_telemetry.sh"], stdout=PIPE, stderr=PIPE) p.stdout.readline() On my host machine, the python code works fine and is able to print out the data it gathers. In my docker container, it prints nothing and I'm not sure why. The docker container defaults to running everything as root. Could that be affecting the stdout pipe? If that is not it then what can I do to fix my issue?
has answer: http://stackoverflow.com/a/48886999
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84749139
type: Question
has comment: http://stackoverflow.com/comment/84749492
has comment: http://stackoverflow.com/comment/84748500
has comment: http://stackoverflow.com/comment/84747199
tagged with: docker
has title: python subprocess cannot read from stdout using popen in docker
score: 0
tagged with: bash
answer count: 1
tagged with: python

http://stackoverflow.com/comment/84646291
score: 1
has text: **"It's like python is reading from the top down"** -- well that's exactly how Python interprets a program. You may also want to read: https://docs.python.org/3/reference/executionmodel.html
comment on: http://stackoverflow.com/q/48821178
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48897341
type: Answer
score: 1
upvote count: 1
has body: I'm not exactly sure how to do it with pandas but what about using itertools.groupby? &gt;&gt;&gt; import pandas as pd &gt;&gt;&gt; s = pd.Series([False, True, False,True,True,True,False, False]) &gt;&gt;&gt; max(sum(1 for _ in g) for k, g in groupby(s) if k) 3
answers question: http://stackoverflow.com/q/48897265
downvote count: 0

http://stackoverflow.com/a/48945773
has comment: http://stackoverflow.com/comment/84898318
upvote count: 1
has comment: http://stackoverflow.com/comment/84898029
has comment: http://stackoverflow.com/comment/84899862
has comment: http://stackoverflow.com/comment/84898827
score: 1
has comment: http://stackoverflow.com/comment/84898396
has body: I think you got confused what position 33 means. When not in the context of programming, then you would look at the 33rd entry in your list, which in your case is 1. In Python and many other languages arrays and lists are indexed, starting at 0. So the 1st entry in your list has index 0. So when you tell python key[33] it actually looks up the 34th entry in your list. That is 0 as the script also outputs. What you want is the 33rd entry in the list. Which has index 33-1=32. So you need to do: for i in range(0,56): print ("index", i, "PC1 ", PC1[i], "value from KEY ", KEY[PC1[i]-1]) KEY_PERM.insert(i, KEY[PC1[i]-1]) print(''.join(KEY_PERM)) &gt;&gt;&gt; '11110000110011001010101011110101010101100110011110001111' Notice PC1[i]-1 when using the entry from PC1[i] to acces KEY Complete Test Script: PC1=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4] KEY='0001001100110100010101110111100110011011101111001101111111110001' KEY_PERM=[] for i in range(0,56): KEY_PERM.insert(i, KEY[PC1[i]-1]) print(''.join(KEY_PERM)) prints: 11110000110011001010101011110101010101100110011110001111
has comment: http://stackoverflow.com/comment/84899373
has comment: http://stackoverflow.com/comment/84899436
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48945506
has comment: http://stackoverflow.com/comment/84899181
accepted answer of: http://stackoverflow.com/q/48945506
has comment: http://stackoverflow.com/comment/84899476
type: Answer
has comment: http://stackoverflow.com/comment/84898958
has comment: http://stackoverflow.com/comment/84899526

http://stackoverflow.com/q/48818434
has title: Clustering and labeling data set with 4 parameters
linked to: http://stackoverflow.com/q/1832076
has answer: http://stackoverflow.com/a/48819911
score: 0
answer count: 2
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
accepted answer: http://stackoverflow.com/a/48819911
possible better answer: http://stackoverflow.com/a/48822930
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48822930
has body: This is a loaded question and it's my first 'real life' machine learning experiment so bare with the simplistic questions. I have USPTO bulk data that looks like this in a CSV file: Name Class Subclass Category Subcategory Lightpack circuitboard E 1 4 9 Lego blocks F 2 56 12 D/C connector E 3 4 1 Colorful dog hat D 6 10 1 Grandma's shoes D 2 11 1 Low temp resistor O 2 4 10 What I want is to be able to run a supervised machine learning environment to group the common objects (there are many more than this in my actual data but this is a simple example). I want to be able to run through to find a common set of class, subclass, category, and subcategory amongst all electronics and to group them as such into an electronics 'bin' (ie: Lightpack circuitboard, D/C connector, and Low temp resistor) but am unsure how to proceed. Currently I'm using Python and sklearn to do my more simplistic modeling but am unsure of how to test and train under 4 parameters given and I have no labeled set to compare to (no validation). Would creating a pseudo-labeled set to make it supervised be more advised or is there an unsupervised approach I could take? As I said before this is my first real test in ML.
tagged with: classification
tagged with: machine-learning
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/q/48848888
tagged with: list
accepted answer: http://stackoverflow.com/a/48848903
score: 1
type: Question
downvote count: 0
has title: Is there a simpler way to set multiple variables from a list in python?
has body: I am attempting to set variables all at once from a list... This is what I have so far: firstName, lastName, age, email, pin, balance = row[0], row[1], row[2], row[3], row[4], row[5] Is there a simpler way to do this? Something like: firstName, lastName, age, email, pin, balance = row[0, 1, 2, 3, 4, 5] I know that won't work, but I'm just trying to figure out if something like that is possible :)
tagged with: variables
has answer: http://stackoverflow.com/a/48848903
answer count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/a/48957532
downvote count: 0
has comment: http://stackoverflow.com/comment/84930902
type: Answer
has comment: http://stackoverflow.com/comment/84923310
has comment: http://stackoverflow.com/comment/84922279
answers question: http://stackoverflow.com/q/48957450
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84924061
has comment: http://stackoverflow.com/comment/84970455
has body: From the documentation one has: "To disable this behaviour and force NumPy to print the entire array, you can change the printing options using:" import numpy as np np.set_printoptions(threshold='nan')

http://stackoverflow.com/comment/84777748
type: Comment
comment on: http://stackoverflow.com/a/48881395
type: AnswerComment
has text: Well, you can if you want - it will work - but that's not what unit tests are for.
score: 0

unit-testing
tags question: http://stackoverflow.com/q/48935272
tags question: http://stackoverflow.com/q/48892497
tags question: http://stackoverflow.com/q/48831731
tags question: http://stackoverflow.com/q/48933845
tags question: http://stackoverflow.com/q/48881296
tags question: http://stackoverflow.com/q/48819238
tags question: http://stackoverflow.com/q/48853947
tags question: http://stackoverflow.com/q/48842832
tags question: http://stackoverflow.com/q/48911300
tags question: http://stackoverflow.com/q/48837554
tags question: http://stackoverflow.com/q/48805457
tags question: http://stackoverflow.com/q/48864027
type: Tag
tags question: http://stackoverflow.com/q/48917056
tag name: unit-testing
tags question: http://stackoverflow.com/q/48872008
tags question: http://stackoverflow.com/q/48890687
tags question: http://stackoverflow.com/q/48936730
tags question: http://stackoverflow.com/q/48915033
tags question: http://stackoverflow.com/q/48905837
tags question: http://stackoverflow.com/q/48874769

http://stackoverflow.com/a/48880442
score: 29
has comment: http://stackoverflow.com/comment/97273247
upvote count: 29
answers question: http://stackoverflow.com/q/48880314
has comment: http://stackoverflow.com/comment/84765360
accepted answer of: http://stackoverflow.com/q/48880314
has comment: http://stackoverflow.com/comment/84765725
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84765296
downvote count: 0
has comment: http://stackoverflow.com/comment/84765401
type: Answer
has body: All your methods are instance methods. None of them are class methods. The first argument to a method is named self only by convention. You can name it anything you want, and naming it cls instead will not make it a reference to the class. That the first argument is bound to an instance is due to how method lookup works (accessing C.getA_s produces a bound method object, and calling that object causes C to be passed into the original function getA_s), the names of the parameters play no role. In your methods, you are merely referencing instance attributes. That the A attribute is ultimately only defined on the class doesn't matter, you are still accessing that attribute through C.A (where C is the instance you created), not maclass.A. Looking up an attribute on the instance will also find attributes defined on the class if there is no instance attribute shadowing it. To make a method a class method, decorate it with the @classmethod decorator: @classmethod def getA_c(cls): print(cls.A) Now cls will always be a reference to the class, never to the instance. I need to stress again that it doesn't actually matter to Python what name I picked for that first argument, but cls is the convention here as that makes it easier to remind the reader that this method is bound to the class object. Note that if you do this for the getB_c() method, then trying to access cls.B in the method will fail because there is no B attribute on the maclass class object. That's because classmethod wraps the function in a descriptor object that overrides the normal function binding behaviour. It is the descriptor protocol that causes methods to be bound to instances when accessed as attributes on the instance, a classmethod object redirects that binding process. Here is a short demonstration with inline comments, I used the Python convertions for naming classes (using CamelCase), and for instances, attributes, functions and methods (using snake_case): &gt;&gt;&gt; class MyClass(): ... class_att…

http://stackoverflow.com/q/48936548
favorite count: 0
upvote count: 2
tagged with: qgridlayout
has answer: http://stackoverflow.com/a/48936738
tagged with: python
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48936738
has title: Qlabel in front of a QGridLayout
tagged with: pyqt5
type: Question
has body: I am trying to make a QLabel appear over a QGridLayout, but I cannot figure how to do it. This is a sample code: from PyQt5.QtWidgets import QWidget, QApplication, QGridLayout, QFrame, QLabel import sys class Foo(QWidget): def __init__(self): super().__init__() grid_layout = QGridLayout() rect1 = QLabel('RECT1') rect1.setStyleSheet("color: green;") grid_layout.addWidget(rect1, 0, 1) rect2 = QLabel('RECT2') rect2.setStyleSheet("color: blue;") grid_layout.addWidget(rect2, 0, 2) self.setLayout(grid_layout) self.show() app = QApplication(sys.argv) foo = Foo() sys.exit(app.exec_()) which produces the following output: For instance, I want to create another QLabel in red, and display it over them, in the center of the image: red_label = QLabel('red') red_labe.setStyleSheet("font-size:20pt; color: red;"); Something like this: How can I achieve that?
tagged with: qlabel
possible better answer: http://stackoverflow.com/a/48936986
has answer: http://stackoverflow.com/a/48936986
answer count: 2
tagged with: pyqt
downvote count: 0

http://stackoverflow.com/q/48821050
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84675439
has comment: http://stackoverflow.com/comment/84668187
answer count: 0
has comment: http://stackoverflow.com/comment/84671730
has comment: http://stackoverflow.com/comment/84658585
tagged with: fiona
type: Question
has title: change espg from hex shape (which was converted using shapely.wkb.loads)
has comment: http://stackoverflow.com/comment/84647409
has comment: http://stackoverflow.com/comment/84674520
score: 0
tagged with: shapely
tagged with: geopandas
has comment: http://stackoverflow.com/comment/84662697
has comment: http://stackoverflow.com/comment/84671536
has comment: http://stackoverflow.com/comment/84675675
has body: I'm working with a geodataframe called college3 college3 = gpd.GeoDataFrame(pd.read_table('data.txt'),crs = {'init': 'epsg:4269'}) The shape column was originally written in the format: country type color relver shape _imported _dataset uniq_id pop 67 10 1781 1788 166452 Lesley University Art Institute of Boston 700 Beacon Street Boston MA 2215 ... 25025 USA 4-Year, Private 10 1.13.3 0106000020157C01000100000001030000000100000005... 2013-09-24 09:14:10 2013-01-01 00:00:00 d7a43fd5b64ce70481de5e6f057e99f4 480.694851 68 10 1995 2002 165167 Cambridge College Main Campus 1000 Massachusetts Avenue, Suite 31 Cambridge MA 2138 ... 25017 USA 4-Year, Private 0 1.13.3 0106000020157C01000200000001030000000100000005... 2013-09-24 09:14:10 2013-01-01 00:00:00 b57a1f68ea10a72ec9f53fece669f2cb 8942.000000 69 10 1025 1026 166513 University of Massachusetts Lowell UML South 1 Solomont Way Lowell MA 1854 ... 25017 USA NaN 5 1.13.3 0106000020157C01000100000001030000000100000021... 2013-09-24 09:14:10 2013-01-01 00:00:00 a961b9066a579a5d6d56a0e91f3ce1be 10456.345189 70 10 509 509 164924 Boston College Newton Campus 885 Centre Street Newton Centre MA 2459 ... 25017 USA NaN 10 1.13.3 0106000020157C01000100000001030000000100000030... 2013-09-24 09:14:10 2013-01-01 00:00:00 d8f31b0bde7553d795bd68ba697c6b5c 5589.823847 72 10 2160 2167 167376 Northern Essex Community College Main 100 Elliot Street Haverhill MA 1843 ... 25009 USA 2-Year, Public 0 1.13.3 0106000020157C0100010000000103000000010000007F... 2013-09-24 09:14:10 2013-01-01 00:00:00 dc686ca64b68ad0e18137f576caee96a 19264.000000 I converted the hex shape by doing the following: college3['geometry'] = np.nan for i in range(0, len(college3)): college3['geometry'].iloc[i] = shapely.wkb.loads(hex=True,data=college3['shape'].iloc[I]) which yielded a new college3['geometry']: 0 (POLYGON ((1045282.478239882 1257128.653710355... 1 (POLYGON ((1114508.897557752 1243969.445296504... 2 (POLYGON ((1023386.780084164 1265306.580706236... 3 (POLYGON …

http://stackoverflow.com/comment/84641237
comment on: http://stackoverflow.com/q/48818676
score: 0
has text: check you brackets on the line before.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48945066
tagged with: python
score: 2
downvote count: 2
has answer: http://stackoverflow.com/a/48945151
accepted answer: http://stackoverflow.com/a/48945151
type: Question
tagged with: opencv
type: AnsweredQuestion
has body: I am new to opencv and I couldn't find any solution for this problem of mine. I wonder if it is possible to apply erosion/dilation only to a specific portion of an image and let the rest of the image remain as it is originally.
upvote count: 4
answer count: 1
favorite count: 0
has title: Apply erosion to only a portion of an image

scikit-learn
tags question: http://stackoverflow.com/q/48938905
tags question: http://stackoverflow.com/q/48836431
tags question: http://stackoverflow.com/q/48929124
tags question: http://stackoverflow.com/q/48904994
tags question: http://stackoverflow.com/q/48845016
tags question: http://stackoverflow.com/q/48932266
tags question: http://stackoverflow.com/q/48925311
tags question: http://stackoverflow.com/q/48902767
tags question: http://stackoverflow.com/q/48840360
tags question: http://stackoverflow.com/q/48948319
tags question: http://stackoverflow.com/q/48912695
tags question: http://stackoverflow.com/q/48843578
tags question: http://stackoverflow.com/q/48925747
tags question: http://stackoverflow.com/q/48917781
tags question: http://stackoverflow.com/q/48859767
tags question: http://stackoverflow.com/q/48962346
tags question: http://stackoverflow.com/q/48817300
tags question: http://stackoverflow.com/q/48817949
tags question: http://stackoverflow.com/q/48826891
tags question: http://stackoverflow.com/q/48886477
tags question: http://stackoverflow.com/q/48936542
tags question: http://stackoverflow.com/q/48873321
tags question: http://stackoverflow.com/q/48865972
tags question: http://stackoverflow.com/q/48872742
tags question: http://stackoverflow.com/q/48874610
tags question: http://stackoverflow.com/q/48808985
tags question: http://stackoverflow.com/q/48816458
tags question: http://stackoverflow.com/q/48880557
tags question: http://stackoverflow.com/q/48869343
tags question: http://stackoverflow.com/q/48887096
tags question: http://stackoverflow.com/q/48856595
tags question: http://stackoverflow.com/q/48820601
tags question: http://stackoverflow.com/q/48807374
tags question: http://stackoverflow.com/q/48853484
tags question: http://stackoverflow.com/q/48941548
tags question: http://stackoverflow.com/q/48929377
tags question: http://stackoverflow.com/q/48894219
tags question: http://stackoverflow.com/q/48871652
tags question: http://stackoverflow.com/q/48830989
tags question: http://stackoverflow.com/q/48817095
tags question: http://stackoverflow.com/q/48877846
tags question: http://stackoverflow.com/q/48939305
tags question: http://stackoverflow.com/q/48924970
tags question: http://stackoverflow.com/q/48909334
tags question: http://stackoverflow.com/q/48890866
tags question: http://stackoverflow.com/q/48901691
tags question: http://stackoverflow.com/q/48948209
tags question: http://stackoverflow.com/q/48831851
tags question: http://stackoverflow.com/q/48811807
tags question: http://stackoverflow.com/q/48839149
tags question: http://stackoverflow.com/q/48855290
tags question: http://stackoverflow.com/q/48901491
tags question: http://stackoverflow.com/q/48870380
tag name: scikit-learn
tags question: http://stackoverflow.com/q/48819346
tags question: http://stackoverflow.com/q/48842143
tags question: http://stackoverflow.com/q/48857864
tags question: http://stackoverflow.com/q/48832925
tags question: http://stackoverflow.com/q/48810310
tags question: http://stackoverflow.com/q/48880849
type: Tag
tags question: http://stackoverflow.com/q/48811817
tags question: http://stackoverflow.com/q/48914360
tags question: http://stackoverflow.com/q/48834722
tags question: http://stackoverflow.com/q/48909832
tags question: http://stackoverflow.com/q/48809878
tags question: http://stackoverflow.com/q/48826588
tags question: http://stackoverflow.com/q/48911300
tags question: http://stackoverflow.com/q/48909418
tags question: http://stackoverflow.com/q/48891875
tags question: http://stackoverflow.com/q/48877919
tags question: http://stackoverflow.com/q/48954453
tags question: http://stackoverflow.com/q/48832836
tags question: http://stackoverflow.com/q/48856766
tags question: http://stackoverflow.com/q/48878188
tags question: http://stackoverflow.com/q/48867788
tags question: http://stackoverflow.com/q/48884782
tags question: http://stackoverflow.com/q/48929072
tags question: http://stackoverflow.com/q/48852824
tags question: http://stackoverflow.com/q/48956252

http://stackoverflow.com/comment/84663183
type: QuestionComment
has text: This sounds so specific to your case, I'm having a hard time knowing how I would figure this out without stepping through the debugger with the site right in front of me. It probably has something to do with how the website itself is functioning, which I'm sure is hard to put details about here.
comment on: http://stackoverflow.com/q/48814291
score: 0
type: Comment

http://stackoverflow.com/q/48931887
score: 1
has comment: http://stackoverflow.com/comment/88957165
tagged with: numpy
upvote count: 1
answer count: 1
tagged with: aws-lambda
favorite count: 0
has body: Am trying to run a function in AWS Lambda (Python 3.6) from a Zip file, located in S3. Followed the instructions in various locations (AWS documentation, other blogs, etc.). However, I seem to be going wrong somewhere while loading numpy. Can some one please help with the same? Here is the Zip file I uploaded to S3 - ZIP file Also, the Error logs return the following, when I test the zip - START RequestId: b004d192-17e7-11e8-8323-bb9e005088cc Version: $LATEST Unable to import module 'trial22': Importing the multiarray numpy extension module failed. Most likely you are trying to import a failed build of numpy. If you're working with a numpy git repo, try `git clean -xdf` (removes all files not under version control). Otherwise reinstall numpy. Original error was: cannot import name 'multiarray' END RequestId: b004d192-17e7-11e8-8323-bb9e005088cc REPORT RequestId: b004d192-17e7-11e8-8323-bb9e005088cc Duration: 0.84 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 31 MB On trying to uninstall (&amp; then install) numpy, the virtualenv attempts to remove the global package, instead of the one in the specific directory where it is created. Not uninstalling numpy at /Users/vidyut/projects/aws_lambda_pkgs/trial22, outside environment /Users/vidyut/projects/aws_lambda_pkgs/trial21/bin/.. I know I am making some stupid mistake somewhere, but simply cannot figure out what and where - can some one please help explain the same?
has title: Zipped package (with numpy) for AWS Lambda not working
tagged with: python
tagged with: http://stackoverflow.com/tag/zip
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/51183358
type: Question
tagged with: amazon-s3

hdfs
tags question: http://stackoverflow.com/q/48923946
tag name: hdfs
type: Tag
tags question: http://stackoverflow.com/q/48897340

time
tags question: http://stackoverflow.com/q/48809812
tags question: http://stackoverflow.com/q/48891742
tag name: time
tags question: http://stackoverflow.com/q/48817847
tags question: http://stackoverflow.com/q/48810440
type: Tag
tags question: http://stackoverflow.com/q/48814788

http://stackoverflow.com/comment/103907902
comment on: http://stackoverflow.com/a/48897046
type: Comment
has text: I want to use Xception concept to code it from scratch it that possible, can you please show me the sample code
score: 0
type: AnswerComment

http://stackoverflow.com/comment/102171260
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49073626
type: Comment
has text: Which one is the most up-to-date? I.e. where are the most recent developments made first; in Keras or tf.keras?

http://stackoverflow.com/q/48962424
tagged with: paramiko
has comment: http://stackoverflow.com/comment/84936194
score: 3
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/99111641
has comment: http://stackoverflow.com/comment/84933449
favorite count: 0
linked to: http://stackoverflow.com/q/40090445
type: Question
has title: Paramiko invoke_shell() returns command text and not results
tagged with: python
has body: Problem: error with ssh.exec_command : Extra params found in CLI, this is not supported, exiting the CLI session. It's a Cisco box with limited ssh functionality/dumb terminal support only. Seems like the solution: Link with my exact issue, but not working for me: paramiko.exec_command() not executing and returns "Extra params found in CLI" My code: import paramiko ssh = paramiko.SSHClient() ssh.load_system_host_keys() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect('my host', username='admin', password='pass') #stdin, stdout, stderr = ssh.exec_command("show version") #print(stdout.readlines()) chan = ssh.invoke_shell() chan.sendall('show version\r') s = chan.recv(4096) print s ssh.close() Output: root@salt01-master tmp]# python ssh_cimc.py show version Just the command itself, no sort of return value. If I point the script to a regular linux box and use uptime or ifconfig, I'm still getting the text output of the command and not results.
has comment: http://stackoverflow.com/comment/84932226
upvote count: 3
has comment: http://stackoverflow.com/comment/84933589
type: UnansweredQuestion

http://stackoverflow.com/q/48883647
has body: I stumbled upon the following code: import re regex_compiled = re.compile('\d{2}-\d{3,5}') res = re.search(regex_compiled, '12-9876') I was under impression that re.search attempts to compile the first parameter which is already compiled so it should error or regex_compiled.__repr__() or regex_compiled.__str__() should be called just before a repeated attempt to compile it! Just to be sure I compared it with regex_compiled.search(...: &gt;&gt;&gt; from timeit import timeit &gt;&gt;&gt; timeit("import re; regex_compiled = re.compile('\d{2}-\d{3,5}'); res = re.search(regex_compiled, '12-9876')") 1.3797054840251803 &gt;&gt;&gt; timeit("import re; regex_compiled = re.compile('\d{2}-\d{3,5}'); res = regex_compiled.search('12-9876')") 0.7649686150252819 &gt;&gt;&gt; I am very puzzled from where so substantial difference comes from given that debugging into re.search (in both CPython v. 2 and v. 3) shows that the compiled pattern is reused! I hope someone can help shed some light on this. Execution environment: Ubuntu 16.04, 64b
has comment: http://stackoverflow.com/comment/84772166
tagged with: python-2.7
upvote count: 3
has title: Reusing compiled regex in re.search
tagged with: regex
downvote count: 0
has answer: http://stackoverflow.com/a/48884734
accepted answer: http://stackoverflow.com/a/48884734
tagged with: python
type: AnsweredQuestion
score: 3
type: Question
tagged with: python-3.5
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84757818
has text: The error log you posted shows a permission error when trying to create a directory. Are you having a different error when trying with `sudo`?
type: AnswerComment
comment on: http://stackoverflow.com/a/48876778
score: 0
type: Comment

http://stackoverflow.com/q/48904495
favorite count: 0
has comment: http://stackoverflow.com/comment/138961639
tagged with: python
tagged with: python-3.x
has title: In Python 3, requests.get() gives incomplete json response
has body: I am trying to get data using requests.get(). And the response data is large(containing 10000 mongodb records). But the response I get is almost always broken. Very few times I got the correct result. Example: Should be like this: [ { "_id":"5a72c839c634133e1e9ab502", "data":{"today_wh":13500}, "dts":"2018-02-01T07:56:31.000Z", "ts":1517471791 }, { "_id":"5a72c839c634133e1e9ab503", "data":{"today_wh":13500}, "dts":"2018-02-01T07:57:06.000Z", "ts":1517471826 } ] Comes like this: [ { "_id":"5a72c8ecc634133e1e9ab51b", "data":{"today_wh":13700}, "dts":"2018-02-01T08:00:01.000Z", "ts":1517472001 }, { "_id": What to do to get the whole result?
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48904626
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84814581
downvote count: 1
type: Question
upvote count: 5
has comment: http://stackoverflow.com/comment/138951403
answer count: 1
has comment: http://stackoverflow.com/comment/111527449
score: 4

http://stackoverflow.com/a/48848761
downvote count: 0
has body: First, create a column with shifted values from 'observed_column' (or whatever name you have on your dataset): df['shifted_column'] = df['observed_column'].shift(1) Second, create a column with the difference between current value ('observed_column') and last line value ('shifted_column'): df['difference'] = df['observed_column'] - df['shifted_column'] Third, get absolute values to measure change (doesn't seem necessary to your problem, but just in case): df['difference'] = df['difference'].abs() Fourth, compute the statistics: average = df['difference'].mean() maximum = df['difference'].max() minimum = df['difference'].min()
type: Answer
has comment: http://stackoverflow.com/comment/84711108
score: 1
has comment: http://stackoverflow.com/comment/84701896
upvote count: 1
answers question: http://stackoverflow.com/q/48847210

http://stackoverflow.com/q/48850731
favorite count: 0
has answer: http://stackoverflow.com/a/48850871
has title: Apache 2 run '*.py' by python 2
type: UnansweredQuestion
tagged with: python
downvote count: 1
type: Question
upvote count: 0
tagged with: apache
score: -1
tagged with: ubuntu
has body: I have a error with import some libraries in my python script. This made for python 3 and good work in Terminal. But when I try to start this script by web server (Apache 2) I have error with "cannot import name 'ImageTk'". I think Apache start this script by python 2, but wrote to start by python 3. Could you help me? Here code: #!/usr/bin/env python3 import json import cgi import cgitb import os from PIL import Image, ImageTk cgitb.enable() print('Content-type: application/json\n\n') res = json.dumps({'age': 0, 'pol': '0', 'status': 0}) print(res) Here error from log: ImportError: cannot import name 'ImageTk'
answer count: 1

http://stackoverflow.com/comment/84850107
comment on: http://stackoverflow.com/a/48910328
score: 0
type: AnswerComment
has text: Thanks, moving the initialization operation inside the loop did the trick indeed. Then, the first value returned is the previous value of the averaged accuracy (therefore, it is equal to `0.0` after re-initialization). Still not sure why someone would need that instead of the actual value of the accuracy though. As a note, `tf.contrib.metrics.accuracy` seems to be [deprecated](https://www.tensorflow.org/versions/r1.6/api_docs/python/tf/contrib/metrics/streaming_accuracy)
type: Comment

http://stackoverflow.com/comment/84902543
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48947591
type: Comment
has text: @Universalis I updated my answer. A GPU will just make training faster. It won't affect accuracy.

http://stackoverflow.com/comment/84731526
comment on: http://stackoverflow.com/a/48832772
type: Comment
has text: I updated my answer @mohamadrezach. That old code would work on a ONE TO ONE field type.... try it now
type: AnswerComment
score: 0

http://stackoverflow.com/a/48937094
score: 0
has body: check if You connected the right pins You are not reading upload_mission = GPIO.input(23) in while. You just read it once before and then not You need: upload_mission = GPIO.input(23) execute_mission = GPIO.input(24) while(1): upload_mission = GPIO.input(23) execute_mission = GPIO.input(24) if execute_mission == True: print 'x' if upload_mission == True: subprocess.call(["node", "/home/pi/QRIDrone/RPIBuild/updateMission.js"], shell=False
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84881581
type: Answer
answers question: http://stackoverflow.com/q/48936975
accepted answer of: http://stackoverflow.com/q/48936975

http://stackoverflow.com/q/48886761
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84814550
has comment: http://stackoverflow.com/comment/84814481
linked to: http://stackoverflow.com/q/36314797
possible better answer: http://stackoverflow.com/a/68806012
has comment: http://stackoverflow.com/comment/84814516
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/68806012
has answer: http://stackoverflow.com/a/72708300
has body: I'm trying to upload a pandas.DataFrame to Google Big Query using the pandas.DataFrame.to_gbq() function documented here. The problem is that to_gbq() takes 2.3 minutes while uploading directly to Google Cloud Storage takes less than a minute. I'm planning to upload a bunch of dataframes (~32) each one with a similar size, so I want to know what is the faster alternative. This is the script that I'm using: dataframe.to_gbq('my_dataset.my_table', 'my_project_id', chunksize=None, # I have tried with several chunk sizes, it runs faster when it's one big chunk (at least for me) if_exists='append', verbose=False ) dataframe.to_csv(str(month) + '_file.csv') # the file size its 37.3 MB, this takes almost 2 seconds # manually upload the file into GCS GUI print(dataframe.shape) (363364, 21) My question is, what is faster? Upload Dataframe using pandas.DataFrame.to_gbq() function Saving Dataframe as CSV and then upload it as a file to BigQuery using the Python API Saving Dataframe as CSV and then upload the file to Google Cloud Storage using this procedure and then reading it from BigQuery Update: Alternative 1 seems faster than Alternative 2 , (using pd.DataFrame.to_csv() and load_data_from_file() 17.9 secs more in average with 3 loops): def load_data_from_file(dataset_id, table_id, source_file_name): bigquery_client = bigquery.Client() dataset_ref = bigquery_client.dataset(dataset_id) table_ref = dataset_ref.table(table_id) with open(source_file_name, 'rb') as source_file: # This example uses CSV, but you can use other formats. # See https://cloud.google.com/bigquery/loading-data job_config = bigquery.LoadJobConfig() job_config.source_format = 'text/csv' job_config.autodetect=True job = bigquery_client.load_table_from_file( source_file, table_ref, job_config=job_config) job.result() # Waits for job to complete print('Loaded {} rows into {}:{}.'.format( job.output_rows, dataset_id, table_id))
tagged with: google-bigquery
tagged with: google-cloud-storage
tagged with: google-cloud-python
type: Question
has answer: http://stackoverflow.com/a/49033607
accepted answer: http://stackoverflow.com/a/49033607
has title: Efficiently write a Pandas dataframe to Google BigQuery
has comment: http://stackoverflow.com/comment/84814922
has comment: http://stackoverflow.com/comment/84783008
score: 45
answer count: 3
tagged with: pandas
downvote count: 1
upvote count: 46

http://stackoverflow.com/q/48847564
upvote count: 1
downvote count: 1
has body: I have already written out my code but I keep getting an error message on if personsAge &gt;= 1. Here is the error: type error >= not supported between instances of 'str' and 'int' This happens everytime I run my program. I am not sure what I'm doing wrong. Any help is much appreciated. Here is my code: # Purpose ''' This program classifies a person to a certain group based on their age''' #================================================================================= # Initialize variables(used for processing data) ageGroup =""; #specify data as empty string personsAge =""; #specify data as float /real #==================================================================================== # Input Statements fullName = str(input("&lt;Enter your full name&gt;")); personsAge = str(input("&lt;Enter your age&gt;")); #========================================================================== '''nested if statements to determine a person's age group.''' # Using the Nested If eliminates the need to check all if statements # Once the criteria has been met, control is transferred to the statement # following the last if Statement. However, the IF/ELSE must be aligned in same column if (personsAge &lt;=1) and (personsAge &gt;0): ageGroup = "Infant."; elif (personsAge &gt;=1) and (personsAge &lt;=13): ageGroup = "Child."; elif (personsAge &gt;=13) and (personsAge &lt;=20): ageGroup = "Teenager."; elif (personsAge &gt;=20): ageGroup = "Adult."; #==================================================================================== #Output Statements print(); print("My name is " + fullName); print("My age is " + personsAge); #================================================================= # Print Age group print(fullName + "is an " + ageGroup); print("=" * 80); #=============================================================================== #End program
has comment: http://stackoverflow.com/comment/84699204
has comment: http://stackoverflow.com/comment/84699173
type: Question
linked to: http://stackoverflow.com/q/41950021
has title: type error >= not supported between instances of 'str' and 'int'
has comment: http://stackoverflow.com/comment/84699211
answer count: 1
has answer: http://stackoverflow.com/a/48847606
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/84699200
has comment: http://stackoverflow.com/comment/84699180
tagged with: python
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/84699222

http://stackoverflow.com/q/48913556
tagged with: argparse
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84834003
has comment: http://stackoverflow.com/comment/84833635
has comment: http://stackoverflow.com/comment/84833595
type: Question
score: 3
linked to: http://stackoverflow.com/q/9366369
has answer: http://stackoverflow.com/a/64894725
has comment: http://stackoverflow.com/comment/84833692
upvote count: 3
has title: python argparse: name of argument not displayed in help menu, if choices attr supplied
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84833830
has body: When using argparse in python 3.6, I've noticed that if I supply the 'choices' attr when adding one of the arguments, then in the help menu's section for that argument, the list of choices themselves show up rather than the name of the argument. Using this stackoverflow answer Python argparse: Lots of choices results in ugly help output, I found to use the 'metavar' and 'numargs' attrs to try and clean up the help menu. While this gets rid of the ugly choices being displayed as a hash, the name of the option still does not display at all in help. Example... This: import argparse parser = argparse.ArgumentParser() parser.add_argument("works", type=int, help="Shows up properly") parser.add_argument("nope", type=int, choices=[1,2,3], help="foobared") parser.add_argument("nope2", type=int, choices=[1,2,3], nargs='?', metavar='', help="still foobared") parser.add_argument("why", type=int, help="help me") parser.parse_args() Results in this help output: $ python myparser.py --help usage: myparser.py [-h] works {1,2,3} why positional arguments: works Shows up properly {1,2,3} foobared still foobared why help me optional arguments: -h, --help show this help message and exit This has to be simple... Can someone please advise me where I'm going wrong?

http://stackoverflow.com/comment/84698078
comment on: http://stackoverflow.com/q/48847018
type: QuestionComment
type: Comment
has text: `args` is a tuple
score: 4

http://stackoverflow.com/q/48909789
has body: I am trying to output formset as a result of another form submission on the same page. This formset contains forms that should be submitted too. Here is my func view: def manage_articles(request): dyn_form = type('DynForm', (forms.BaseForm,), {'base_fields': {'title': forms.CharField(), 'name': forms.CharField()}}) form = ArticleForm() formset = formset_factory(dyn_form, extra=4) if request.method == 'POST': form = ArticleForm(request.POST) formset = formset(request.POST, request.FILES) if formset.is_valid(): print('Formset sent') if form.is_valid(): return render(request, 'test_form.html', {'formset': formset, 'form':form}) else: return render(request, 'test_form.html', {'form':form, 'formset': ''}) Here is my basic form: class ArticleForm(forms.Form): author = forms.CharField() Currently, I get an error when I submit the first form: ['ManagementForm data is missing or has been tampered with'] How can I do that?
downvote count: 0
has comment: http://stackoverflow.com/comment/85076547
favorite count: 0
has comment: http://stackoverflow.com/comment/84828503
type: UnansweredQuestion
has title: How can I output formset as a result of submition of another form?
tagged with: django
upvote count: 1
tagged with: python
answer count: 0
tagged with: formset
score: 1
tagged with: django-forms
has comment: http://stackoverflow.com/comment/84856217
type: Question
has comment: http://stackoverflow.com/comment/84853370

http://stackoverflow.com/q/48816718
has body: I'm running into a memory error when trying to evaluate a function at a number of points and store in an array. I've read a few other posts about similar issues and I don't think that I am exceeding the memory limits of my system: total used free shared buff/cache available Mem: 131898384 8964068 122074628 15128 859688 121905868 Swap: 14648316 1001760 13646556 and also MemTotal: 131898384 kB MemFree: 75056308 kB MemAvailable: 74889296 kB The error message is: PDF= np.zeros([T,Y]) MemoryError My code is: Y=40000 T = 200000 tmin = 0 timestep = 10 tmax = timestep*T TD_Psi = np.zeros([T,Y],'complex') t = np.linspace(tmin, tmax, T) for j in range(T): for i in range(M): TD_Psi[j] = TD_Psi[j] + c[i]*MO_basis[i]*np.exp(-evals[i]*t[j]*1j) PDF= np.zeros([T,Y]) for time in range(T): PDF[time] = np.real(np.conjugate(TD_Psi[time])*TD_Psi[time]) I'm not sure if the problem is in my code or my system and what I can do to resolve this issue. It runs up until T = 150000 before giving me the error. Thank you very much for your help.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48816807
has comment: http://stackoverflow.com/comment/84637560
type: Question
tagged with: numpy
answer count: 2
possible better answer: http://stackoverflow.com/a/74809558
tagged with: arrays
has answer: http://stackoverflow.com/a/74809558
score: 0
has title: Memory Error Python Numpy Array
accepted answer: http://stackoverflow.com/a/48816807
tagged with: python

http://stackoverflow.com/q/48817141
type: Question
accepted answer: http://stackoverflow.com/a/48821753
has comment: http://stackoverflow.com/comment/84644506
downvote count: 0
has comment: http://stackoverflow.com/comment/84638288
tagged with: string
has comment: http://stackoverflow.com/comment/84639178
has body: Assuming we have a certain number of possible strings: possible_strings_list = ['foo', 'bar', 'baz', 'qux', 'spam', 'ham', 'eggs'] and receive new strings that are known to be one of them. We want to assign an integer to every new string, for example if new_string == 'foo': return 0 elif new_string == 'bar': return 1 ... What is the fastest way to do that in Python 3.6? I tried several ways and using a dictionary is the fastest so far: list_index 2.7494255019701086 dictionary 0.9412809460191056 if_elif_else 2.10705983400112 lambda_function 2.6321219780365936 tupple_index 2.751029207953252 ternary 1.931659944995772 np_where 15.610908019007184 However I am more or less a Python newbie and I'm interested if there are other and faster solutions. Do you have any suggestions? My complete testig code: import timeit import random import numpy as np def list_index(i): return(possible_strings_list.index(i)) def dictionary(i): return possible_strings_dict[i] def tupple_index(i): return possible_strings_tup.index(i) def if_elif_else(i): if i == 'foo': return 1 elif i == 'bar': return 2 elif i == 'baz': return 3 elif i == 'qux': return 4 elif i == 'spam': return 5 elif i == 'ham': return 6 elif i == 'eggs': return 7 def ternary(i): return 0 if i == 'foo' else 1 if i == 'baz' else 2 if i == 'bar' else 3 if i == 'qux' else 4 if i == 'spam'else 5 if i == 'ham' else 6 n = lambda i: 0 if i == 'foo' else 1 if i == 'baz' else 2 if i == 'bar' else 3 if i == 'qux' else 4 if i == 'spam'else 5 if i == 'ham' else 6 def lambda_function(i): return n(i) def np_where(i): return np.where(possible_strings_array == i)[0][0] ## def check(function): for i in testlist: function(i) possible_strings_list = ['foo', 'bar', 'baz', 'qux', 'spam', 'ham', 'eggs'] testlist = [random.choice(possible_strings_list) for i in range(1000)] possible_strings_dict = {'foo':0, 'bar':1, 'baz':2, 'qux':3, 'spam':4, 'ham':5, 'eggs':6} possible_strings_tup = ('foo', 'bar', 'baz', 'qux', 'spam', 'ham', 'eggs') allfunctions …
tagged with: optimization
has comment: http://stackoverflow.com/comment/84640012
has comment: http://stackoverflow.com/comment/84638952
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84638387
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84638368
has answer: http://stackoverflow.com/a/48821753
has comment: http://stackoverflow.com/comment/84638296
has comment: http://stackoverflow.com/comment/84639019
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84639540
score: 10
has title: Fastest way to perform string lookups?
upvote count: 10
has comment: http://stackoverflow.com/comment/84644670

http://stackoverflow.com/comment/84723902
comment on: http://stackoverflow.com/q/48860378
has text: Possible duplicate of [Get class that defined method](https://stackoverflow.com/questions/961048/get-class-that-defined-method)
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/q/48911602
has answer: http://stackoverflow.com/a/48912198
has comment: http://stackoverflow.com/comment/84829642
accepted answer: http://stackoverflow.com/a/48911970
has title: Python 3 Concat Single Byte with String Bytes
tagged with: byte
possible better answer: http://stackoverflow.com/a/48912198
has comment: http://stackoverflow.com/comment/84829914
linked to: http://stackoverflow.com/q/59520331
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84830236
has comment: http://stackoverflow.com/comment/84830100
type: Question
has answer: http://stackoverflow.com/a/48911970
has body: I need to concat a single byte with the bytes I get from a parameter string. byte_command = 0x01 socket.send(byte_command + bytes(message, 'UTF-8')) but I get this error: socket.send(byte_command + bytes(message, 'UTF-8')) TypeError: str() takes at most 1 argument (2 given) I assume this happens because I am using the string concat operator - how do I resolve that?
answer count: 2

http://stackoverflow.com/comment/84841343
type: Comment
comment on: http://stackoverflow.com/q/48917405
type: QuestionComment
has text: When you split the string, it creates a new list, it does not mutate the string to a list if that is what you fear. Why do you want to avoid split?
score: 0

sublist
tags question: http://stackoverflow.com/q/48896964
tag name: sublist
tags question: http://stackoverflow.com/q/48953042
tags question: http://stackoverflow.com/q/48946896
type: Tag
tags question: http://stackoverflow.com/q/48879615

weather
tags question: http://stackoverflow.com/q/48913271
tags question: http://stackoverflow.com/q/48816331
tag name: weather
type: Tag

http://stackoverflow.com/comment/84856671
score: 0
comment on: http://stackoverflow.com/a/48913857
type: Comment
has text: That is not what I want. I want to to match any nouns, not only predefined ones.
type: AnswerComment

http://stackoverflow.com/comment/84781048
has text: I was wondering if I could take advantage of the fact that s1 is actually a grid of coordinates, and there really is no need to try and compare elements of s2 with each element of s1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48887912
score: 0

http://stackoverflow.com/comment/138761199
comment on: http://stackoverflow.com/a/78687008
score: 1
type: AnswerComment
has text: have similar unexpected behavior. Python 3.11 on macos 14.3.1. `open( "myfile", "w") ` fails with error file not found, unless file path is either only file name or is absolute file path. Any other relative file path causes error `FileNotFoundError: [Errno 2] No such file or directory: ...`
type: Comment

http://stackoverflow.com/a/48827113
type: Answer
has body: The html comment tag &lt;!-- ... --&gt; does not work in a jinja template. For commenting use the jinja comment tag ie, {# ... #}
upvote count: 22
downvote count: 0
score: 22
answers question: http://stackoverflow.com/q/48825486

http://stackoverflow.com/q/48820940
score: 0
tagged with: snpe
answer count: 1
has comment: http://stackoverflow.com/comment/84645822
type: UnansweredQuestion
tagged with: android
tagged with: python
has answer: http://stackoverflow.com/a/49233411
tagged with: tensorflow
has title: how to download and convert a pre-trained "inception_v3" example in Tensorflow format:?
type: Question
has comment: http://stackoverflow.com/comment/84647189
has comment: http://stackoverflow.com/comment/84646537
has comment: http://stackoverflow.com/comment/84645639
has comment: http://stackoverflow.com/comment/84645805
has body: I am just starting to use tensor flow while downloading ML fileby using python API and I am getting the below error "C:\Users\IVISSW\Desktop\snpe-1.12.0> python ./models/inception_v3/scripts/setup_inceptionv3.py -a ./temp-assets-cache -d File "./models/inception_v3/scripts/setup_inceptionv3.py", line 159 except Exception, err: ^ SyntaxError: invalid syntax" Is there any solution for that, I tried lots of stuff but could not find any suitable solution. I am following this tutorial
has comment: http://stackoverflow.com/comment/84649887

http://stackoverflow.com/comment/84647844
has text: Of course, I can, but the same problem occurs for both cases. And the dictionary is more for demonstration rather than the actual case. And there are some functions in my actual dictionary must be expressed in the lambda expression.
comment on: http://stackoverflow.com/q/48822166
type: QuestionComment
score: 0
type: Comment

http://stackoverflow.com/comment/84684259
type: AnswerComment
type: Comment
score: 1
has text: Thanks for your answer, I'd upvote it if I had enough reputation! That was precisely the problem. :)
comment on: http://stackoverflow.com/a/48839703

http://stackoverflow.com/a/48849830
accepted answer of: http://stackoverflow.com/q/48845016
type: Answer
upvote count: 2
has body: Your python process is being killed by the Linux Kernel's OOM killer, as the system is out of memory and python is requesting more. Since you are doing cross-validation, I assume you are also using TensorFlow as backend, and in that case it is possible that its a bug in Keras/TF as the session isn't cleared. More information in https://github.com/keras-team/keras/issues/2102 A quick solution would be to use keras.backend.clear_session after each CV iteration. If you are not using the TF backend, then its probably a bug in your own code.
score: 2
answers question: http://stackoverflow.com/q/48845016
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84628094
type: AnswerComment
score: 0
has text: Yes, exactly. The goal is to distribute this variable as evenly as possible.
type: Comment
comment on: http://stackoverflow.com/a/48809945

http://stackoverflow.com/comment/84726734
has text: @Tomalak Thats why it is a comment and not an answer. Suggestions for standard debugging are totally legitimate here. Also, we don't see a link of proof for your "stated as fact" claim "Quick Edit Mode is a feature of Windows console emulator". Make sure you hold self-proclaimed standards yourself first.
type: QuestionComment
comment on: http://stackoverflow.com/q/48861268
type: Comment
score: 0

http://stackoverflow.com/comment/84647231
score: 0
type: Comment
has text: Sorry but it does not work. There are two errors. First, when I try to delete rows with "-" button, it does not work> Second, it does not inserts value in every entry under cost/m2.
comment on: http://stackoverflow.com/a/48818695
type: AnswerComment

http://stackoverflow.com/q/48874874
has title: Python Beautiful Soup only scraping the lower part of the page
has answer: http://stackoverflow.com/a/49682573
downvote count: 0
answer count: 1
favorite count: 0
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/84754011
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84769883
tagged with: python
has comment: http://stackoverflow.com/comment/84753983
upvote count: 3
has comment: http://stackoverflow.com/comment/84756535
tagged with: web-scraping
has body: I'm trying to pull product info from a rather large apparel website page, but soup only appears to scrape a lower half of the html document, at an arbitrary cutoff, so the data that I'm interested in is not actually in my soup. I've tried it on another website and it worked fine, so I assume it's website specific. Here's my code: from bs4 import BeautifulSoup import requests r = requests.get("https://www.pullandbear.com/rs/man/sale-c1030036006.html") soup = BeautifulSoup(r.content, "html.parser") print(soup.prettify())
has comment: http://stackoverflow.com/comment/84753754
type: Question
has comment: http://stackoverflow.com/comment/84755839
score: 3
has comment: http://stackoverflow.com/comment/84753661

http://stackoverflow.com/q/48822537
tagged with: python
has comment: http://stackoverflow.com/comment/84648338
type: AnsweredQuestion
has title: How does this Python function work?
score: 0
has answer: http://stackoverflow.com/a/48822557
type: Question
has body: I'm going through an MIT open courseware class right now for Python, and I'm not understanding how this function is returning 9. def a(x): ''' x: int or float. ''' return x + 1 a(a(a(6))) The above returns 9. I've went through it step by step using pythontutor (Visualize Python) and I'm still not understanding. I understand the function. It has a name of a, and takes one argument, x. If I did a(6) I'd expect 7 to be returned. It's the a(a(a(6))) that confuses me - all of the a's and parentheses. How is this working? Maybe a step by step sequence of what each a means, etc. Based from your replies, is this what you mean?
accepted answer: http://stackoverflow.com/a/48822557
tagged with: function
has comment: http://stackoverflow.com/comment/84648401
has comment: http://stackoverflow.com/comment/84648387
has comment: http://stackoverflow.com/comment/84648440
answer count: 1
has comment: http://stackoverflow.com/comment/84648351

http://stackoverflow.com/q/48917447
possible better answer: http://stackoverflow.com/a/65975123
accepted answer: http://stackoverflow.com/a/49995860
downvote count: 0
tagged with: deep-learning
type: AnsweredQuestion
tagged with: python
tagged with: object-detection
score: 1
has title: Tensorflow object detection API: output boxes for probability less than 50%
favorite count: 0
type: Question
answer count: 2
has body: I am referring to Tensorflow Object Detection API (https://github.com/tensorflow/models/tree/master/research/object_detection): Heres the IPython notebook for the detection code I am using (https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb). In this file the output values are set to draw boxes for probability greater than 50% Detection code: with detection_graph.as_default(): with tf.Session(graph=detection_graph) as sess: # Definite input and output Tensors for detection_graph image_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Each box represents a part of the image where a particular object was detected. detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represent how level of confidence for each of the objects. # Score is shown on the result image, together with the class label. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0') #myFile = open('example2.csv', 'w') i=0 #boxeslist=[] new_boxes = [] for image_path in TEST_IMAGE_PATHS: image = Image.open(image_path) # the array based representation of the image will be used later in order to prepare the # result image with boxes and labels on it. image_np = load_image_into_numpy_array(image) # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) # Actual detection. (boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict={image_tensor: image_np_expanded}) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates=True, li…
has answer: http://stackoverflow.com/a/49995860
tagged with: machine-learning
upvote count: 1
has answer: http://stackoverflow.com/a/65975123
tagged with: tensorflow

http://stackoverflow.com/a/48950316
score: 1
has comment: http://stackoverflow.com/comment/84922308
accepted answer of: http://stackoverflow.com/q/48948520
downvote count: 0
answers question: http://stackoverflow.com/q/48948520
type: AcceptedAnswer
has body: Try this. It will fetch you the tabular data from that site. from bs4 import BeautifulSoup import requests URL = "https://finance.google.com/finance?q=NASDAQ:{}&amp;fstype=ii" def Get_Table(ticker): response = requests.get(URL.format(ticker)) soup = BeautifulSoup(response.text,"lxml") table = soup.select_one("#fs-table") for items in table.select(" tr"): data = [' '.join(item.text.split()) for item in items.select("th,td")] print(data) if __name__ == '__main__': for tckr in ['SBUX','MSFT','AAPL']: Get_Table(tckr)
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84911515
has text: While it is a good idea to form a cartesian product of the indices, this approach would still end up forming the intermediate array, thus not solving the memory issue because it will not fit.
type: Comment
comment on: http://stackoverflow.com/a/48888541
type: AnswerComment
score: 0

http://stackoverflow.com/q/48954479
tagged with: oauth-2.0
has comment: http://stackoverflow.com/comment/84916100
type: Question
has comment: http://stackoverflow.com/comment/84937432
has title: python How do i store the [code] in url/code=xxx so i can pass it to a function
tagged with: function
score: 0
tagged with: variables
tagged with: foursquare
type: UnansweredQuestion
tagged with: python
has body: Halo Devs. I want to get an Foursquare access_token. Foursquare sends a code in this formart: 'http://www.example.net/auth?code=Z0NJ55C4BUX4DIMNCHRSVSIIPBEBD4TGOD45J3IZNVNVAIFZ#=' I want to store the code parameter value so i may exchange the code I got for an access token. What code can i use to save the code parameter in a variable? Here are the instructions by Foursquare: https://developer.foursquare.com/docs/api/configuration/authentication
answer count: 0

pipeline
type: Tag
tags question: http://stackoverflow.com/q/48925332
tags question: http://stackoverflow.com/q/48813968
tags question: http://stackoverflow.com/q/48925311
tag name: pipeline
tags question: http://stackoverflow.com/q/48909334

http://stackoverflow.com/a/48884154
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48883784
has body: I think you need first add NaNs and then this solution: N = 3 x = np.concatenate([[np.nan] * (N-1), df['temperature'].values]) def rolling_window(a, window): shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) print (rolling_window(x, N)) [[ nan nan 0. ] [ nan 0. 1. ] [ 0. 1. 2. ] [ 1. 2. nan] [ 2. nan 4. ] [ nan 4. 2. ] [ 4. 2. 0.8 ] [ 2. 0.8 4. ] [ 0.8 4. 8.8 ] [ 4. 8.8 7.12]]
type: Answer
answers question: http://stackoverflow.com/q/48883784
upvote count: 7
score: 7
type: AcceptedAnswer

http://stackoverflow.com/comment/84648806
has text: You really shouldn't be using an unreleased version of Python. Stick to 3.6.
score: 2
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48822571

http://stackoverflow.com/comment/84650261
score: 0
type: AnswerComment
type: Comment
has text: This is how I was thinking of doing it, after my mistake below, so have an upvote. @shoresh, [here](https://engineering.upside.com/a-beginners-guide-to-optimizing-pandas-code-for-speed-c09ef2c6a4d6) is a nice article about your options for improving speed in Pandas.
comment on: http://stackoverflow.com/a/48818014

http://stackoverflow.com/comment/84838777
has text: Why not just `ppst = [adjusted_exc_pass_numbers[index] for index in processed_start_times]`? Iterating over `range(len(thing))` is generally unidiomatic in Python.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48916154

http://stackoverflow.com/comment/137517530
has text: Yes, you are correct. Fixed it now.
comment on: http://stackoverflow.com/a/67078389
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48876623
has body: The current script appears to overwrite the same PDF file for each line of the CSV. The modified script shown below generates the table as shown in the spreadsheet. I made some major changes, so you will need to modify the file paths, formatting, content, etc., to fit your application. The new code also includes column widths and removes a few characters that appear to be unnecessary. Example of the generated PDF CSV data used to test: ['ID','Incoming Number','Date &amp; Time','Read','Sent/Replied','Body','Seen'] (1,'555-555-5555','23-01-2018 17:03:52',1,1,'Where are you at? Are you on your way yet?',1) (2,'555-555-5555','23-01-2018 17:04:08',1,2,'Yes I am driving at the moment',1) (3,'555-555-5555','23-01-2018 17:04:34',1,1,'Be here soon or I'm going to call you',1) (4,'555-555-5555','23-01-2018 17:05:10',1,2,'Yes I will try and pick up the speed and make up time. I'm breaking the speed limit already.',1) (5,'555-555-5555','23-01-2018 17:05:46',1,1,'Ok',1) Modified Python script The table style code is longer than necessary to help demonstrate how the cell ranges work. import csv import datetime from reportlab.lib.units import cm, inch from reportlab.lib import colors from reportlab.lib.pagesizes import letter from reportlab.platypus import * from reportlab.lib.styles import getSampleStyleSheet # Data from CSV with open('smsInfo.csv', "r") as csvfile: data = list(csv.reader(csvfile)) elements = [] # PDF Text # PDF Text - Styles styles = getSampleStyleSheet() styleNormal = styles['Normal'] # PDF Text - Content line1 = 'LYIT MOBILE FORENSICS DIVISION' line2 = 'Date: {}'.format(datetime.datetime.now().strftime("%d-%m-%y")) line3 = 'Case Number: 10' line4 = 'This forensic report on sms card data has been compiled by the forensic' line5 = 'examiner in conclusion to the investigation into the RTA' line6 = 'case which occurred on 23/01/2018.' elements.append(Paragraph(line1, styleNormal)) elements.append(Paragraph(line2, styleNormal)) elements.append(Paragraph(line3, styl…
downvote count: 0
has comment: http://stackoverflow.com/comment/84781252
accepted answer of: http://stackoverflow.com/q/48863462
score: 13
has comment: http://stackoverflow.com/comment/84777028
answers question: http://stackoverflow.com/q/48863462
upvote count: 13
has comment: http://stackoverflow.com/comment/84780470
has comment: http://stackoverflow.com/comment/84781002
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84781081

http://stackoverflow.com/q/48840448
answer count: 1
downvote count: 1
tagged with: python
favorite count: 0
tagged with: tkinter
has answer: http://stackoverflow.com/a/48840500
has body: I want Python to display data from Access by SELECT (SQL) but there is an error. The data and database are existed. What is a problem? from tkinter import * import pypyodbc import ctypes #Create connection con = pypyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=C:/Users/HP/Desktop/PITL;DBQ=C:/Users/HP/Desktop/PITL/PITL.mdb;') cursor = con.cursor () form = Tk () form.title ("Main") form.geometry ('400x400') def Show (): cursor.execute ("SELECT `Law_ID` FROM Laws WHERE Fine='1'") for row in cursor: print (row) Button=Button(form, text = 'PUSH ME', command = Show) Button.pack () form.mainloop () con.commit () cursor.close () con.close () Error: Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__ return self.func(*args) File "C:\Users\HP\Desktop\PITL\SHOW DATA.py", line 14, in Show cursor.execute ("SELECT `Law_ID` FROM Laws WHERE Fine='1'") File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypyodbc-1.3.4-py3.6.egg\pypyodbc.py", line 1626, in execute self.execdirect(query_string) File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypyodbc-1.3.4-py3.6.egg\pypyodbc.py", line 1652, in execdirect check_success(self, ret) File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypyodbc-1.3.4-py3.6.egg\pypyodbc.py", line 1007, in check_success ctrl_err(SQL_HANDLE_STMT, ODBC_obj.stmt_h, ret, ODBC_obj.ansi) File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypyodbc-1.3.4-py3.6.egg\pypyodbc.py", line 977, in ctrl_err raise DataError(state,err_text) pypyodbc.DataError: ('22018', '[22018] [Microsoft][Драйвер ODBC Microsoft Access] Несоответствие типов данных в выражении условия отбора.')
accepted answer: http://stackoverflow.com/a/48840500
type: AnsweredQuestion
upvote count: 0
tagged with: select
score: -1
type: Question
has title: Cannot display data from Access in Python (via SQL)
has comment: http://stackoverflow.com/comment/84691065
tagged with: ms-access
tagged with: sql

http://stackoverflow.com/a/48899134
has body: You can use itertools for counting words in file.below is simple example code.explore itertools.groupby and modify code according to your logic. import itertools tweets = ["I am a cat", "cat", "Who is a good cat"] words = sorted(list(itertools.chain.from_iterable(x.split() for x in tweets))) count = {k:len(list(v)) for k,v in itertools.groupby(words)}
downvote count: 0
answers question: http://stackoverflow.com/q/48898831
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/48860814
has comment: http://stackoverflow.com/comment/84724896
has comment: http://stackoverflow.com/comment/84724844
has body: You can get your href value to hold your data on empty div.Loop and get herf value and again empty your div. var papersFound = ['Symmetric spectra', 'Topological transformation groups'] var arrayLength = papersFound.length; var html = ''; for (i = 0; i < arrayLength; i++) { html += papersFound[i]; } $('.results').html(html); $('.results').find('a').each(function(index, element) { console.log($(this).attr('href')); }); $('.results').html('');
answers question: http://stackoverflow.com/q/48860520
score: 0
type: Answer

http://stackoverflow.com/comment/84794792
comment on: http://stackoverflow.com/a/48893477
score: 0
type: AnswerComment
type: Comment
has text: That really is a great solution. A lot better than mine below since it will pick up ever value, not just the hardcoded ones I have.

http://stackoverflow.com/comment/84639491
has text: What is the `vect` that you do `fit_transform` on? A vectorizer?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48815919

http://stackoverflow.com/comment/84760616
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48878292
has text: Maybe you could take a look at your network traffic and see what calls it is making to the API to get new content. You could possibly make the calls yourself
score: 0

http://stackoverflow.com/comment/84748410
type: AnswerComment
type: Comment
has text: @SafenessAndSafe: do you know which one?
comment on: http://stackoverflow.com/a/48872255
score: 0

http://stackoverflow.com/a/48892188
score: 2
upvote count: 2
has body: Tweepy doesn't work with python 3.7 yet. Similar question: Having trouble installing Tweepy Official documentation says : https://github.com/tweepy/tweepy Python 2.6 and 2.7, 3.3, 3.4, 3.5 &amp; 3.6 are supported. As suggested by Samuel. Create a virtual environment I would suggest go with 3.6. And then pip install tweepy in that environment.
downvote count: 0
answers question: http://stackoverflow.com/q/48891714
type: Answer

http://stackoverflow.com/a/48867290
upvote count: 1
has body: You'll just use the client socket to send a response. con, cliente = serv_socket.accept() receive = con.recv(1024) if receive == '0123456789': con.send("ACK") serv_socket.close()
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48867064

deepface
tags question: http://stackoverflow.com/q/48902559
tag name: deepface
type: Tag

http://stackoverflow.com/comment/84866146
type: Comment
comment on: http://stackoverflow.com/a/48929764
score: 0
type: AnswerComment
has text: Not just might, but definitely should update it. I missed the part where you say your tensorflow installation is on version 1.2.1

http://stackoverflow.com/q/48817253
type: UnansweredQuestion
has body: So I have this Model: class Mymodel(models.Model): brand = models.CharField(max_length=256) model = models.PositiveIntegerField() year = models.PositiveIntegerField() and I have a dropdown as such: Volvo Saab Mercedes Audi I want the user to be able to click a button, and it take their input from the dropdown. Then compare it to values in the database, and once it finds one that matches to return the other values related to that one. And lastly have a way to use them in a function in the views.py file.
type: Question
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84642841
tagged with: django-views
score: 0
has title: How to take input from dropdown list compare it to a value in the database and then run commands using the other relating values of the same model?
tagged with: django-models
tagged with: django-forms
has comment: http://stackoverflow.com/comment/84642878
has comment: http://stackoverflow.com/comment/84642854
answer count: 0

http://stackoverflow.com/a/48824217
has comment: http://stackoverflow.com/comment/84690768
type: AcceptedAnswer
downvote count: 0
score: 1
has body: In general, I've found that in tensorflow you want good known shapes. This is because most operations are matrix multiplications and the matrices are fixed shape. If you really want to do this you need to convert to sparse tensor and then apply tf.sparse_retain. The "equivalent" I would normally use in tensorflow is to multiply the mask with the large_array to 0 out the False values (large_array_masked = large_array * mask). This keeps the original shape so it makes it easier to pass to dense layers, etc...
type: Answer
accepted answer of: http://stackoverflow.com/q/48817784
answers question: http://stackoverflow.com/q/48817784
upvote count: 1

http://stackoverflow.com/comment/84744124
has text: You wanna to look df.columns, exclude some column names not to clip with, and then replace it with ['one', 'two'] at the above expression.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48869904
score: 0

http://stackoverflow.com/comment/84956205
score: 0
type: AnswerComment
type: Comment
has text: Not enough details Ashutosh, sorry brother, I would suggest you start a new question.
comment on: http://stackoverflow.com/a/48952296

http://stackoverflow.com/q/48806208
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/84622892
tagged with: boto3
tagged with: amazon-web-services
answer count: 3
has comment: http://stackoverflow.com/comment/84615908
tagged with: aws-lambda
favorite count: 0
has answer: http://stackoverflow.com/a/72171851
type: UnansweredQuestion
has body: I'm trying to copy a file from 1 bucket to another prefix in the same bucket using lambda &amp; boto3 however I keep getting an error: An error occurred (AccessDenied) when calling the CopyObject operation. or An error occurred (403) when calling the HeadObject operation: Forbidden depending on which copy method I use. The lambda function has a role assigned to it, which I think gives it all the permissions it requires: { "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:HeadObject", "s3:ListObjects" ], "Resource": [ "arn:aws:s3:::bucket-name", "arn:aws:s3:::bucket-name/*" ], "Effect": "Allow" }, { "Action": [ "s3:GetObject", "s3:PutObject", "s3:DeleteObject" ], "Resource": [ "arn:aws:s3:::bucket-name/folderA/folderB/*", "arn:aws:s3:::bucket-name/folderC/folderD/*", "arn:aws:s3:::bucket-name/folderE/folderF/*" ], "Effect": "Allow" } ] } The lambda function is: #connect to s3 s3 = boto3.resource('s3') dirs = { "folderA/folderB": "folderC/folderD" } key = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['key'], encoding='utf-8') etag = urllib.parse.unquote_plus(event['Records'][0]['s3']['object']['eTag'], encoding='utf-8') bucket = event['Records'][0]['s3']['bucket']['name'] filePathName = key.split("/") sourceDir = filePathName[0] + "/" + filePathName[1] fileName = filePathName[2] sourceKey = sourceDir + "/" + fileName source = {'Bucket': bucket, 'Key': sourceKey} destination = dirs[sourceDir] + "/" + fileName ########## # This option comes up with the An error occurred (AccessDenied) when calling the CopyObject operation. Error ########### s3.Object(bucket, destination).copy_from(CopySource=source) ########### ## This option comes up with the An error occurred (403) when calling the HeadObject operation: Forbidden error ########### s3.meta.client.copy(source, bucket, destination) EDIT: forgot to mention, it works fine if I change the role to { "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:*" ], "Resource": [ "arn:aws:s3:::bucket-name…
tagged with: python
has comment: http://stackoverflow.com/comment/84623388
has comment: http://stackoverflow.com/comment/84622415
has comment: http://stackoverflow.com/comment/84635288
has comment: http://stackoverflow.com/comment/84616149
has comment: http://stackoverflow.com/comment/84621320
has answer: http://stackoverflow.com/a/77405215
has title: boto3 s3 copyObject error
has comment: http://stackoverflow.com/comment/84631979
type: Question
score: 5
has comment: http://stackoverflow.com/comment/84622849
has answer: http://stackoverflow.com/a/51973175

http://stackoverflow.com/q/48861126
has comment: http://stackoverflow.com/comment/84725412
has comment: http://stackoverflow.com/comment/84727040
has comment: http://stackoverflow.com/comment/84727003
score: 0
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48861545
downvote count: 1
possible better answer: http://stackoverflow.com/a/48861282
favorite count: 0
has body: apply mask like this to an image How can I apply mask to a 16bit image? It works fine with a 8bit image with this code: image = misc.imread('test.jpg') gray = cv2.cvtColor(image, cv2.Color(image, cv2.COLOR_BGR2GRAY) x = 610 y = 220 w = h = 150 mask = np.zeros(gray.shape[:2], np.uint8) mask[y:y+h,x:x+w] = 255 res = cv2.bitwise_and(gray, gray, mask = mask) cv2.imshow("res", res) cv2.waitKey(0) But when I try to do it with a 16 bit.png picture it doesn't work. I tried this code: mask = np.zeros(gray.shape[:2], np.uint16) mask[y:y+h, x:x+w] = 6535 res = cv2.bitwise_and(gray, gray, mask = mask) I get the error: res = cv2.bitwise_and(gray, gray, mask = mask) cv2.error: /home/... : error: (-215) (mtype == CV_8U || mtype == CV_8S) &amp;&amp; _mask.sameSize(*psrc1) in function binary_op Does anybody know how I can apply a mask to my 16 bit image?
has answer: http://stackoverflow.com/a/48861282
tagged with: python
type: AnsweredQuestion
has title: How can I apply mask to a 16bit image?
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/84725389
has comment: http://stackoverflow.com/comment/84726948
accepted answer: http://stackoverflow.com/a/48861545
has comment: http://stackoverflow.com/comment/84725548

http://stackoverflow.com/comment/84780470
type: Comment
comment on: http://stackoverflow.com/a/48876623
has text: It has worked but I would like to have gridlines around the whole table. I tried putting in "('INNERGRID', (0,0), (-1,-1), 1, colors.black)," but the data in the table seems to go past the gridlines. Is there any way of making the gridlines move according to what is in the cells?
type: AnswerComment
score: 0

http://stackoverflow.com/q/48920949
tagged with: django-forms
has comment: http://stackoverflow.com/comment/84854029
has comment: http://stackoverflow.com/comment/84892276
type: Question
has comment: http://stackoverflow.com/comment/84853922
has comment: http://stackoverflow.com/comment/84848322
tagged with: django-models
has title: Querying model data in form for cleaned DB
score: 0
has answer: http://stackoverflow.com/a/48921282
answer count: 1
has comment: http://stackoverflow.com/comment/84848246
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: So I have forms.py which is as below: from django import forms from .models import SipExtension from xmpp.models import xmpp_buddy_groups class ExtensionForm(forms.Form): xmpp_buddy_groups_choices = xmpp_buddy_groups.objects.values_list('group_name',flat=True) boolean_choices=(('Yes','Yes'),('No','No')) sip_extension = forms.IntegerField(min_value=0,max_value=100000) sip_secret = forms.CharField(required=True,max_length=32) commlink_push = forms.ChoiceField(choices=boolean_choices,widget=forms.CheckboxSelectMultiple,required=True) real_name = forms.CharField(required=True,max_length=32) xmpp = forms.ChoiceField(choices=boolean_choices,widget=forms.CheckboxSelectMultiple,required=True) xmpp_username = forms.CharField(required = True,min_length=5) xmpp_password = forms.CharField(max_length=32, widget=forms.PasswordInput) xmpp_buddy_groups_names = forms.MultipleChoiceField(choices=xmpp_buddy_groups_choices,widget=forms.CheckboxSelectMultiple,required=False) It works fine if my DB is already created by previous migrations. But I faced problem when my DB is blank. To test,I dropped all the tables and then run make migrations and got below error: django.db.utils.ProgrammingError: relation "extensions_sipextension" does not exist LINE 1: ...p_buddy_groups_names"."xmpp_buddy_groups_id" FROM "extension... I am getting problems in handling this on blank database when I need to deploy on entirely new system. I could handle that by commenting the urls which are executing views which needs this form but that is a bad and temporary work around. How to fix this?

http://stackoverflow.com/comment/84641406
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48813243
score: 0
has text: can you give me some general direction how to change my input?

http://stackoverflow.com/comment/84927826
type: Comment
comment on: http://stackoverflow.com/a/48960509
has text: @learner8269 , what is the point of your approach? IMHO it makes no sense to find the same element twice
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84776453
comment on: http://stackoverflow.com/q/48885284
type: Comment
type: QuestionComment
has text: Yes: (venv)wiks@asus:~/Dokumenty/projects/wiks_depend/mysite$ python manage.py makemigrations No changes detected
score: 0

http://stackoverflow.com/comment/84895614
comment on: http://stackoverflow.com/a/48937531
has text: I just tested your suggestion against my original code. Apparently it's faster to leave the code the way I initially wrote it, as without the second filter the code is way slower (I had to gave up on the processing after waiting 5 times the time, seeing it was still not done).
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48815842
accepted answer: http://stackoverflow.com/a/48818014
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48816110
tagged with: performance
tagged with: dynamic
has body: How can I use better solution instead of following codes? in big data set with lots of columns this code takes too much time import pandas as pd df = pd.DataFrame({'Jan':[10,20], 'Feb':[3,5],'Mar':[30,4],'Month': [3,2],'Year':[2016,2016]}) # Jan Feb Mar Month Year # 0 10 3 30 3 2016 # 1 20 5 4 2 2016 df1['Antal_1']= np.nan df1['Antal_2']= np.nan for i in range(len(df)): if df['Yaer'][i]==2016: df['Antal_1'][i]=df.iloc[i,df['Month'][i]-1] df['Antal_2'][i]=df.iloc[i,df['Month'][i]-2] else: df['Antal_1'][i]=df.iloc[i,-1] df['Antal_2'][i]=df.iloc[i,-2] df # Jan Feb Mar Month Year Antal_1 Antal_2 # 0 10 3 30 3 2016 30 3 # 1 20 5 4 2 2016 5 20
score: 1
upvote count: 1
possible better answer: http://stackoverflow.com/a/48816110
type: Question
has title: How to efficiently add multiple columns to pandas data frame with values that depend on other dynamic columns
has answer: http://stackoverflow.com/a/48818014
downvote count: 0
answer count: 2
tagged with: pandas
favorite count: 0

http://stackoverflow.com/q/48955932
tagged with: python
has answer: http://stackoverflow.com/a/48959118
type: AnsweredQuestion
upvote count: 0
tagged with: tkinter
type: Question
tagged with: window-resize
score: -1
has body: I am designing a GUI in Python/Tkinter. Resizing the root frame makes the geometry controller adapt and resize the widgets in the GUI according to the room available, up to here everything's fine. BUT... One of the widgets that gets shrunk first is a left-justified label. I would like it to start disappearing from the right side, instead Tkinter reduces it from left and right at the same time. Here is a sample code to replicate the situation: import tkinter as tk root = tk.Tk() my_font = ("Consolas", 12) label1 = tk.Label(root, text="Label 1\nGoes on the Left", justify="left", font=my_font, bg='cyan') label2 = tk.Label(root, text="Label 2\nGoes on the Right", justify="left", font=my_font, bg='magenta') label3 = tk.Label(root, text="Label 3 - Goes in the middle\n(During a resize, this shrinks first)", justify="left", font=my_font, bg='orange') label1.pack(side=tk.LEFT) label2.pack(side=tk.RIGHT) label3.pack(side=tk.LEFT) # packed last, so it gets reduced first during a resize root.mainloop() And here is a picture of what happens with that same code: resize in action Is there a way to tell the geometry controller how to reduce the widgets during window resize? Many thanks.
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/48959118
favorite count: 0
has title: Shrinking widgets during resize in Tkinter (can I decide shrinkage behavior?)

http://stackoverflow.com/a/48944768
score: 1
accepted answer of: http://stackoverflow.com/q/48944593
upvote count: 1
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48944593
has body: You should implement a __getitem__ method in the user_class. class user_class: def __init__(self, lst): self.values = lst def __getitem__(self, it): return self.values[it] Or it can be a subclass of some base type like list: class user_class(list): # your control code goes here def shout(self): print("AAA!")
downvote count: 0

http://stackoverflow.com/q/48952140
type: Question
tagged with: numpy
has title: Creating a sparse matrix from csv file data
has body: Data in the csv file is of the format ("user_id", "group_id", "group_value"). "group_id" ranges from 0 to 100. For a given user_id, it may be possible that group_value for a particular group_id is not available. I want to create a sparse matrix representation of the above data. ("group_id_0", "group_id_1", ... , "group_id_100") What is the best way to achieve this in Python? Edit: Data is too big to iterate over.
tagged with: sparse-matrix
tagged with: pandas
has answer: http://stackoverflow.com/a/48967829
answer count: 1
favorite count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84914344
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84910992
score: 1
downvote count: 1
tagged with: scipy

http://stackoverflow.com/comment/84798731
type: Comment
has text: I fixed the initializer, but problem still persists. This time with -- TypeError: super() takes at least 1 argument (0 given)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48896422

http://stackoverflow.com/q/48883784
favorite count: 0
score: 4
type: Question
has answer: http://stackoverflow.com/a/48884154
has body: How do I obtain the rolling values of some length n of a pandas series of value ? For example, if I have the following: df = pd.DataFrame({'temperature': [0, 1, 2, np.nan, 4, 2, 0.8, 4, 8.8, 7.12]}) how do I obtain the moving values of length n, i.e. something like, if n=3: [NaN, NaN, 0], [NaN, 0, 1],..., [4, 8.8, 7.12] EDIT: If I use pandas rolling, as: roll = pd.Series.rolling(df, 3).mean() then roll is the moving averages of the series. Here, I do not want the averages of every moving set of 3 values, but these sets of 3 values.
has comment: http://stackoverflow.com/comment/84772227
has title: Pandas rolling values
downvote count: 1
has comment: http://stackoverflow.com/comment/84772773
has comment: http://stackoverflow.com/comment/84772261
has comment: http://stackoverflow.com/comment/84772282
has answer: http://stackoverflow.com/a/68935193
accepted answer: http://stackoverflow.com/a/48884154
answer count: 4
upvote count: 5
has answer: http://stackoverflow.com/a/74860401
has comment: http://stackoverflow.com/comment/84772251
tagged with: pandas
type: AnsweredQuestion
tagged with: python
possible better answer: http://stackoverflow.com/a/74860401
has answer: http://stackoverflow.com/a/77528386

http://stackoverflow.com/q/48939750
answer count: 1
has title: Python Counter does not work. Or I forgot first grade matematics
has comment: http://stackoverflow.com/comment/84886676
has comment: http://stackoverflow.com/comment/84886680
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: Well hello there, I'm about to lose my mind, so I'll be glad if SOMEBODY helped. The code is below. The output doesn't give me the right count. import os, sys from random import randint from collections import Counter import random N = range(1,11) print "N=" , N #the stupid part below should take 10 random integers whose sum is equal to 10 def sum_to_ten(n): values = [1, 11] + [random.randint(2,n) for _ in range(n - 1)] values.sort() return [values[i+1] - values[i] for i in range(n)] E = sum_to_ten(10) print "E is: ", sum_to_ten(10) N_E = dict(zip(N,E)) print N_E #N_i should count the number of times an integer shows up, but does it? NO. N_i = Counter(E) print "N_i is:", N_i Here's the output: N is: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] E is: [1, 0, 1, 2, 0, 1, 2, 0, 1, 2] N_E : {1: 1, 2: 4, 3: 1, 4: 0, 5: 1, 6: 0, 7: 0, 8: 2, 9: 0, 10: 1} N_i is: Counter({0: 4, 1: 4, 2: 1, 4: 1}) #See, N and E doesn't zip together to a dictionary correctly, and the counter doesn't count right.
has comment: http://stackoverflow.com/comment/84886729
type: Question
has comment: http://stackoverflow.com/comment/84886697
accepted answer: http://stackoverflow.com/a/48939838
tagged with: counter
has comment: http://stackoverflow.com/comment/84886598
score: 0
has comment: http://stackoverflow.com/comment/84886664
has answer: http://stackoverflow.com/a/48939838
upvote count: 1
downvote count: 1

opencv
tags question: http://stackoverflow.com/q/48866756
tags question: http://stackoverflow.com/q/48866310
type: Tag
tags question: http://stackoverflow.com/q/48869453
tags question: http://stackoverflow.com/q/48877967
tags question: http://stackoverflow.com/q/48849870
tags question: http://stackoverflow.com/q/48887160
tags question: http://stackoverflow.com/q/48827085
tags question: http://stackoverflow.com/q/48830865
tags question: http://stackoverflow.com/q/48806504
tags question: http://stackoverflow.com/q/48898155
tags question: http://stackoverflow.com/q/48877925
tags question: http://stackoverflow.com/q/48890390
tags question: http://stackoverflow.com/q/48817794
tags question: http://stackoverflow.com/q/48916296
tags question: http://stackoverflow.com/q/48850764
tags question: http://stackoverflow.com/q/48928640
tags question: http://stackoverflow.com/q/48934830
tags question: http://stackoverflow.com/q/48896693
tags question: http://stackoverflow.com/q/48954246
tags question: http://stackoverflow.com/q/48956585
tags question: http://stackoverflow.com/q/48904835
tags question: http://stackoverflow.com/q/48877502
tags question: http://stackoverflow.com/q/48825227
tags question: http://stackoverflow.com/q/48946472
tags question: http://stackoverflow.com/q/48960741
tags question: http://stackoverflow.com/q/48947106
tags question: http://stackoverflow.com/q/48810243
tags question: http://stackoverflow.com/q/48843562
tags question: http://stackoverflow.com/q/48909132
tags question: http://stackoverflow.com/q/48941504
tag name: opencv
tags question: http://stackoverflow.com/q/48813291
tags question: http://stackoverflow.com/q/48920136
tags question: http://stackoverflow.com/q/48922718
tags question: http://stackoverflow.com/q/48920120
tags question: http://stackoverflow.com/q/48840810
tags question: http://stackoverflow.com/q/48918008
tags question: http://stackoverflow.com/q/48855506
tags question: http://stackoverflow.com/q/48816703
tags question: http://stackoverflow.com/q/48884177
tags question: http://stackoverflow.com/q/48897935
tags question: http://stackoverflow.com/q/48886532
tags question: http://stackoverflow.com/q/48890276
tags question: http://stackoverflow.com/q/48865868
tags question: http://stackoverflow.com/q/48923084
tags question: http://stackoverflow.com/q/48895902
tags question: http://stackoverflow.com/q/48905676
tags question: http://stackoverflow.com/q/48850987
tags question: http://stackoverflow.com/q/48918145
tags question: http://stackoverflow.com/q/48928196
tags question: http://stackoverflow.com/q/48950949
tags question: http://stackoverflow.com/q/48804790
tags question: http://stackoverflow.com/q/48815849
tags question: http://stackoverflow.com/q/48948769
tags question: http://stackoverflow.com/q/48853997
tags question: http://stackoverflow.com/q/48945066
tags question: http://stackoverflow.com/q/48814216
tags question: http://stackoverflow.com/q/48861126
tags question: http://stackoverflow.com/q/48962001
tags question: http://stackoverflow.com/q/48863230
tags question: http://stackoverflow.com/q/48858317
tags question: http://stackoverflow.com/q/48930270
tags question: http://stackoverflow.com/q/48818032
tags question: http://stackoverflow.com/q/48831212
tags question: http://stackoverflow.com/q/48868348
tags question: http://stackoverflow.com/q/48866205
tags question: http://stackoverflow.com/q/48912988
tags question: http://stackoverflow.com/q/48847515

http://stackoverflow.com/q/48949878
favorite count: 0
tagged with: python
tagged with: datastax-python-driver
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/48954203
upvote count: 1
type: Question
downvote count: 0
tagged with: cassandra
tagged with: datastax
has body: I'm developing a simple python module that reads data from a tsv file and load them into a Cassandra keyspace table. I started by looking at the examples given by Datastax and everything seemed to be ok, so at that point I began to code. The program reads data from the tsv file correctly, it translates them into a list of rows and I verified that every element of each row has the right type for the destination column. But when I try to insert a raw into a table the terminal says: AttributeError: 'float' object has no attribute 'encode' This is the code: #Upload data to Cassandra DB (cassandra_df is a Pandas dataframe) session.set_keyspace(data_ks) cassandra_df_list = cassandra_df.values.tolist() query = "INSERT INTO table_str (rowid,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa,ab,ac,ad,ae,af,ag,ah,ai,aj,ak,al,am,an,ao,ap,aq,ar,as,at,au,av,aw,ax,ay,az,ba,bb,bc,bd) VALUES (uuid(),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)" prepared = session.prepare(query) for row in cassandra_df_list: prepared.bind(row) session.execute(prepared) cluster.shutdown() I made a lot of changes in order to solve the problem, but I got new issues or the same with 'int' instead of 'float'. I also read other questions here and tried to use str(row) and repr(row) in prepared.bind(), but I got other errors. I'm new to Python and I'm not able to find other solutions, what would you do? Thanks in advance! Edit Sorry, I forgot to give details about the DB table. Here is the creation statement: CREATE TABLE prova.table_str ( rowid uuid PRIMARY KEY, a text, aa text, ab text, ac text, ad text, ae text, af text, ag text, ah text, ai text, aj double, ak double, al double, am text, an double, ao double, ap double, aq double, ar double, as double, at double, au double, av double, aw double, ax double, ay double, az double, b text, ba double, bb text, bc text, bd text, c text, d text, e int, f text, g text, h text, i text, j te…
answer count: 1
has title: Python Cassandra Driver: encoding issue during insertion
has answer: http://stackoverflow.com/a/48954203

http://stackoverflow.com/q/48819296
score: 2
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/48819457
has comment: http://stackoverflow.com/comment/84642711
tagged with: python-3.6
answer count: 2
has title: SQLalchemy couldn't find the target column?
downvote count: 0
has body: ticker_table = Table('ticker_data', MetaData(), Column('id', Integer, primary_key=True), Column('ticker', String(100), nullable=False), Column('adj_slope', Float(3), nullable=False), Column('sector', String(100), nullable=False), Column('sub_sector', String(100), nullable=False) ) price_data = Table('price_data', MetaData(), Column('id', Integer, primary_key=True), Column('ticker', String(100), ForeignKey('ticker_data.ticker'), nullable=False), Column('date', Date), Column('price', Float(3)), ) price_data.create(bind=engine) I'm getting this error Foreign key associated with column 'price_data.ticker' could not find table 'ticker_data' with which to generate a foreign key to target column 'ticker' I'm using MySQL Workbench with Python 3.6 and the most up to date everything else. Not sure what would be causing this error? Any help would be much appreciated. Maybe because I'm using the mysqlclient since the actual plugin isn't updated to python 3.6? I'm relatively new to all things sqlalchemy so any feedback would greatly benefit me.
has comment: http://stackoverflow.com/comment/84642497
favorite count: 0
has answer: http://stackoverflow.com/a/48819435
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48835849
has body: Check this out first: https://www.w3schools.com/tags/att_form_action.asp Action should be "/process" instead of "POST". Method is "POST". Also you will need input elements in the form to allow user inputs something. The input value can be retrieved on the flask side by request.form['value of name attribute of input'] https://www.w3schools.com/tags/tag_input.asp I would like to recommend you to use https://flask-wtf.readthedocs.io/en/stable/ flask wtf to generate form and retrieve users' input.
score: 0
answers question: http://stackoverflow.com/q/48834408
type: Answer

http://stackoverflow.com/a/48889180
answers question: http://stackoverflow.com/q/48888671
score: 1
has body: Your loop should always run, otherwise you would need a second loop to check if it should run the loop = redundant. Also you are using the multiprocessing library, which means they won't share global variables inside the system, like threads would. SO... you need to save the switch in an outside context (like a DB, or config file) and have the loop check that before output. def logstate(): while 1: with open('myfile.txt', 'r') as f: switch = f.readline() if switch.lower() == "true": print('state') sleep(1) Here is the problem with the above. Sleep blocks the thread. You really should think about context switching, like gevent. Additional option, if you do go to gevent, you can use GIPC to open multiple processes as well as asynch threading inside each process AND share states between them. It works extremely well.
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84807467
upvote count: 1

http://stackoverflow.com/q/48914493
upvote count: 2
tagged with: raspberry-pi
answer count: 1
has title: File transfer to Raspberry with Python language
has answer: http://stackoverflow.com/a/48914679
downvote count: 1
accepted answer: http://stackoverflow.com/a/48914679
tagged with: python
favorite count: 0
tagged with: file
type: Question
type: AnsweredQuestion
score: 1
has body: I am doing a project where I need to make a communication channel between a PC and Raspberry Pi, this channel should be able to transfer text files from pc to a folder in Raspberry. The PC and RBPi are conected throught network. The security is not really relevant. Thank you in advance.
has comment: http://stackoverflow.com/comment/84835370
has comment: http://stackoverflow.com/comment/84835616

http://stackoverflow.com/q/48823008
tagged with: sigint
downvote count: 1
type: Question
has title: How to avoid python exception in while handling SIGINT
linked to: http://stackoverflow.com/q/1112343
has comment: http://stackoverflow.com/comment/84649384
has comment: http://stackoverflow.com/comment/84649998
score: -1
has comment: http://stackoverflow.com/comment/84653319
tagged with: python-2.7
upvote count: 0
has comment: http://stackoverflow.com/comment/84649463
answer count: 1
has comment: http://stackoverflow.com/comment/84649945
has answer: http://stackoverflow.com/a/48825118
favorite count: 0
has comment: http://stackoverflow.com/comment/84649374
has comment: http://stackoverflow.com/comment/84653500
has comment: http://stackoverflow.com/comment/84649685
tagged with: python
type: AnsweredQuestion
has body: import signal import time def sigint_handler(signum, frame): print 'User pressed CTRL+C!' signal.signal(signal.SIGINT, sigint_handler) def main(): while True: print 'Script to handle SIGINT' time.sleep(2) ########## if __name__ == "__main__": main() How can I block this below exception thrown by python itself when executing the code: File "D:\Documents\scripts\ctrlc handler.py", line 19, in &lt;module&gt; main() File "D:\Documents\scripts\ctrlc handler.py", line 14, in main time.sleep(2) OError: [Errno 4] Interrupted function call
accepted answer: http://stackoverflow.com/a/48825118

http://stackoverflow.com/comment/84865495
has text: You must run manage.py in the container, something among the lines `docker-compose exec container-name /path/to/manage.py db migrate`.
comment on: http://stackoverflow.com/q/48929409
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/84809337
type: AnswerComment
has text: Thanks for detail explanation and modifying my code accordingly.
type: Comment
comment on: http://stackoverflow.com/a/48889004
score: 0

http://stackoverflow.com/a/48866728
upvote count: 3
type: Answer
accepted answer of: http://stackoverflow.com/q/48822715
has body: I wrote a few functions that are all supposed to do the same thing, but need different amounts of time to complete the task: import timeit import numba as nb x = np.random.normal(0,1,(10000,2)) def f1(): res = [np.sum(x[:i,0] &gt; x[i,1]) for i in range(x.shape[0])] return res def f2(): buf = np.empty(x.shape[0]) res = np.empty(x.shape[0]) for i in range(x.shape[0]): buf[:i] = x[:i,0] &gt; x[i,1] res[i] = np.sum(buf[:i]) return res def f3(): res = np.empty(x.shape[0]) for i in range(x.shape[0]): res[i] = np.sum(x[:i,0] &gt; x[i,1]) return res @nb.jit(nopython=True) def f2_nb(): buf = np.empty(x.shape[0]) res = np.empty(x.shape[0]) for i in range(x.shape[0]): buf[:i] = x[:i,0] &gt; x[i,1] res[i] = np.sum(buf[:i]) return res @nb.jit(nopython=True) def f3_nb(): res = np.empty(x.shape[0]) for i in range(x.shape[0]): res[i] = np.sum(x[:i,0] &gt; x[i,1]) return res ##checking that all functions give the same result: print('checking correctness') print(np.all(f1()==f2())) print(np.all(f1()==f3())) print(np.all(f1()==f2_nb())) print(np.all(f1()==f3_nb())) print('+'*50) print('performance tests') print('f1()') print(min(timeit.Timer( 'f1()', setup = 'from __main__ import f1,x', ).repeat(7,10))) print('-'*50) print('f2()') print(min(timeit.Timer( 'f2()', setup = 'from __main__ import f2,x', ).repeat(7,10))) print('-'*50) print('f3()') print(min(timeit.Timer( 'f3()', setup = 'from __main__ import f3,x', ).repeat(7,10))) print('-'*50) print('f2_nb()') print(min(timeit.Timer( 'f2_nb()', setup = 'from __main__ import f2_nb,x', ).repeat(7,10))) print('-'*50) print('f3_nb()') print(min(timeit.Timer( 'f3_nb()', setup = 'from __main__ import f3_nb,x', ).repeat(7,10))) As you can see, the differences are not big, but there are some differences in performance. The last two functions are just 'duplicates' of earlier ones, but using numba optimisation. The results of the speed tests are checking correctness True True True True ++++++++++++++++++++++++++++++++++++++++++++++++++ performanc…
answers question: http://stackoverflow.com/q/48822715
score: 3
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48875447
has body: I have a Pandas DataFrame, df, with a column called LocationNormalized. I've examined how often each value occurs with value_counts() and there are values that occur very rarely. So I want to convert these rare values to "RARE". Specifically, if a value occurs in the column less than 10 times, I want to replace it with "RARE". I was thinking something like: df["LocationNormalized"].apply(lambda x: "RARE" if df.value_counts()[x] &lt; 10 else x) But I know the df.value_counts()[x] syntax isn't correct because value_counts() returns a Series. How would I go about this? Thanks!
tagged with: pandas
favorite count: 0
has title: Pandas: Convert Rare Entries in Column to Common Value
type: Question
answer count: 2
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48875462
score: 0
has answer: http://stackoverflow.com/a/48875751
downvote count: 1
type: UnansweredQuestion

http://stackoverflow.com/a/48836174
type: AcceptedAnswer
downvote count: 0
has body: In order for the figure to be updated, you can introduce a small pause after plt.draw() for step in range(N_OF_DTs): clear_fired_grid() step1_grid() check_fired_grid() temp2 = np.nonzero(spike_data[0,0,step]) if not temp2[0].size == 0: print(temp2) print('iteration number == '+ str(step) + '\n') plt.plot(temp2[0], temp2[1], 'ro') plt.draw() plt.pause(0.1) # add a pause so that the events can be drawn on the figure Which will update the figure on each iteration, producing the desired "video" effect
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/48835854
upvote count: 1
answers question: http://stackoverflow.com/q/48835854

http://stackoverflow.com/a/48825708
score: 3
has comment: http://stackoverflow.com/comment/84655261
accepted answer of: http://stackoverflow.com/q/48825344
has comment: http://stackoverflow.com/comment/84655467
has body: example without re: input_filename = 'full_path_to_my_input_file.txt' output_filename = 'full_path_to_my_output_file.txt' with open(output_filename, 'a') as f_out: with open(input_filename, 'r') as f_in: for line in f_in: records = line.strip().split(',') if float(records[1]) &gt; float(records[3]): records[1], records[3] = records[3], records[1] if float(records[2]) &gt; float(records[4]): records[2], records[4] = records[4], records[2] f_out.write(','.join(records) + '\n') input: data/processed/10/blueprint-0.png,1915.0,387.0,1933.0,402.0 data/processed/10/blueprint-0.png,3353.0,389.0,3350.0,388.0 data/processed/10/blueprint-0.png,952.0,724.0,1010.0,734.0 output: data/processed/10/blueprint-0.png,1915.0,387.0,1933.0,402.0 data/processed/10/blueprint-0.png,3350.0,388.0,3353.0,389.0 ## swapped !! data/processed/10/blueprint-0.png,952.0,724.0,1010.0,734.0
answers question: http://stackoverflow.com/q/48825344
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 3

http://stackoverflow.com/q/48815849
has body: i want to change the code i got by the Youtuber Mark Jay which can detect objects in front of a webcam to detect objects in windows(like pygta5). (i changed the code a bit to something i (noob) thaught could work) import cv2 from darkflow.net.build import TFNet import numpy as np import time from PIL import ImageGrab options = { 'model': 'cfg/yolo.cfg', 'load': 'bin/yolo.weights', 'threshold': 0.2, 'gpu': 1.0 } tfnet = TFNet(options) colors = [tuple(255 * np.random.rand(3)) for _ in range(10)] #capture = cv2.VideoCapture(0) #capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) #capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080) while True: stime = time.time() screen = np.array(ImageGrab.grab(bbox=(0,0,1920,1080))) ret, frame = cv2.cvtColor(screen, cv2.COLOR_BGR2RGB) results = tfnet.return_predict(frame) if ret: for color, result in zip(colors, results): tl = (result['topleft']['x'], result['topleft']['y']) br = (result['bottomright']['x'], result['bottomright']['y']) label = result['label'] confidence = result['confidence'] text = '{}: {:.0f}%'.format(label, confidence * 100) frame = cv2.rectangle(frame, tl, br, color, 5) frame = cv2.putText(frame, text, tl, cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 0), 2) cv2.imshow('frame', frame) print('FPS {:.1f}'.format(1 / (time.time() - stime))) if cv2.waitKey(25) &amp; 0xFF == ord('q'): break cv2.destroyAllWindows() This code returns this error Traceback (most recent call last): File "D:\Python_Object_analyzis\YOLO Version\darkflow-master\Person_detection.py", line 23, in &lt;module&gt; ret, frame = cv2.cvtColor(screen, cv2.COLOR_BGR2RGB) ValueError: too many values to unpack (expected 2) What do i have to change the code to get it working? (sorry for bad english) Thanks in advance Tobias
tagged with: opencv
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84636234
score: 0
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48904382
has comment: http://stackoverflow.com/comment/84635864
has comment: http://stackoverflow.com/comment/84635868
type: Question
has title: YOLO object detection in windows
has comment: http://stackoverflow.com/comment/84685446
has comment: http://stackoverflow.com/comment/84636147
answer count: 1
accepted answer: http://stackoverflow.com/a/48904382
favorite count: 0
tagged with: python
tagged with: object-detection
has comment: http://stackoverflow.com/comment/84635753

http://stackoverflow.com/comment/84929356
comment on: http://stackoverflow.com/a/48891486
score: 0
type: Comment
has text: I understand that I get an error from authorize, because get_credentials returns object that does not define the method. But why is that? Why I can't get this pop up google login window to pass credentials ?
type: AnswerComment

http://stackoverflow.com/a/48896214
type: Answer
upvote count: 0
answers question: http://stackoverflow.com/q/48895802
downvote count: 1
score: -1
has body: If you want to apply that logic to all elements, you might want to go with something like this: In [21]: a=[[ 1, 2, 3, 4], ...: [ 2, 4, 10, 1]] ...: ...: In [22]: b = list() In [23]: l = lambda v: 0 if v &lt; 3 else v In [24]: for r in a: ...: b.append(list(map(l, r))) ...: In [25]: b Out[25]: [[0, 0, 3, 4], [0, 4, 10, 0]]

http://stackoverflow.com/comment/84916985
has text: wouldn't that require `apply()`? how would that change the for loop in `read_corpus`? apologies - my brain is quite addled today
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48954904
type: Comment

http://stackoverflow.com/comment/84841387
comment on: http://stackoverflow.com/q/48917405
type: QuestionComment
has text: Why, why do you not want to use list?
score: 2
type: Comment

http://stackoverflow.com/comment/84695090
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48845156
has text: I won't add this as an answer because `Javier`'s answer I think already covers what's needed. I would personally use `mp.Queue` mainly because I think it's clearer and maybe gives a little bit more control over the whole process. In terms of what is fastest, that's highly dependent on the actual compute load, if each call to `computeThing` takes an hour then the overhead from managed data structures are likely to be negligible. So for you to know what is best, you need to test it on your specific load.

http://stackoverflow.com/q/48875480
tagged with: python
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: pip
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/48875497
type: Question
has body: Trying to install pcapdb on a fresh debian install (requires django==1.9) installed via 'sudo pip3 install django==1.9' Other parts of django can be imported without issue e.g. django.conf, django.db, django.utils, etc. Output of 'pip3 list | grep -i django' Django (1.9) django-auth-ldap-ng (1.7.6) django-braces (1.12.0) django-celery (3.2.2) django-filebrowser (3.9.1) django-grappelli (2.10.2) django-hosts (3.0) django-url-tools (0.0.8) djangorestframework (3.7.7) djangorestframework-jwt (1.11.0) pip3 --version pip 9.0.1 from /usr/lib/python3/dist-packages (python 3.6) django version from interpreter import django print(django.get_version()) # 1.9 Ideas? Edit: The code in question is a dependency for pcapDB, not my code. See one of the files in question (django.urls imports) here
has title: Django 1.9 No module named 'django.urls'
answer count: 2
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48876648

http://stackoverflow.com/a/48860427
has body: This will also work. Shifted line : imageViewer.show() in your code. from PyQt5 import QtCore, QtWidgets, QtGui class ImageViewWidget(QtWidgets.QScrollArea): def __init__(self, parent = None): super(ImageViewWidget, self).__init__(parent) self.w = QtWidgets.QFrame() self.l = QtWidgets.QVBoxLayout() self.w.setLayout(self.l) self.setWidget(self.w) def setImages(self, *images): self.imageLabel = QtWidgets.QLabel() self.imageLabel.setScaledContents(True) self.l.addWidget(self.imageLabel) if not images[0].isNull(): self.imageLabel.setPixmap(QtGui.QPixmap.fromImage(images[0])) #self.normalSize() ## event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress, QtCore.Qt.Key_N, QtCore.Qt.NoModifier) ## QtWidgets.QApplication.sendEvent(self, event) def normalSize(self): self.w.adjustSize() def keyPressEvent(self, event): if event.key() == QtCore.Qt.Key_N: self.normalSize() if __name__ == '__main__': import sys app = QtWidgets.QApplication(sys.argv) imageViewer = ImageViewWidget() imageViewer.resize(800, 600) image1 = QtGui.QImage('test.png') imageViewer.setImages(image1) imageViewer.show() sys.exit(app.exec_())
score: 0
answers question: http://stackoverflow.com/q/48860153
has comment: http://stackoverflow.com/comment/84753462
type: Answer

http://stackoverflow.com/a/48844158
downvote count: 0
answers question: http://stackoverflow.com/q/48844055
has comment: http://stackoverflow.com/comment/84692663
type: Answer
has comment: http://stackoverflow.com/comment/84692702
accepted answer of: http://stackoverflow.com/q/48844055
score: 1
has body: You have to use raw_input if you use python 2. Anyway if I get what you wanna do, this should look like the basic starting main program: import random if __name__ == '__main__': print("Hello, world") while 1: sex = raw_input("What's your sex? ") # If user chooses Male the program will execute. if sex == 'Male': # This is where the list of male first names are stored. firstNameMale = ['Ughash', 'Spoguk', 'Truigig', 'Wudhagh', 'Wumkbanok', 'Hogug', 'Karrhig', 'Pargu', 'Xokuk', 'Furbog'] # This is where the list of male last names are stored. lastNameMale = ['Opkagut', 'Zombilge', 'Grushnag', 'Gujarek', 'Igmut', 'Gorgo', 'Filge', 'XorokuShamob', 'Zurgha'] # This is where the random function calls on the lists to assemble the name. firstName = random.choice(firstNameMale) lastName = random.choice(lastNameMale) print('Your name is ' + firstName + ' ' + lastName) break # If user chooses Female the program will execute. elif sex == "Female": # This is where the list of female first names are stored. firstNameFemale = ['Ughash', 'Spoguk', 'Truigig', 'Wudhagh', 'Wumkbanok', 'Hogug', 'Karrhig', 'Pargu', 'Xokuk', 'Furbog'] # This is where the list of female last names are stored. lastNameFemale = ['Opkagut', 'Zombilge', 'Grushnag', 'Gujarek', 'Igmut', 'Gorgo', 'Filge', 'XorokuShamob', 'Zurgha'] # This is where the random function calls on the lists to assemble the name. firstName = random.choice(firstNameFemale) lastName = random.choice(lastNameFemale) print('Your name is ' + firstName + ' ' + lastName) break # If user did not choose Male of Female program will execute. else: print('Please choose from Male or Female. Remember capitalization counts!') Here I made an infinite loop until you enter Male or Female. Hope it helps.
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48905380
accepted answer: http://stackoverflow.com/a/48905525
has body: I'm trying to filter a list based on an attribute. If I use the attribute as a string everything works fine: {% set ys = xs | selectattr("type", "equalto", "first") | list %} If I tried to use a variable (in my case a property of an enum) instead I get back an empty list {% set ys = xs | selectattr("type", "equalto", MyEnum.FIRST) | list %} The variable MyEnum.FIRST contains the string "first".
answer count: 1
favorite count: 0
upvote count: 5
has title: How can I use a variable in a jinja2 selectattr filter?
tagged with: python
type: AnsweredQuestion
tagged with: enums
downvote count: 0
tagged with: jinja2
type: Question
score: 5
has answer: http://stackoverflow.com/a/48905525

http://stackoverflow.com/a/48867114
has comment: http://stackoverflow.com/comment/84742881
has comment: http://stackoverflow.com/comment/84740568
has comment: http://stackoverflow.com/comment/84764588
has comment: http://stackoverflow.com/comment/84741110
has body: You don't need subprocess here and you must always avoid subprocess when you can (that means: 99.99% of time). As Joel pointed out in comments, maybe I should take a few minutes and bullet points to explain you why: Using subprocess (or similar) assume your code will always run on the exact same environment, that means same OS, version, shell, tools installed, etc.. This is really not fitted for a production grade code. These kind of libraries will prevent you to make "pythonic Python code", you will have to handle errors by parsing string instead of try / except, etc.. Tim Peters wrote the Zen of Python and I encourage you to follow it, at least 3 points are relevant here: "Beautiful is better than ugly.", "Readability counts." and "Simple is better than complex.". In other words: subprocess will only make your code less robust, force you to handle non-Python issues, force you to perform tricky computing where you could just write clean and powerful Python code. There are way more good reasons to not use subprocess, but I think you got the point. Just open files with open, here is a basic example you will need to adapt: import os for filename in os.listdir('./'): with open(filename, 'r') as fileh: with open('output.txt', 'a') as outputh: outputh.write(fileh.read()) Implementation example for your specific needs: import os sources = ['/tmp/folder01/', '/tmp/folder02/'] targets = ['/tmp/output/File1', '/tmp/output/File2'] # Loop in `sources` for index, directory in enumerate(sources): # Match `sources` file with expected `targets` directory output_file = targets[index] # Loop in files within `directory` for filename in os.listdir(directory): # Compute absolute path of file filepath = os.path.join(directory, filename) # Open source file in read mode with open(filepath, 'r') as fileh: # Open output file in append mode with open(output_file, 'a') as outputh: # Write content into output outputh.write(fileh.read()) Be careful, I changed your source and target values (/tmp…
has comment: http://stackoverflow.com/comment/84742473
type: Answer
has comment: http://stackoverflow.com/comment/84740324
has comment: http://stackoverflow.com/comment/84763538
downvote count: 0
has comment: http://stackoverflow.com/comment/84740783
score: 1
accepted answer of: http://stackoverflow.com/q/48866500
answers question: http://stackoverflow.com/q/48866500
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48865837
has comment: http://stackoverflow.com/comment/84734765
score: 0
tagged with: mocking
tagged with: black-box-testing
has comment: http://stackoverflow.com/comment/84735958
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84734777
has comment: http://stackoverflow.com/comment/84734952
tagged with: python
has body: all this won't work. even changing side_effect to something completelly different won't solve a problem. mock = unittest.mock.MagicMock() with unittest.mock.patch('builtins.set', mock): handle = set() print(mock.called) import builtins mock = unittest.mock.MagicMock() with unittest.mock.patch.object(builtins, "set"): handle = set() I actually need somehow to know, if nested function uses some classes\methods\structures. For instance, set(), tuple(), dict() | {}. For instance, it works with dict(), but when you use {}, there is False returns. Is there any convenient way to introspect code in assertions, thinking about it as a black-box?
tagged with: introspection
answer count: 0
type: UnansweredQuestion
type: Question
has title: How to catch set() usage in python3

http://stackoverflow.com/comment/121097573
has text: somehow "b'Content-Length: ' + f"{len(frame)}".encode() + b'\r\n'" even slows my programm
score: 0
type: Comment
comment on: http://stackoverflow.com/a/61501930
type: AnswerComment

http://stackoverflow.com/q/48955933
has answer: http://stackoverflow.com/a/48958291
tagged with: inheritance
possible better answer: http://stackoverflow.com/a/49038552
score: 0
has body: I want to run a set of tests under different conditions and therefore share these tests between two different TestCase-derived classes. One creates its own standalone session and the other attaches to an existing session and executes the same tests in there. I guess I'm kind of abusing the unittest framework when testing an API with it but it doesn't feel like it's too far from its original purpose. Am I good so far? I hacked a few things together and got it kind of running. But the way it's done, doesn't feel right and I'm afraid will cause problems sooner or later. These are the problems I have with my solution: When simply running the thing with PyCharm without limiting the tests, it attempts to run not only the intended StandaloneSessionTests and ExistingSessionTests but also GroupOfTests which is only the collection and has no session, i.e. execution context. I can make it not run GroupOfTests by not deriving that one from TestCase but then PyCharm complains that it doesn't know about the assert...() functions. Rightly so, because GroupOfTest only gets indirect access to these functions at runtime when a derived class also inherits from TestCase. Coming from a C++ background, this feels like black magic and I don't think I should be doing this. I tried passing the session creation classes to the constructor of GroupOfTests like this: __init__(self, session_class). But this causes problems when the unittest framework attempts to instantiate the tests: It doesn't know what to do with the additional __init__ parameter. I learned about @classmethod, which seems to be a way to get around the "only one constructor" limitation of Python but I couldn't figure out a way to get it running. I'm looking for a solution that lets me state something as straightforward as this: suite = unittest.TestSuite() suite.addTest(GroupOfTests(UseExistingSession)) suite.addTest(GroupOfTests(CreateStandaloneSession)) ... This is what I got so far: #!/usr/bin/python3 import unittest def ex…
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85082306
has answer: http://stackoverflow.com/a/49038552
type: Question
has title: Use different implementations of `setUp` and `tearDown` of unittest.TestCase instances
tagged with: python-unittest
accepted answer: http://stackoverflow.com/a/48958291
has comment: http://stackoverflow.com/comment/84919330
has comment: http://stackoverflow.com/comment/85060367
answer count: 2
tagged with: mixins
linked to: http://stackoverflow.com/q/1323455

http://stackoverflow.com/a/73444348
answers question: http://stackoverflow.com/q/48830946
has body: You can define a pipeline builder, that you can reuse to build pipelines. Each pipeline is a function that can be invoked with one argument or none (rarely used). When a pipeline is called it sequentially run every functions with previous function return value as argument. from functools import reduce import warnings # pipeline function builder def pipe(*funcs): """ Usage: pipe( lambda x: x+1, lambda x: x+20 )(50) Order of execution of functions is FIFO. FIFO = First In First Out """ # if no arguments return an identity function and warn the developer if not funcs: warnings.warn("""pipe() is useless when called without arguments. Please provide functions as arguments or remove call to pipe(). """) return lambda x=None: x # Identity function def runner(value=None): return reduce(lambda acc, curr: curr(acc), funcs, value) return runner # test 1 pipeline = pipe() print(pipeline()) # None # test 2 pipeline = pipe() print(pipeline(8)) # 8 # test 3 pipeline = pipe( lambda unused: 50 ) print(pipeline()) # 50 # test 4 -> Real Usage pipeline = pipe( lambda age: age >= 18, lambda is_adult: 'Adult' if is_adult else 'Minor' ) print(pipeline(12)) # Minor print(pipeline(20)) # Adult
score: 0
type: Answer

http://stackoverflow.com/comment/84721453
type: AnswerComment
comment on: http://stackoverflow.com/a/48858913
type: Comment
has text: @user3447273. No, strings should be fine. Feel free to change my example to see for yourself.
score: 0

http://stackoverflow.com/q/48854161
has comment: http://stackoverflow.com/comment/84712895
score: 1
upvote count: 1
accepted answer: http://stackoverflow.com/a/48855655
type: Question
has title: DLL load failed error with Python while trying to convert .dem files to .grid files
tagged with: dll
tagged with: gdal
has body: I've been trying to find a free and easy way to convert .dem files to .grid files, and I've been working on getting a python program that was online to do it. I've been getting an error that I don't understand, and looking it up online has shown me that people have gotten this error before, but not necessarily in the context that I'm finding it, so their solutions involve installing different modules that are not the one that I need. Here is my python installment: Python 3.4.0 (v3.4.0:04f714765c13) [MSC v.1600 64 bit (AMD64)] on win32 Here is how I installed a module I needed, called osgeo. I followed the steps based on the above python installment, making sure that I used the correct versions for everything: Instructions I used Following those instructions allowed me to get past an error that osgeo didn't exist, so at least I've made some progress in that aspect. Here is the code I've been trying to run: import sys import os import osgeo.gdal as gd from gdalconst import GA_ReadOnly, GDT_Byte, GDT_UInt16, GDT_Int16, \ GDT_UInt32, GDT_Int32, GDT_Float32, GDT_Float64 import struct # GDAL data types to packt data_types gd_type = {GDT_Byte: "b", GDT_UInt16: "H", GDT_Int16: "h", GDT_UInt32: "I", GDT_Int32: "i", GDT_Float32: "f", GDT_Float64: "d"} # establish input file ifilename = r"C:\Users\Nick\Desktop\sample.dem" # generate output file name ofilename = os.path.splitext(ifilename)[0] + ".grid" # use gdal to read DEM file idataset = gd.Open(ifilename, GA_ReadOnly) if idataset is None: print("Cannot read input file {}".format(ifilename)); sys.exit(2) # get size of dem cols = idataset.RasterXSize rows = idataset.RasterYSize # get and calculate coordinate limits tr = idataset.GetGeoTransform() xul = tr[0] yul = tr[3] xlr = xul + (cols - 1) * tr[1] ylr = yul + (rows - 1) * tr[5] # write data to binary output of = open(ofilename, "wb") of.write(struct.pack("2i", cols, rows)) of.write(struct.pack("4f", xul, ylr, xlr, yul)) band = idataset.GetRasterBand(1) d = band.ReadRaster(…
has comment: http://stackoverflow.com/comment/84712606
has comment: http://stackoverflow.com/comment/84712175
downvote count: 0
answer count: 1
tagged with: load
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48855655
type: AnsweredQuestion

http://stackoverflow.com/comment/84636522
score: 0
type: Comment
has text: no. I am not looking for files names without extensions. I am trying to read each pdf and copy its content into a new column. Before opening and reading PDFs, i would like to see if the file exists. To check that i am using `os.path.exists`. But if i use `os.path.exists(url)`, it returns wrong results as 'url' contains unnecessary stuff like `dtype:object`
comment on: http://stackoverflow.com/a/48816115
type: AnswerComment

http://stackoverflow.com/comment/84802181
score: 0
has text: the code works but what if i wanted to add new data to the existing one
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48896693

minimax
type: Tag
tags question: http://stackoverflow.com/q/48846735
tag name: minimax
tags question: http://stackoverflow.com/q/48957432

http://stackoverflow.com/q/48914161
type: Question
tagged with: dataframe
score: -1
answer count: 2
downvote count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48914249
upvote count: 1
accepted answer: http://stackoverflow.com/a/48914249
possible better answer: http://stackoverflow.com/a/63287871
favorite count: 0
has answer: http://stackoverflow.com/a/63287871
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
type: AnsweredQuestion
has title: How to write dataframe to csv, while updating and dropping duplicates in csv?
has comment: http://stackoverflow.com/comment/84834704
has body: I can successfully drop duplicates and update rows in an existing dataframe. When I write this dataframe too a csv that already has data in it, how do I do the same commands in the dataframe to the csv to drop duplicates and update rows. df: ID email date 0 a@a.com 2018-01-22 1 b@b.com 2018-01-20 csv: ID email date 0 d@d.com 2018-01-22 I need the csv to look like this: csv: ID email date 0 a@a.com 2018-01-22 1 b@b.com 2018-01-20 This is my code for pandas to drop and update in the dataframe: permanent=permanent.sort_values(['ID']).drop_duplicates(['ID'],keep='last') Not sure how to do the pandas line for the csv. Thank you in advance for your help.

http://stackoverflow.com/a/48896773
has body: Say suppose you wanted to add item to greetingInput through input, if greetingInput it is treated as string object, not as list object for which you intended to add. To avoid this you can categorize the lists through numbering. Based on that you can use if..elsif to add lists. the function code can be modified like below &lt;code&gt; userWord = input("Input the word: ") if userCategory == 1: greetingInput.append(userWord) &lt;/code&gt;
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48896633

http://stackoverflow.com/q/48857159
has title: Issue saving a retrained tensorflow model
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
has body: I am trying to load a model(previously saved), and save it after retraining. The loading works well, but I face issue with the saving it as below: sess=tf.Session() sess.run(init) loader = tf.train.import_meta_graph(self.model_path+'.meta') loader.restore(sess,self.model_path)#tf.train.latest_checkpoint('./')) print('Model restored') #retrain saver=tf.train.Saver() saver.save(sess, self.model_path) I don't face any similar issue with saving it the first time as below: saver=tf.train.Saver() sess=tf.Session() sess.run(init) #train saver.save(sess, self.model_path) The error I encounter is : File "/share/apps/python2.7-tensorflow-1.2.1/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1139, in __init__ self.build() File "/share/apps/python2.7-tensorflow-1.2.1/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 1170, in build restore_sequentially=self._restore_sequentially) File "/share/apps/python2.7-tensorflow-1.2.1/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 673, in build saveables = self._ValidateAndSliceInputs(names_to_saveables) File "/share/apps/python2.7-tensorflow-1.2.1/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 557, in _ValidateAndSliceInputs names_to_saveables = BaseSaverBuilder.OpListToDict(names_to_saveables) File "/share/apps/python2.7-tensorflow-1.2.1/lib/python2.7/site-packages/tensorflow/python/training/saver.py", line 535, in OpListToDict name) ValueError: At least two variables have the same name: Variable_15/Adam
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48861875
upvote count: 3
tagged with: machine-learning
tagged with: tensorflow
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/48861875

http://stackoverflow.com/a/48861875
accepted answer of: http://stackoverflow.com/q/48857159
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48857159
has comment: http://stackoverflow.com/comment/84761518
has body: You see this message because there are two Variables with the same name in the scope. The tf.train.import_meta_graph reads a graph from a file and adds all operations and tensors to the current existing graph. I am surprised that import_meta_graph does not even fire such an exception in the first place. See the full example to reproduce this behavior: import tensorflow as tf # tiny graph x = tf.placeholder(tf.float32, shape=[1, 2], name='input') output = tf.identity(tf.layers.dense(x, 1), name='output') cost = tf.reduce_sum(x * output) # create first time u'beta1_power:0', u'beta2_power:0' train_op = tf.train.AdamOptimizer().minimize(cost) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) saver = tf.train.Saver(tf.global_variables()) saver.save(sess, './adam/my_model') print([v.name for v in tf.global_variables()]) # create second time u'beta1_power:0', u'beta2_power:0' meta_graph = tf.train.import_meta_graph('./adam/my_model.meta') meta_graph.restore(sess, './adam/my_model') print([v.name for v in tf.global_variables()]) saver = tf.train.Saver(tf.global_variables()) # exception as there are now two times: u'beta1_power:0', u'beta2_power:0' saver.save(sess, './adam/my_model2') A solution is to either clear the graph using tf.reset_default_graph() before tf.trainimport_meta_graph use a new session for tf.train.import_meta_graph just load the weights using tf.train.Saver().restore(sess, '/tmp/model/my_model')
type: Answer
score: 0

http://stackoverflow.com/a/78300979
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48863734
downvote count: 0
has body: You should be able to use delete_path path = array("block", "2") stmt = ( update(Block) .values( { Block.randomblocks: Block.randomblocks.delete_path(path) } ) .where(...) ) https://docs.sqlalchemy.org/en/20/dialects/postgresql.html#sqlalchemy.dialects.postgresql.JSONB.Comparator.delete_path
type: Answer

http://stackoverflow.com/a/48953392
has comment: http://stackoverflow.com/comment/84917436
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84917263
downvote count: 0
has comment: http://stackoverflow.com/comment/84915879
has comment: http://stackoverflow.com/comment/84914125
accepted answer of: http://stackoverflow.com/q/48953331
has comment: http://stackoverflow.com/comment/84916263
type: Answer
has comment: http://stackoverflow.com/comment/84913581
has comment: http://stackoverflow.com/comment/84913812
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84919663
has comment: http://stackoverflow.com/comment/84913563
has comment: http://stackoverflow.com/comment/84916360
has comment: http://stackoverflow.com/comment/84914459
has body: Use os.listdir for iterating over the image files in the directory: for img_filename in os.listdir('my/path/to/images'): # in case you don't need to worry about anything but 'img'. x, y = img_filename.split('img') # in case you want to remove .png as in the comments. x, y = os.path.splitext(img_filename)[0].split('img') # do stuff here If you want to enforce your assumption, say of a .png file name, when iterating the directory, you could do this: raw_files = os.listdir(DIRECTORY) for img_filename in filter(lambda x: x.endswith('.png'), raw_files): ... or for img_filename in [x for x in os.listdir(DIRECTORY) if x.endswith('.png')]: ... or various other variations of the idea. Note that you may also want to further post-process the result of x and y above, like converting them to int, or removing any file extension (if present in the file name), and there are various other helper functions in the os module that will help with it. This solution makes a hard assumption that the files follow your given format exactly, and that the special string img only appears once in the file name, and acts as a perfect separator between the X portion and the Y portion you need. You'll have to do some additional processing if this assumption is not true.
answers question: http://stackoverflow.com/q/48953331

http://stackoverflow.com/q/48894258
has comment: http://stackoverflow.com/comment/84794870
answer count: 1
has comment: http://stackoverflow.com/comment/84794404
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84794729
has comment: http://stackoverflow.com/comment/84794725
upvote count: 1
downvote count: 1
type: Question
has body: In Python3 and pandas I need to load a .txt file. It starts with a header. Columns have quotation marks and are divided by ";" Lines with data follow the same pattern. Example of the header and the first two lines: "Cód. Eleição";"Desc. Eleição";"Data e hora";"CNPJ Prestador Conta";"Sequencial Candidato";"UF";"Sigla Partido";"Numero candidato";"Cargo";"Nome candidato";"CPF do candidato";"Numero Recibo Eleitoral";"Numero do documento";"CPF/CNPJ do doador";"Nome do doador";"Nome do doador (Receita Federal)";"Sigla UE doador";"Número partido doador";"Número candidato doador";"Cod setor econômico do doador";"Setor econômico do doador";"Data da receita";"Valor receita";"Tipo receita";"Fonte recurso";"Especie recurso";"Descricao da receita";"CPF/CNPJ do doador originário";"Nome do doador originário";"Tipo doador originário";"Setor econômico do doador originário";"Nome do doador originário (Receita Federal)" "143";"Eleições Gerais 2014";"09/07/201617:15:01";"20571108000141";"10000000120";"AC";"PC do B";"65013";"Deputado Estadual";"FRANCISCO EDUARDO SARAIVA DE FARIAS";"27648176220";"650130700000AC000040";"#NULO";"20614471000105";"Direção Estadual/Distrital";"ELEICAO 2014 COMITE FINANCEIRO AC DISTRITAL/ESTADUAL PARA DEPUTADO FEDERAL PC DO B";"AC";"65";"65013";"9492800";"Atividades de organizações políticas";"10/10/201400:00:00";"5010";"Recursos de partido político";"Outros Recursos nao descritos";"Estimado";"GASOLINA";"#NULO";"#NULO";"#NULO";"#NULO";"#NULO" "143";"Eleições Gerais 2014";"09/07/201617:15:01";"20572570000163";"10000000121";"AC";"PC do B";"65789";"Deputado Estadual";"JANILSON LOPES LEITE";"61275468268";"657890700000AC000036";"#NULO";"20614471000105";"Direção Estadual/Distrital";"ELEICAO 2014 COMITE FINANCEIRO AC DISTRITAL/ESTADUAL PARA DEPUTADO FEDERAL PC DO B";"AC";"65";"65789";"9492800";"Atividades de organizações políticas";"10/10/201400:00:00";"4008";"Recursos de partido político";"Outros Recursos nao descritos";"Estimado";"GASOLINA";"#NULO";"#NULO";"#NULO";…
has title: How to open in pandas a TXT with space between rows and header?
has answer: http://stackoverflow.com/a/48894461
has comment: http://stackoverflow.com/comment/84794575
has comment: http://stackoverflow.com/comment/84794446
score: 0
tagged with: pandas

http://stackoverflow.com/comment/84906687
type: QuestionComment
has text: Keys are tuples with 3 integer values and values (list entries) are strings. For example: { (1, 1, 1): ['a', 'b', 'c'] }
comment on: http://stackoverflow.com/q/48950125
score: 0
type: Comment

http://stackoverflow.com/comment/84812133
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48903362
has text: could you explain why the use of processes is more appropriate then the use of threads in this example?

http://stackoverflow.com/q/48852907
type: UnansweredQuestion
has title: Nan in summary histogram for: model/Training/dense/kernel/gradients
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/48871753
score: 0
answer count: 1
tagged with: tensorboard
tagged with: python
has body: I'm building a dataset with 45 features, all numerical, and normalized so values gets between -1 and 1. Here is the normalization: def normalize(train, test, cv): normalized_train=(train-train.mean())/train.std() normalized_test=(test-test.mean())/test.std() normalized_cv=(cv-cv.mean())/cv.std() return normalized_train, normalized_test, normalized_cv X_train, X_test, X_cv = normalize(X_train, X_test, X_cv) Then I am building the tensorflow dataset and iterator and pass it to my model. Here is the model: with tf.name_scope('model'): regularizer = tf.contrib.layers.l2_regularizer(scale=0.1) net = tf.layers.dense(features, 40, activation=tf.nn.relu, kernel_regularizer=regularizer, kernel_initializer=tf.contrib.layers.xavier_initializer()) net = tf.layers.dense(net, 60, activation=tf.nn.relu, kernel_regularizer=regularizer, kernel_initializer=tf.contrib.layers.xavier_initializer()) net = tf.layers.dense(net, 30, activation=tf.nn.relu, kernel_regularizer=regularizer, kernel_initializer=tf.contrib.layers.xavier_initializer()) net = tf.layers.dense(net, 12, activation=tf.nn.relu, kernel_regularizer=regularizer, kernel_initializer=tf.contrib.layers.xavier_initializer()) prediction = tf.layers.dense(net, 2, activation=tf.nn.sigmoid) And finally my loss function, my optimizer and the gradient calculation then applied: with tf.name_scope('Loss'): loss = tf.losses.softmax_cross_entropy(onehot_labels=labels, logits=prediction) tf.summary.scalar('Loss', loss) with tf.name_scope('Training'): opt = tf.train.AdamOptimizer(learning_rate = learning_rate) grads = opt.compute_gradients(loss) for grad, var in grads: if grad is not None: tf.summary.histogram(var.op.name + '/gradients', grad) train_op = opt.apply_gradients(grads) When I run this I get the following error: Caused by op 'model/Training/dense/kernel/gradients', defined at: File "c:\Users\123456\Google Drive\Projects\GIT\Churn_TF\churn_1.2_local_dataset.py", line 103, in &lt;module&gt; tf.summary.histogram(var.op.name + '/grad…

http://stackoverflow.com/comment/84689282
score: 0
type: Comment
has text: I think typically with this pattern of parallelism, the map function takes a function, then an iterable, whose only argument is each item in the iterable. Your function is both generating the list of URLs and processing them. Get the data structure separately ("urls"), then make sure your worker function only accepts one URL at a time.
type: QuestionComment
comment on: http://stackoverflow.com/q/48842585

http://stackoverflow.com/comment/84672869
score: 0
type: Comment
type: QuestionComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165304/discussion-between-ruth-and-aws-apprentice).
comment on: http://stackoverflow.com/q/48833839

http://stackoverflow.com/q/48956597
has comment: http://stackoverflow.com/comment/85068024
tagged with: openpyxl
linked to: http://stackoverflow.com/q/16923281
upvote count: 1
tagged with: excel
type: Question
has title: Write to Excel - Reading CSV with Pandas & Openpyxl - Python
has comment: http://stackoverflow.com/comment/84920997
has comment: http://stackoverflow.com/comment/84920981
has body: I have a csv report thats saved to a specific folder daily. What I would really like to do is to automate &amp; open that csv from the folder every morning, extract what I need, and have it append to my spreadsheet. Baby steps first, I'm a newbie. I seem to be reading the csv just fine. (Here is a link to it) https://drive.google.com/open?id=16leX2pBV1-kXUtufOn0w00Uq9FrddZl2 I'm trying to append the dataframes to different sheets in my excel workbook and I'm screwing up when I start to use openpyxl. import pandas as pd import openpyxl file = ('artb.csv') df = pd.read_csv(file, sep=',',header=0,usecols=[0,1,2,3]) df = pd.DataFrame(list) print (df) output: Date Balance Fwd Charges Credits 0 3/4/2018 1,905.00 69,799,377.71 73,405,427.70 1 3/4/2018 0 1,221,028.15 596,488.63 df1=[df.iloc[0]] df2=[df.iloc[1]] print (df1) output: Date 3/4/2018 Balance Fwd 1,905.00 Charges 69,799,377.71 Credits 73,405,427.70 Name: 0, dtype: object wb = openpyxl.Workbook() wb = openpyxl.load_workbook(filename = 'summary.xlsx') sheets = wb.sheetnames # Stu Tab ws = wb[sheets[1]] ws2 = wb[sheets[2]] This is where it messes up, I've tried at least a dozen different things. #append df1 to Stu Sheet for row in df1: ws.append(row) #append df2 to Sp Sheet for row in df2: ws.append(row) wb.save("summary.xlsx") It's not giving me errors now, but its not writing anything :( I'm going to keep messing with it. I'd appreciate any advice. Thank you!
has comment: http://stackoverflow.com/comment/85243754
tagged with: pandas
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48956615
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/85063676
tagged with: python
has answer: http://stackoverflow.com/a/48956615
has comment: http://stackoverflow.com/comment/84920315
type: AnsweredQuestion
score: 1

http://stackoverflow.com/comment/84692046
comment on: http://stackoverflow.com/q/48843859
has text: Please fix your indentation, it is very important in python.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84634638
comment on: http://stackoverflow.com/a/48807592
has text: Yes its exactly the same :) Just noticed the second example
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84682570
has text: Moreover `loginFieldID` in `driver.find_element_by_id(loginFieldID)` etc seems to me as a placeholder rather than being the actual ones.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48837221
type: Comment

http://stackoverflow.com/a/48807772
score: 9
has comment: http://stackoverflow.com/comment/84618819
has body: I think need join what align for same index name date in both DataFrames: df = df1.join(df2) print (df) x y z level name date alpha A 2018-01-01 5 4 123 2018-01-02 6 6 124 2018-01-03 7 5 125 B 2018-01-01 3 5 123 2018-01-02 4 4 124 2018-01-03 5 3 125 beta C 2018-01-01 1 2 123 2018-01-02 1 0 124 2018-01-03 0 1 125 D 2018-01-01 12 13 123 2018-01-02 15 14 124 2018-01-03 14 13 125
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84618734
has comment: http://stackoverflow.com/comment/84618732
type: Answer
accepted answer of: http://stackoverflow.com/q/48807723
has comment: http://stackoverflow.com/comment/84618772
answers question: http://stackoverflow.com/q/48807723
upvote count: 9
has comment: http://stackoverflow.com/comment/84618683

http://stackoverflow.com/comment/84664393
score: 0
has text: @StefanPochmann well actually I'm not sure. I just want to show status of every ports if the user doesn't specify the port number.
type: QuestionComment
comment on: http://stackoverflow.com/q/48830120
type: Comment

http://stackoverflow.com/a/48877662
answers question: http://stackoverflow.com/q/48870380
upvote count: 2
has body: 'tree_' is not RandomForestClassifier attribute. It is the attribute of DecisionTreeClassifiers. You should not use this while using RandomForestClassifier, there is no need of it.
downvote count: 2
score: 0
type: Answer

http://stackoverflow.com/comment/84889192
score: 0
type: Comment
type: QuestionComment
has text: @eyllanesc thanks. Now these are the errors: https://pastebin.com/kiLCDSqk have you had anything like that?
comment on: http://stackoverflow.com/q/48936524

http://stackoverflow.com/a/48934595
has comment: http://stackoverflow.com/comment/85879311
upvote count: 3
answers question: http://stackoverflow.com/q/48934473
has comment: http://stackoverflow.com/comment/84876017
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84876040
has comment: http://stackoverflow.com/comment/85880146
has body: You can use itertools.groupby: import itertools tuple1 = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence', 'which is incomplete.') new_data = tuple(' '.join(i[-1] for i in b) for _, b in itertools.groupby(enumerate(tuple1), key=lambda x:x[-1][0].islower() or tuple1[x[0]+1][0].islower() if x[0]+1 &lt; len(tuple1) else True)) Output: ('Traditionally, companies have been communicating with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence which is incomplete.')
type: Answer
has comment: http://stackoverflow.com/comment/85879194
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/85879253
has comment: http://stackoverflow.com/comment/85878982
has comment: http://stackoverflow.com/comment/85878843
accepted answer of: http://stackoverflow.com/q/48934473

http://stackoverflow.com/q/48943503
type: Question
type: AnsweredQuestion
has body: I've setted up travis.ci to automatically deploy to pypi a package when a push to master is tagged. The problem is that in my setup.py I've to specify the package version, and sometimes I forget that resulting in a non deployed package (or does Pypi overwrites the old one?) Nevertheless, Is there a way to match the package version on pypi as the tag that is assigned to the commit?
accepted answer: http://stackoverflow.com/a/48944069
tagged with: pypi
answer count: 1
downvote count: 0
tagged with: travis-ci
favorite count: 0
has title: Travis pypi package version
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/48944069
upvote count: 2

http://stackoverflow.com/comment/84843047
type: Comment
comment on: http://stackoverflow.com/q/48918277
type: QuestionComment
score: 0
has text: Please fix your indentation so it matches your real code.

http://stackoverflow.com/comment/84833916
type: Comment
type: QuestionComment
has text: Do you mind to share your df with `df.to_dict()`?
comment on: http://stackoverflow.com/q/48913780
score: 0

http://stackoverflow.com/a/48822324
score: 0
accepted answer of: http://stackoverflow.com/q/48821832
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48821832
has body: This should help. import requests from bs4 import BeautifulSoup t = """ date LME Nickel Cash-Settlement LME Nickel 3-month LME Nickel stock 15. Febuary 2018 14.150,00 14.200,00 339.708 14. Febuary 2018 13.630,00 13.660,00 338.652 13. Febuary 2018 13.215,00 13.255,00 339.006 12. Febuary 2018 12.965,00 13.005,00 341.160 09. Febuary 2018 12.970,00 13.000,00 342.204 08. Febuary 2018 13.025,00 13.080,00 343.896 07. Febuary 2018 13.490,00 13.500,00 347.148 06. Febuary 2018 13.370,00 13.380,00 349.476 05. Febuary 2018 13.540,00 13.585,00 350.652 02. Febuary 2018 13.795,00 13.830,00 353.592 01. Febuary 2018 13.545,00 13.555,00 355.266 date LME Nickel Cash-Settlement LME Nickel 3-month LME Nickel stock 31. January 2018 13.555,00 13.550,00 357.012 30. January 2018 13.650,00 13.700,00 359.292 29. January 2018 13.890,00 13.890,00 360.714 26. January 2018 13.750,00 13.770,00 361.782 25. January 2018 13.695,00 13.725,00 362.058 24. January 2018 13.000,00 13.005,00 362.196 23. January 2018 12.750,00 12.820,00 362.868 22. January 2018 12.720,00 12.755,00 363.168 19. January 2018 12.595,00 12.610,00 361.500 18. January 2018 12.455,00 12.500,00 362.532 17. January 2018 12.415,00 12.470,00 364.968 16. January 2018 12.415,00 12.490,00 364.218 15. January 2018 12.835,00 12.875,00 364.248 12. January 2018 12.670,00 12.690,00 365.994 11. January 2018 12.835,00 12.890,00 368.292 10. January 2018 12.900,00 12.950,00 365.868 09. January 2018 12.515,00 12.565,00 367.056 08. January 2018 12.450,00 12.490,00 368.430 05. January 2018 12.500,00 12.505,00 365.070 04. January 2018 12.615,00 12.680,00 365.934 03. January 2018 12.465,00 12.525,00 366.072 02. January 2018 12.690,00 12.730,00 366.612 """ soup = BeautifulSoup(t, "html.parser") res = [] for tr in soup.findAll("table"): for td in tr.find_all("tr", class_=["even", "odd"]): print td.td.text.replace(".", ""), " = ", td.find('td', class_="last").text Output: 15 Febuary 2018 = 339.708 14 Febuary 2018 = 338.652 13 Febuary 2018 = 339.006 12 Febu…

http://stackoverflow.com/a/48823841
score: -1
has comment: http://stackoverflow.com/comment/85028407
has comment: http://stackoverflow.com/comment/85022967
downvote count: 2
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48823661
has comment: http://stackoverflow.com/comment/85022874
has body: Try this (with page_title being the title of the popup window and assuming you are on a windows machine) : from win32com.client import Dispatch autoit = Dispatch("AutoItX3.Control") def _window_movement_windows(page_title): autoit.WinSetOnTop(page_title, "", 1) autoit.WinActivate(page_title, "") autoit.WinWaitActive(page_title) An example how to setup AutoIt with python can be found here : Calling AutoIt Functions in Python
has comment: http://stackoverflow.com/comment/85028060

http://stackoverflow.com/comment/106888452
score: 2
comment on: http://stackoverflow.com/a/48987535
type: AnswerComment
has text: but what if you want to receive on that sqs?
type: Comment

http://stackoverflow.com/comment/84778590
comment on: http://stackoverflow.com/q/48884058
score: 0
type: QuestionComment
type: Comment
has text: I don't understand how your second solution works at all. Assuming all_words is a set, `keywords__overlap` would create a `NameError` I think.

http://stackoverflow.com/q/48908353
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/48909658
linked to: http://stackoverflow.com/q/2255878
type: Question
answer count: 2
downvote count: 0
tagged with: http://stackoverflow.com/tag/csv
has body: I have a CSV file that has 3 columns. Let's say: a, b, c. I'm using csv.dictReader to read it and add another column that has just the name of the file on each row. This is my function: def addFilename(self): with open(self.datafile, "r") as f: reader = csv.DictReader(f, delimiter='|') for a, b, c in reader: #Get filename filename = self.getFilename() yield { "_source": { "a": a, "b": b, "c": c, "filename": filename } } Now I'd like to generalize that behavior for many different CSV files. Those files have different number of columns and different column names. Is there a way to do so? I don't want to modify the CSV file. The only thing I know is that I can get the fieldnames (and the number of fields) using reader.fieldnames, but I don't know how I could use that in a yield.
favorite count: 0
has answer: http://stackoverflow.com/a/48908503
has title: Adding a column to dictReader without modifying the CSV file
upvote count: 2
type: UnansweredQuestion

http://stackoverflow.com/q/48953569
favorite count: 0
has body: I'm using Pandas with a DataFrame called df. I'm extracting new features with it and combining the resulting two new dataframes with pd.concat. Here's my function: def get_processed_df(df, rare_cols, threshold=10): print("df at start", df.shape) df = df[pd.notnull(df["FullDescription"]) &amp; pd.notnull(df["Title"]) &amp; pd.notnull(df["SalaryNormalized"])] print("df after filtering nulls", df.shape) tfidf_desc = get_tfidf_df(df, "FullDescription", max_features=100, prefix="DESC", tokenize=tokenize) print("tfidf_desc shape: ", tfidf_desc.shape) tfidf_title = get_tfidf_df(df, "Title", max_features=100, prefix="TITLE", tokenize=tokenize) print("tfidf_title shape: ", tfidf_title.shape) df.drop("FullDescription", inplace=True, axis=1) df.drop("Title", inplace=True, axis=1) final_df = pd.concat([df, tfidf_desc, tfidf_title], axis=1) print("final df shape: ", final_df.shape) return final_df When I run this, I get the following output: df at start (10000, 12) df after filtering nulls (9999, 12) tfidf_desc shape: (9999, 100) tfidf_title shape: (9999, 100) final df shape: (10000, 210) So my filtering has removed one row in my original df and both tfidf_desc and tfidf_title dataframes have 9,999 rows also. I concatentate them with pd.concat using axis=1 and somehow end up with a DataFrame of 10,000 rows, with NaNs for all of the "Title" and "FullDescription" based features. Any idea why this is happening? Thanks!
tagged with: pandas
linked to: http://stackoverflow.com/q/40339886
has title: Pandas: Concat adds a row unexpectedly
duplicate of: http://stackoverflow.com/q/40339886
has comment: http://stackoverflow.com/comment/84914219
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84927785
upvote count: 5
tagged with: dataframe
type: Question
score: 5
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/50581739
has comment: http://stackoverflow.com/comment/84927625

http://stackoverflow.com/q/48837160
has answer: http://stackoverflow.com/a/48839447
tagged with: event-loop
has body: I'm going through some asyncio source for networking and implementation raised a question in my head. To create a non-blocking I/O when waiting for the data to arrive from a socket, asyncio.StreamReader.read() at its end calls _wait_for_data method that creates an empty Future and awaits it. That future is set as finished (which allows it to be finally awaited) in _wakeup_waiter method that is called when a new data arrives to the stream (feed_data method). That makes complete sense. My question is: Why not use asyncio.Event? It feels to me like Event was designed exactly for these purposes. In fact, you wouldn't have to create a new Future on each _wait_for_data call, but would initialize a single Event in a class and would simply toggle its value during its lifetime. It also has specific .wait() method for awaiting its value to become True (for when the new data arrives from the socket). Can anyone elaborate if there's an actual difference between the two approaches? Or is it just a method chosen arbitrarily?
upvote count: 6
tagged with: python-asyncio
has answer: http://stackoverflow.com/a/48840608
tagged with: synchronization
favorite count: 0
score: 6
tagged with: python
type: AnsweredQuestion
downvote count: 0
has title: asyncio: Event vs Future for synchronization
accepted answer: http://stackoverflow.com/a/48839447
possible better answer: http://stackoverflow.com/a/48840608
type: Question
answer count: 2

http://stackoverflow.com/a/48879483
has body: try: chosen_car = int(input("&gt; ")) except ValueError: print("Don't waste my time, choose a correct number.") choose_a_car() This code snippet uses recursion. Therefore, if the user enters an invalid input, the program enters the except block and calls the function again. And if the user enters a correct number in the second call, the second call terminates successfully and you turn back to the first function call. However, in the first call, chosen_car is not defined because of the invalid input. Therefore the program crashes with the error. Instead of recursion, you can try to use a flag as follows: myFlag = True while( myFlag): try: chosen_car = int(input("&gt; ")) myFlag = False except ValueError: print("Don't waste my time, choose a correct number.") By doing this, if the program crashes in chosen_car = int(input("&gt; ")) line, myFlag is not set to False and the program continues to get inputs from the user. I have not checked the code, but I suppose that should work.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48879378
type: Answer
answers question: http://stackoverflow.com/q/48879378
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84794817

http://stackoverflow.com/comment/84863196
comment on: http://stackoverflow.com/a/48928441
has text: can you suggest which of the proposed methods is the most efficient? I think 2) should be the best option, right?
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84779676
type: Comment
comment on: http://stackoverflow.com/a/48886891
type: AnswerComment
score: 0
has text: @Victor In your case, yes thats the only split. Have you tried plotting the tree?

ubuntu
tags question: http://stackoverflow.com/q/48960009
tags question: http://stackoverflow.com/q/48824326
tags question: http://stackoverflow.com/q/48850766
tags question: http://stackoverflow.com/q/48872120
tags question: http://stackoverflow.com/q/48820732
tags question: http://stackoverflow.com/q/48852772
tags question: http://stackoverflow.com/q/48961362
tags question: http://stackoverflow.com/q/48818833
tags question: http://stackoverflow.com/q/48883332
tags question: http://stackoverflow.com/q/48913770
tag name: ubuntu
tags question: http://stackoverflow.com/q/48844547
tags question: http://stackoverflow.com/q/48894529
type: Tag
tags question: http://stackoverflow.com/q/48850731

variable-length
tags question: http://stackoverflow.com/q/48955868
tag name: variable-length
type: Tag

http://stackoverflow.com/comment/84659870
comment on: http://stackoverflow.com/q/48828007
type: Comment
type: QuestionComment
has text: Possible duplicate of [Python split string by space and strip newline char](https://stackoverflow.com/questions/25253120/python-split-string-by-space-and-strip-newline-char)
score: 0

http://stackoverflow.com/q/48862350
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python
has body: For example, if I enter CH3CH3 currently using counter, my program will read it as just 2 'H' in total, unlike the 6 that I want. How do I work around this? Thanks
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/84727730
type: Question
score: -1
has answer: http://stackoverflow.com/a/48862440
accepted answer: http://stackoverflow.com/a/48862440
has title: How to read 'H3' as 3 H values?

http://stackoverflow.com/a/48819633
has comment: http://stackoverflow.com/comment/84643284
downvote count: 2
has comment: http://stackoverflow.com/comment/84643291
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84643345
has comment: http://stackoverflow.com/comment/84644277
has comment: http://stackoverflow.com/comment/84643627
has comment: http://stackoverflow.com/comment/84643503
has body: Let me know if this is what you are looking for: import re def smallest_between_two(a, b, text): return min(re.findall(re.escape(a)+"(.*?)"+re.escape(b),text), key=len) print(smallest_between_two(' ', '(', 'def test()')) print(smallest_between_two('[', ']', '[this one][not this one]')) print(smallest_between_two('paste ', '/', '@paste "game_01/01"')) Output: test this one "game_01 To add an explanation to what this does: re.findall(): Return all non-overlapping matches of pattern in string, as a list of strings re.escape() Escape all the characters in pattern except ASCII letters and numbers. This is useful if you want to match an arbitrary literal string that may have regular expression metacharacters in it (.*?) .*? matches any character (except for line terminators) *? Quantifier — Matches between zero and unlimited times, as few times as possible, expanding as needed (lazy) So our regular expression matches any character (not including line terminators) between two arbitrary escaped strings, and then returns the shortest length string from the list that re.findall() returns.
has comment: http://stackoverflow.com/comment/84643321
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/48819569
score: 2
has comment: http://stackoverflow.com/comment/84643700
accepted answer of: http://stackoverflow.com/q/48819569
has comment: http://stackoverflow.com/comment/84643518
has comment: http://stackoverflow.com/comment/84643312
has comment: http://stackoverflow.com/comment/84643400

http://stackoverflow.com/q/48898896
tagged with: selenium
upvote count: 1
has comment: http://stackoverflow.com/comment/84854755
has title: Python 'For' Loops: How to store the output in a Dictionary
tagged with: web-scraping
type: Question
has comment: http://stackoverflow.com/comment/84855606
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has body: I'm trying to scrape the website named below, my code scrapes the names of NGOs and the related information data off of it, but it doesnt store them together in one Dict. Individually, my for loops are getting the data, but they don't together. So, my Dict ends up storing either the last value of NGO_name or data stored in ITEM variable below. And when I run the two 'for' loops separately, keeping the other loop commented out, I get, {'NGO_Name': 'INDIA INCLUSION FOUNDATION', 'Pancard': 'AABTI3598J'} Together, they dont work. How should I achieve this? 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 driver = webdriver.Safari() wait = WebDriverWait(driver, 2) driver.get("site") it_data = {} while True: for elem_li in driver.find_elements_by_class_name("exempted-detail"): for item in elem_li.find_elements_by_tag_name("li"): it_data[item.find_element_by_tag_name('strong').text] = item.find_element_by_tag_name('span').text for elem, pan_li in zip(driver.find_elements_by_class_name("fc-blue fquph"),driver.find_elements_by_class_name("pan-id")): it_data["NGO_Name"] = elem.text.replace(pan_li.text, '') it_data["Pancard"] = pan_li.text print (it_data) try: wait.until(EC.presence_of_element_located((By.ID, "ctl00_SPWebPartManager1_g_d6877ff2_42a8_4804_8802_6d49230dae8a_ctl00_imgbtnNext"))).click() wait.until(EC.staleness_of(elem)) except Exception as e: print(e) driver.quit()
tagged with: python
has answer: http://stackoverflow.com/a/48930191
score: 1

http://stackoverflow.com/comment/84865519
type: Comment
has text: You have the first, the last and the number of elements. You don't need anything else to calculate the sum.
comment on: http://stackoverflow.com/q/48929281
score: 3
type: QuestionComment

http://stackoverflow.com/comment/84955247
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48955041
score: 0
has text: I think in this example: https://stackoverflow.com/a/48954998/4045774 should answer the question how to read and write data into the HDF5 format. If not feel free to ask

http://stackoverflow.com/comment/84839031
comment on: http://stackoverflow.com/q/48916262
type: Comment
has text: Can you print `inv` and update your question with it?
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84834336
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48913065
has text: Oh I understand your question better now - I'll see if I can figure it out

http://stackoverflow.com/q/48820483
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48820924
has comment: http://stackoverflow.com/comment/84645043
type: Question
has title: My JavaScript Post and Get functions with python server are out of order
tagged with: server
tagged with: javascript
tagged with: post
tagged with: get
score: 0
answer count: 1
has body: For my class I am making a simple web app that essentially is a picture that can be commented on. The problem is every time I type in a new comment, it doesn't get displayed, but rather the previous comment gets displayed. It appears that the GET gets called before the POST can finish updating the list on the server. However, maybe the problem is somewhere else, I don't know. I've done some research and it seems like the problem is due to asynchronization, however everything I've tried from reading up on that doesn't work the way I implement it, including callback functions. Here is my code: Javascript var messages = [] function getData() { fetch('http://localhost:8080/bananas').then(function(response) { return response.json(); }).then(function(data) { messages = [] for (i=0; i < Object.keys(data).length; i++) { messages.push(data[i]); console.log(data[i]); } }) } function update() { var box = document.getElementById("messages"); box.innerHTML = ""; getData(); for (i=0; i < messages.length; i++) { var newDiv = document.createElement("div"); newDiv.className = "comment"; var curM = document.createTextNode(messages[i]); newDiv.appendChild(curM); box.appendChild(newDiv); } document.getElementById("comment").value = ""; } update(); var submit = document.getElementById("submit"); submit.onclick = function () { postData(); update(); } var clickenter = document.getElementById("comment"); clickenter.addEventListener("keyup", function(event) { event.preventDefault(); if (event.keyCode === 13) { document.getElementById("submit").click(); } }); function postData() { var content = document.getElementById("comment").value; if (content.length > 0) { message = "message=" + encodeURIComponent(content) fetch('http://localhost:8080/bananas', { body: message, method: 'POST', header: { 'Content-Type': 'application/x-www-form-urlencoded' } }) } } HTML Page Title Comments My Python server: from http.server import BaseHTTPRequestHandler, HTTPServer from urllib.parse import parse_qs import…
has answer: http://stackoverflow.com/a/48820924

http://stackoverflow.com/q/48852970
has body: I implemented an LSTM with Keras and trained it on a corpus. Now I want to take the output of the NN and pass it as input to another NN model and test on a test set. I saved the model of the NN, but I do not know how to extract the output and feed it to the other NN. How can I do it? This is my code: model = Sequential() model.add(Embedding(vocab_size, 50, input_length=seq_length)) model.add(LSTM(100, return_sequences=True)) model.add(LSTM(100)) model.add(Dense(100, activation='relu')) model.add(Dense(vocab_size, activation='softmax')) print(model.summary()) # compile model model.compile(loss='categorical_crossentropy', optimizer='adam', metrics= ['accuracy']) # fit model model.fit(X, y, batch_size=128, epochs=500) # save the model to file model.save('model.h5')
favorite count: 0
possible better answer: http://stackoverflow.com/a/64481356
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84709396
upvote count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/48853075
type: Question
tagged with: neural-network
has title: How to use output of Neural Network as input for another NN in Keras
tagged with: lstm
answer count: 2
has answer: http://stackoverflow.com/a/64481356
accepted answer: http://stackoverflow.com/a/48853075
score: 1
tagged with: keras

http://stackoverflow.com/q/48939280
has comment: http://stackoverflow.com/comment/84886323
has comment: http://stackoverflow.com/comment/84886085
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84886015
has body: Consider the following SQLAlchemy code class Foo(Base): __tablename__ = 'currency' id = Column(Integer, primary_key=True) name = Column(String(40), nullable=False, unique=True) symbol = Column(String(4), nullable=False, unique=True) l = session.query(Foo.symbol, Foo.id).all() In the last line, I am trying to generate a list of the symbol-id pairs. It produces the following error: NameError: name 'Foo' is not defined I tried the following and got the errors as specified: l = session.query(models.Foo.symbol, models.Foo.id).all() #note: The Foo object is in the models.py file #error: NameError: name 'models' is not defined l = session.query(symbol, id).all() #error: sqlalchemy.exc.CompileError: Cannot compile Column object until its 'name' is assigned. l = session.query(self.symbol, self.id).all() #error: NameError: name 'self' is not defined So how do I pass in Foo object's column names to the SqlAlhemy query from inside the Foo class? Why am I doing this? I am then converting the list to a dictionary and only access the dictionary from code throughout the program since its values are seldom changed. So I want to populate it once and then access it many many times without hitting the DB again. And I want to keep it in the Foo Class which I believe is where it belongs. If there is a better way to do this please do let me know.
has answer: http://stackoverflow.com/a/48940137
upvote count: 1
has comment: http://stackoverflow.com/comment/84886552
type: Question
has title: how to access a class attribute from within the class in Python
has comment: http://stackoverflow.com/comment/84885745
score: 1
has comment: http://stackoverflow.com/comment/84885802
has comment: http://stackoverflow.com/comment/84885709
tagged with: sqlalchemy
has comment: http://stackoverflow.com/comment/84885747
accepted answer: http://stackoverflow.com/a/48940137
has comment: http://stackoverflow.com/comment/84885778
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84886555
favorite count: 0

http://stackoverflow.com/a/48824861
answers question: http://stackoverflow.com/q/48823152
downvote count: 0
type: Answer
upvote count: 3
has body: If you have a lot of features (words), then it makes sense to use sparse matrices in order to use memory much more efficiently: In [120]: from sklearn.feature_extraction.text import CountVectorizer In [121]: cvect = CountVectorizer() In [122]: data = data.join(pd.SparseDataFrame(cvect.fit_transform(data.pop(1)), data.index, cvect.get_feature_names(), default_fill_value=0)) In [123]: data Out[123]: 0 event2 event3 event4 0 userA 1 1 0 1 userB 0 1 1 2 userC 1 0 0 In [124]: data.memory_usage() Out[124]: Index 80 0 24 event2 16 event3 16 event4 8 dtype: int64
score: 3

http://stackoverflow.com/a/48889118
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/84784073
has body: You need to go to your settings.py file and add xadmin to the INSTALLED_APPS list. See the documentation here: https://docs.djangoproject.com/en/2.0/ref/applications/#for-application-users
score: 4
has comment: http://stackoverflow.com/comment/102650860
accepted answer of: http://stackoverflow.com/q/48889074
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48889074
has comment: http://stackoverflow.com/comment/84783369
has comment: http://stackoverflow.com/comment/84783644
type: Answer
has comment: http://stackoverflow.com/comment/84828026

http://stackoverflow.com/a/71729267
score: 0
has body: I wanted to store a small amount of metadata with my dataframe when I asked this question. Monkey-patching information is maybe the worst option :). If I faced this issue today, I would probably do one of the following: use plaintext/markdown (readme, easiest and preferable) use json if I want a little bit of structure (easy, minimal change to flow) reach for "production grade" tooling (e.g. sqlite/hdf5/parquet) if this was going to be more serious json is particularly good as both human and machine readable/editable format. One option would be to store a json metadata file: metadata.json: [ { "path": "df.pkl", "metadata": "some editable metadata string" }, { "path": "some/path/to/df2.pkl", "metadata": "metadata for df2" }, ] You can even parse this into a df: df_meta = pd.read_json("metadata.json")
type: Answer
answers question: http://stackoverflow.com/q/48832397

http://stackoverflow.com/comment/84905663
comment on: http://stackoverflow.com/a/48929500
score: 0
type: AnswerComment
type: Comment
has text: Happy to help. If this answered your original question, please mark this as "Accepted" so other readers know your problem was solved. As for resources to help understand: That's the beauty of OpenSource, there's nothing stoping you from reading the source code, and once you have a basic understanding of the authors intended design, all ported language bindings become perfectly clear.

http://stackoverflow.com/a/48828476
has body: Given that you mentioned storing the selected data in a numpy array or a pandas dataframe, I assume that you plan to actually use bokeh serve. In this case, you don't need to write any JS code since all Bokeh DataSources have selected attribute, and you can attach a Python callback to it. Just replace your callbacks code with this: def attach_selection_callback(main_ds, selection_ds): def cb(attr, old, new): new_data = {c: [] for c in main_ds.data} for idx in new['1d']['indices']: for column, values in main_ds.data.items(): new_data[column].append(values[idx]) # Setting at the very end to make sure that we don't trigger multiple events selection_ds.data = new_data main_ds.on_change('selected', cb) attach_selection_callback(s1, s2) attach_selection_callback(s1b, s2b)
answers question: http://stackoverflow.com/q/48823884
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48823884
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84677256
has comment: http://stackoverflow.com/comment/84663767

http://stackoverflow.com/comment/84728437
type: AnswerComment
has text: Yes, accuracy is a measure of how well you're fitting. Since there are only two outcomes, which I assume have similar frequencies 0.5 accuracy means you aren't doing better than random guessing, unfortunately.
type: Comment
comment on: http://stackoverflow.com/a/48853597
score: 0

http://stackoverflow.com/comment/84676584
score: 0
comment on: http://stackoverflow.com/q/48835731
has text: My problem is `space` and that `NUL` on the image logs "PartName" exactly on that log image attached
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48959078
type: AnsweredQuestion
score: 1
has title: Python code with Input() given syntax error in Sublime REPL, but works with Python Shell
duplicate of: http://stackoverflow.com/q/21122540
type: Question
accepted answer: http://stackoverflow.com/a/48959111
tagged with: sublimetext
downvote count: 0
has comment: http://stackoverflow.com/comment/84925031
has body: I typed a piece of code in python 3 and the python shell runs it extremely well and gives the right output. I transfered this code to Sublime Text 3, downloaded the package sublime REPL, and I used it to run my code. However, it tells me there is a syntax error when I run it and enter an input in Sublime using REPL. Here's the line where it finds the syntax error: dataGiven = sorted([float(x) for x in input("Enter data separated by a space (At least 3 values of data must be entered) ").split()]) But, there is no syntax error because the python shell runs the code properly. Please help. I find Sublime text to be really helpful but it just wont run properly because of this input. I am willing to post a bigger segment of the code if you need it. Thanks in advance. EDIT screenshot of error: Traceback (most recent call last): File "Untitled.py", line 708, in &lt;module&gt; dataGiven = sorted([float(x) for x in input("Enter data separated by a space (At least 3 values of data must be entered) ").split()]) File "&lt;string&gt;", line 1 78 67 45 ^ SyntaxError: invalid syntax ***Repl Closed***
answer count: 1
tagged with: python-2.x
tagged with: sublimetext3
favorite count: 0
linked to: http://stackoverflow.com/q/2589309
has answer: http://stackoverflow.com/a/48959111
has comment: http://stackoverflow.com/comment/84925114
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84924917

http://stackoverflow.com/q/48897233
downvote count: 1
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84800147
favorite count: 0
has body: I have potentially large amount of text output coming from an application. The output can be broken up into different sections. And I would like to determine which section I am processing based on existence of 1 or more keywords or key phrases. Dummy Example output: ****************** ** MyApp 1.1 ** ** ** ****************** **Copyright ** ****************** Note # 1234 Text of the note 1234 Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ****************** INPUT INFO: Number of data points: 123456 Number of cases: 983 Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. ****************** Analysis Type: Simple Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. ****************** Results: Data 1: 1234e-10 Data 2 ------ 1 2 2 3.4 Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. ******************* CPU TIME: 1:01:12 WALL TIME: 1:04:23 ******************* So I created a dictionary like and am trying to look up the values of the dict in each chunk. def process(this_chunk): keys = ['banner_k','runSummary','inputSummary_k'] vals = [['MyApp','Copyright'],['CPU TIME'],['Number of data']] for k,v in zip(keys,vals): chunkdict[k]=v for k,v in chunkdict.items(): if any(x in v for x in this_chunk.splitlines()): print(k + " is in this chunk") process_for_k(chunk) #Function for each specific section. break else: print(k + " is not in this chunk") return But this does not identify all the chunks. The values are indeed present but only in 1 chunk the values are matched. To be specific, my real application has the exact words for 'CPU TIME' and 'Copyright' in its output. The section with 'CPU TIME' is captured correctly but the section with 'Copyright' is not found. Is this the right approach to identifying sections with known keywords? Any id…
tagged with: python
has title: Unable to identify text segments based on keywords
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84829822
upvote count: 1

http://stackoverflow.com/a/51013840
has comment: http://stackoverflow.com/comment/105121946
type: Answer
has comment: http://stackoverflow.com/comment/101186218
score: 5
downvote count: 2
has comment: http://stackoverflow.com/comment/101615308
type: AcceptedAnswer
has body: In this code: modules = db.relationship('Module', secondary=course_modules, primaryjoin=(course_modules.c.course_id == id), secondaryjoin=(course_modules.c.module_id == id), id in both primaryjoin and secondaryjoin refers due to scoping to Course.id. You should reference the correct id columns explicitly, e.g.: modules = db.relationship('Module', secondary=course_modules, primaryjoin=(course_modules.c.course_id == Course.id), secondaryjoin=(course_modules.c.module_id == Module.id),
has comment: http://stackoverflow.com/comment/129673843
upvote count: 7
accepted answer of: http://stackoverflow.com/q/48852513
has comment: http://stackoverflow.com/comment/129674490
answers question: http://stackoverflow.com/q/48852513

http://stackoverflow.com/a/48934648
type: Answer
downvote count: 0
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48934473
has body: Hope this does what you are looking for. I did it without using any external modules. b = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.') i=0 a=[] num=0 for element in b: print(element) if element[i][0].islower(): a[-1]=a[-1]+element else: a.append(element) num=num+1 print(a)

http://stackoverflow.com/comment/84798238
has text: It might be sometime to do with setting the parameter `zoom` to a value (in [this example](https://stackoverflow.com/questions/22566284/matplotlib-how-to-plot-images-instead-of-points) it was `zoom=0.1`). You'll be able to experiment with different values to change the size. The zoom value is also set on the OffsetImage object -> `im = OffsetImage(im, zoom=0.1)`
score: 1
comment on: http://stackoverflow.com/q/48896088
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48810726
downvote count: 0
tagged with: dataframe
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48811033
has comment: http://stackoverflow.com/comment/84625065
favorite count: 0
has answer: http://stackoverflow.com/a/48810951
has title: Concatenate pandas DataFrames generated with a loop
has comment: http://stackoverflow.com/comment/84626122
tagged with: python
upvote count: 16
tagged with: append
has answer: http://stackoverflow.com/a/48819247
type: AnsweredQuestion
score: 16
tagged with: loops
accepted answer: http://stackoverflow.com/a/48810951
possible better answer: http://stackoverflow.com/a/48819247
type: Question
has body: I am creating a new DataFrame named data_day, containing new features, for each day extrapolated from the day-timestamp of a previous DataFrame df. My new dataframes data_day are 30 independent DataFrames that I need to concatenate/append at the end in a unic dataframe (final_data_day). The for loop for each day is defined as follow: num_days=len(list_day) #list_day= random.sample(list_day,num_days_to_simulate) data_frame = pd.DataFrame() for i, day in enumerate(list_day): print('*** ',day,' ***') data_day=df[df.day==day] ..................... final_data_day = pd.concat() Hope I was clear. Mine is basically a problem of append/concatenation of data-frames generated in a non-trivial for loop

http://stackoverflow.com/a/49004371
has body: One problem is that your ALAudioDevice object doesn't have a "logger" member - you could just pass that one to your constructor (and also use it instead of the "mylogger" you use later on). But the problem is probably coming from your "It works ! " + nbOfChannels ... because you're trying to add a string and an integer, which Python doesn't like; do something like "It works ! %i" % nbOfChannels
has comment: http://stackoverflow.com/comment/85017105
answers question: http://stackoverflow.com/q/48950804
score: 0
type: Answer

http://stackoverflow.com/a/48883111
has comment: http://stackoverflow.com/comment/85721589
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48882768
type: Answer
has body: PyPDF2 is good for reading check it out the this Pdf Reader example
accepted answer of: http://stackoverflow.com/q/48882768
score: 2
upvote count: 3
downvote count: 1

http://stackoverflow.com/a/65604939
downvote count: 0
has comment: http://stackoverflow.com/comment/125314701
upvote count: 2
has body: You must use base64.urlsafe_b64encode which, as Debangshu Paul mentions, uses '-' instead of '+' and '_' instead of '/'. See https://docs.python.org/3/library/base64.html#base64.urlsafe_b64encode for more info.
answers question: http://stackoverflow.com/q/48910253
type: Answer
score: 2

http://stackoverflow.com/q/48832188
has comment: http://stackoverflow.com/comment/84675209
type: Question
has comment: http://stackoverflow.com/comment/84668588
has body: I have a little problem with display subcategories belongs only in specific categories. For example: I have a categories: Business, Factory, Health ... and after I can add subcategories for example Own Company in category Business. In this case if I choose category Business I need to have only visible subcategories belongs to this category. How to make it? This is my code. models.py from django.db import models from slugify import slugify class Kategoria(models.Model): name = models.CharField(max_length=50, unique=True, verbose_name='Nazwa kategorii') slug = models.SlugField(verbose_name='Adres SEO') class Meta: verbose_name_plural = 'Kategorie' def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Kategoria, self).save(*args, **kwargs) def __str__(self): return self.name class Subkategoria(models.Model): category = models.ForeignKey('Kategoria', related_name='subkategoria', on_delete=models.CASCADE, blank=True, null=True, verbose_name='Kategoria główna') name = models.CharField(max_length=50) class Meta: verbose_name_plural = 'Subkategorie' def __str__(self): return self.name class Strona(models.Model): name = models.CharField(max_length=250, verbose_name='Nazwa strony') slug = models.SlugField(verbose_name='Adres SEO') www = models.CharField(max_length=200, verbose_name='Adres strony', unique=True) content = models.TextField(verbose_name='Opis') category = models.ForeignKey('Kategoria', verbose_name='Kategoria', on_delete=models.CASCADE) subcategory = models.ForeignKey('Subkategoria', verbose_name='Subkategoria', on_delete=models.CASCADE) publish = models.DateField(auto_now=False, auto_now_add=False) class Meta: verbose_name_plural = 'Strony' def __str__(self): return self.name
has title: How to make a subcategory belong to a specific category in Django
score: 0
has comment: http://stackoverflow.com/comment/84675161
has comment: http://stackoverflow.com/comment/84668649
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
tagged with: django-models

http://stackoverflow.com/q/48862625
has comment: http://stackoverflow.com/comment/91235850
downvote count: 0
favorite count: 0
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/88235905
score: 2
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/84810240
has body: I am creating a VM from a disk in azure using python. I have all the OS data in a data disk and I am creating a VM from it. I am using this commmand for creating VM from disk: az vm create --resource-group RESOURCE-GRP-NAME \ --location eastus --name VM-NAME --os-type linux \ --attach-os-disk DISK-NAME The VM gets created successfully and runs normally on the azure portal, but it fails when I try to ssh it via terminal. So I think that the data disk must be converted to an OS disk first before creating a VM from it. So how do I do that in python.
has comment: http://stackoverflow.com/comment/84830231
has title: How to convert data disk to OS disk in Azure using python
has comment: http://stackoverflow.com/comment/84829128
tagged with: azure

http://stackoverflow.com/comment/84789000
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48891613
has text: consider using `readlines()` and `split()`. You can split on commas.
type: Comment

http://stackoverflow.com/comment/90698393
comment on: http://stackoverflow.com/q/48886671
type: Comment
type: QuestionComment
has text: Yes, problem was the conversion into a dataframe
score: 0

http://stackoverflow.com/q/48902791
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84812454
accepted answer: http://stackoverflow.com/a/48903585
tagged with: exception
tagged with: python
linked to: http://stackoverflow.com/q/27138440
has body: I have the following code: # exc is a local variable of type Exception # This is not inside an except block if isinstance(exc, ClientError): logging.debug("ClientError raised while loading %s:\n%s", package.id, traceback.format_exc()) continue When this code is run and exc is of type ClientError, format_exc() just prints out NoneType: None because no exception is currently being handled (the code is not inside an except block). Luckily there appears to be the format_exception method on traceback that isn't coupled to whatever the current exception being handled is, but in order to call it I need to extract the type, values, and tb from my exception variable. How do I do this?
has title: How to print an exception when I'm not handling it?
upvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84811207
has answer: http://stackoverflow.com/a/48903585
score: 1
tagged with: traceback
answer count: 1

http://stackoverflow.com/comment/84892744
type: Comment
comment on: http://stackoverflow.com/a/48931322
score: 0
type: AnswerComment
has text: It is defined inside the `else` statement `block = [line]`. This bit of code is reached first as `start` is `False` to begin with.

http://stackoverflow.com/a/48863536
has comment: http://stackoverflow.com/comment/84730518
upvote count: 5
score: 5
has comment: http://stackoverflow.com/comment/84736343
has body: The clean() method is called after the field's validator. If the alias is invalid, then it won't be in cleaned_data. Your clean method should handle this case, for example: def clean(): cleaned_data = super().clean() print(self.errors) # You should see the alias error here if 'alias' in cleaned_data: print(cleaned_data['alias']) # do any code that relies on cleaned_data['alias'] here return cleaned_data See the docs on cleaning fields that depend on each other for more info.
downvote count: 0
has comment: http://stackoverflow.com/comment/84738541
has comment: http://stackoverflow.com/comment/84730284
has comment: http://stackoverflow.com/comment/84730993
has comment: http://stackoverflow.com/comment/85035237
has comment: http://stackoverflow.com/comment/85071344
type: Answer
answers question: http://stackoverflow.com/q/48863201
has comment: http://stackoverflow.com/comment/84738064
has comment: http://stackoverflow.com/comment/84736242
has comment: http://stackoverflow.com/comment/85072962
has comment: http://stackoverflow.com/comment/84731260

http://stackoverflow.com/comment/84658658
comment on: http://stackoverflow.com/a/48822721
has text: Yes, I was looking at sorting by the location name and the year. In your example "date": ["1/1/2016", "1/2/2016", "1/3/2016"] * 2 + ["1/1/2017", "1/2/2017", "1/3/2017"] * 2, would I need to input every date that is in the record book or am I able to say any dates between 1/1/2016 to 12/31/2016?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48913890
type: Question
tagged with: web-search
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48914521
tagged with: python
accepted answer: http://stackoverflow.com/a/48914521
has body: I'm trying to create a search bot which uses Bing Web Search API but I'm facing an issue. subscription_key = API_KEY assert subscription_key search_url = "https://api.cognitive.microsoft.com/bing/v7.0/search" search_term = "Sayam Kanwar" import requests headers = {"Ocp-Apim-Subscription-Key" : subscription_key} params = {"q": search_term, "textDecorations":True, "textFormat":"HTML"} response = requests.get(search_url, headers=headers, params=params) response.raise_for_status() search_results = response.json() print search_results["webPages"]["value"] Output: Screenshot Now, I want to extract just the u'name' from all of them and create a separate array which would contain all the u'name's. Please help me out. Thanks!
has title: Bing API Web Search Python
type: AnsweredQuestion
tagged with: bing-api

http://stackoverflow.com/q/48838562
has answer: http://stackoverflow.com/a/48838706
tagged with: exception
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48838774
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48838706
tagged with: apply
type: Question
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/114378837
possible better answer: http://stackoverflow.com/a/48838774
upvote count: 5
downvote count: 0
linked to: http://stackoverflow.com/q/22847304
has title: Exception handling when using pandas apply
has body: I can extract a substring from a pandas series using series.str.extract. ds = pd.Series(['1A apple', '1B pear', '3C orange', 'grape']) ds.str.extract('(\\d.{1}).*', expand=False) What I tried initially was using apply function. ds.apply(lambda x: re.search('(\\d.{1}).*', x).group(1)) I got error message: AttributeError: 'NoneType' object has no attribute 'group' It seems that the search pattern does not apply to the fourth element 'grape'. So it retuns a nonetype. My question is how I can fix the apply function above to make it work? I'm curious about how to use the apply function to achieve the same task using str.extract. Thanks a lot.
tagged with: pandas
favorite count: 0

http://stackoverflow.com/a/49413296
type: Answer
has comment: http://stackoverflow.com/comment/108567556
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48893689
downvote count: 0
has body: If there are 'm' raters and 'n' items, shouldn't it be a multiplication by 'n' instead of 'm' in 'S'? S = n*np.var(rating_sums) I believe it went by unnoticed because you are using 4 raters and 4 items in your example, so 'm = n'. I noticed because I was using this code and getting values over one.

http://stackoverflow.com/comment/84921367
comment on: http://stackoverflow.com/q/48957150
has text: in the first case, you're iterating over the variable `chosen_subjects`. In the second case, you're iterating over the value returned by calling the method `chosen_subjects.values`. You call methods with parens.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48848628
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48849762
downvote count: 0
tagged with: date
has body: ex: I have a date string 2018-02-17 16:15:36.519 PST How do i convert into isoformat in UTC like below 2018-02-18T00:15:36.519Z I tried this from dateutil.parser import parse d1='2018-02-17 16:15:36.519 PST' print parse(d1) it prints like this. How do i convert it to UTC with Z at the end. 2018-02-17 16:15:36.519000-08:00 EDIT using python 2.7. import dateutil import pytz from dateutil.parser import parse d1='2018-02-17 16:15:36.519 PST' d2=dateutil.parser.parse(d1) d2.replace(tzinfo=pytz.utc) - d2.utcoffset() d3=(d2.replace(tzinfo=pytz.utc) - d2.utcoffset()).isoformat() print d3 then formatting with Z as suggested
type: Question
has answer: http://stackoverflow.com/a/48849762
answer count: 2
score: 5
has comment: http://stackoverflow.com/comment/84701067
possible better answer: http://stackoverflow.com/a/62868454
linked to: http://stackoverflow.com/q/19654578
has answer: http://stackoverflow.com/a/62868454
has comment: http://stackoverflow.com/comment/84713019
favorite count: 0
tagged with: parsing
linked to: http://stackoverflow.com/q/1703546
upvote count: 5
has title: python convert PST time to UTC isoformat
tagged with: python
linked to: http://stackoverflow.com/q/13707545

http://stackoverflow.com/comment/84696582
type: Comment
has text: What is `object` then? I thought `object` was the baseclass that we inherit from. But it seems `type` is the baseclass
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48846044

http://stackoverflow.com/comment/84927644
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48959987
has text: mprof: https://pypi.python.org/pypi/memory_profiler

http://stackoverflow.com/a/48959430
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48959394
upvote count: 1
type: Answer
has body: Depending on the situation, to take arguments you would be looking at argv imported from sys. example: test2.py from sys import argv script, arg1, arg2 = argv print(script) print(arg1) print(arg2) Running the file python3 test2.py my_arg1 my_arg2 test2.py my_arg1 my_arg2 If you want to do the same thing but after asking for input from the user, then look at the split() method in the str class. You can use split to split on spaces, or any other character you'd like.

pygobject
type: Tag
tags question: http://stackoverflow.com/q/48831728
tag name: pygobject

http://stackoverflow.com/comment/84698430
has text: You may want to install another one of the other back-ends @user3133476.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48847047

http://stackoverflow.com/comment/84749027
type: QuestionComment
comment on: http://stackoverflow.com/q/48872516
has text: print(df1.head(0)) Empty DataFrame Columns: [ACCT_DIM_ID, SEC_DIM_ID, POS_TYPE_DIM_ID, DAY_DIM_ID, COMPOSITE_KEY, PSI_FACTSET, ACCT_NUM, TRANSACTION_NUM, TIS_SEQ, ORIGINAL_FACE, QUANTITY, TRADE_DATE, SETTLEMENT_DATE, TRADE_PRICE_LOCAL, ACCRUED_INTEREST_LOCAL, NET_AMOUNT_LOCAL, TRANSACTION_CD, LOCAL_CURRENCY, BASE_CURRENCY, TIS_TRADE_NUM, FX_CONTRACT_AMT, FX_CONTRACT_CURRENCY, PRINCIPAL_AMT, PRINCIPAL_AMT_BASE, TAX_DATE, ENTRY_DATE, ENTRY_TIME, REVERSAL_DATE, REVERSAL_TIME, THROUGH_DATE, CASH_DECREASE_LOCAL, CASH_INCREASE_LOCAL, TRANSACTION_TYPE, QUANTITY_ADDED, QUANTITY_REMOVED,
score: 0
type: Comment

http://stackoverflow.com/a/55008605
answers question: http://stackoverflow.com/q/48951591
has body: def solution(number): bits = [int(digit) for digit in bin(number)[2:]] occurences = [i for i, bit in enumerate(bits) if(bit==1)] res = [occurences[counter+1]-a-1 for counter, a in enumerate(occurences) if(counter+1 &lt; len(occurences))] if(not res): print("Gap: 0") else: print("Gap: ", max(res)) number = 1042 solution(number)
score: 0
type: Answer

http://stackoverflow.com/a/48952738
answers question: http://stackoverflow.com/q/48952593
type: Answer
has body: If you know what strings you're looking for you could use startswith in place of regular expressions if line.startswith(("input", "output", "inout")): print(line.split(" ", 1)[1])
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/q/48929281
accepted answer: http://stackoverflow.com/a/48929378
has comment: http://stackoverflow.com/comment/84865643
has comment: http://stackoverflow.com/comment/84865265
has comment: http://stackoverflow.com/comment/84865362
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84865395
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84865181
has comment: http://stackoverflow.com/comment/84865719
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48929999
has answer: http://stackoverflow.com/a/48929378
has title: Improving sum() calculations on evenly spaced list
has body: I have a code where I need 10Million evenly spaced number between 0 and 1 and I have a logic function which is responsible to pick a random index and return the sum of numbers from that index till the end of the list. Thus the code looks like below, import random import numpy as np ten_million = np.linspace(0.0, 1.0, 10000000) def deep_dive_logic(): # this pick is derived from good logic, however, let's just use random here for demonstration pick = random.randint(0, 10000000) return sum(ten_million[pick:]) for _ in range(2500): r = deep_dive_logic() print(r) # more logic ahead... The problem here is as I loop sum() on a list of such size it takes approx. 1.3 s for each result. Is there any efficient way to reduce the 1.3s wait per call? I also tried creating a kind of cache dictionary, but the deep_dive_logic() function runs in a multi-process environment hence there is need to cache this dictionary, either redis or a json.dump not a choice because of the size of dictionary mounts to around 236MB and adds up as overhead in inter-process communication if not cached. sums_dict = {0: sum(ten_million)} even_difference = (ten_million[1] - ten_million[0]) for i in range(len(ten_million) - 1): sums_dict[i+1] = sums_dict[i] - (even_difference * (i+1)) I need help with either caching of 10Million dictionary or an alternate formula to return the result without using sum() or any out-of-box solution. https://repl.it/repls/HoneydewGoldenShockwave
favorite count: 0
has comment: http://stackoverflow.com/comment/84865295
has comment: http://stackoverflow.com/comment/84865453
possible better answer: http://stackoverflow.com/a/48929722
tagged with: python
has answer: http://stackoverflow.com/a/48929722
has comment: http://stackoverflow.com/comment/84865225
has comment: http://stackoverflow.com/comment/84865519
type: AnsweredQuestion

http://stackoverflow.com/comment/84687821
comment on: http://stackoverflow.com/q/48841180
score: 0
type: Comment
type: QuestionComment
has text: I am not getting paid for it. I am learning it. What am I supposed to do so that I come with error to you? You can add "Not for learning" on the site title so that beginners don't come here. I have no interest in typing a question that won't get answered. I did searching on SO and Google. But didn't find anything of this sort in case of Django. I Google before I come here because that is where whole world of information is. If you don't like helping just bug off. Thank you for whatever edit you did.

http://stackoverflow.com/comment/84661485
has text: Possible duplicate of [Why are Python's 'private' methods not actually private?](https://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private)
score: 3
comment on: http://stackoverflow.com/q/48828658
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84790075
comment on: http://stackoverflow.com/a/48892164
score: 0
type: AnswerComment
type: Comment
has text: Sorry, my bad - should've been more specific. I want it to output value **A** and value **B** to a .txt document. I'm not concerned about formatting just yet, but I am just trying to get the two seperate values, a and b, into a text document.

http://stackoverflow.com/comment/84873051
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48932847
score: 0
has text: No, it will try these solutions.

http://stackoverflow.com/a/48931750
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84872614
has comment: http://stackoverflow.com/comment/84870821
has comment: http://stackoverflow.com/comment/84870566
type: Answer
downvote count: 0
score: 1
has body: Of course you may mask both contours mutually exclusively. import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab x = np.arange(-3.0, 3.0, 0.1) y = np.arange(-2.0, 2.0, 0.1) X, Y = np.meshgrid(x, y) Z = np.zeros((len(y), len(x), 2)) Z[:,:,0] = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z[:,:,1] = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) mask = Z[:,:,0] &gt; Z[:,:,1] plt.figure() plt.contourf(X, Y, np.ma.array(Z[:,:,0], mask=~mask), cmap='Reds', alpha=0.6) plt.contourf(X, Y, np.ma.array(Z[:,:,1], mask=mask), cmap='Blues', alpha=0.6) plt.show()
accepted answer of: http://stackoverflow.com/q/48931104
answers question: http://stackoverflow.com/q/48931104
has comment: http://stackoverflow.com/comment/84872355
has comment: http://stackoverflow.com/comment/84871171

state
tag name: state
tags question: http://stackoverflow.com/q/48924405
type: Tag

http://stackoverflow.com/q/48838346
has answer: http://stackoverflow.com/a/48839902
has comment: http://stackoverflow.com/comment/84681162
has comment: http://stackoverflow.com/comment/84681204
has body: I have a set of vectors (~30k), each of which consists of 300 elements generated by fasttext, each vector is representing the meaning of an entity, I want to calculate the similarity between all entities, so I iterate over the vectors in a nested matter, O(N^2) complexity, which is not practical in terms of time. Can you recommend me another approach for calculating this, or how can I parallelize it? def calculate_similarity(v1, v2): """ Calculate cosine distance between two vectors """ n1 = np.linalg.norm(v1) n2 = np.linalg.norm(v2) return np.dot(v1, v2) / n1 / n2 similarities = {} for ith_entity, ith_vector in vectors.items(): for jth_entity, jth_vector in vectors.items(): if ith_entity == jth_entity: continue if (ith_entity, jth_entity) in similarities.keys() or (jth_entity, ith_entity) in similarities.keys(): continue similarities[(ith_entity, jth_entity)] = calculate_similarity(ith_vector, jth_vector)
favorite count: 0
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/84681267
upvote count: 4
linked to: http://stackoverflow.com/q/18424228
has comment: http://stackoverflow.com/comment/84681251
downvote count: 0
has answer: http://stackoverflow.com/a/69719631
type: UnansweredQuestion
tagged with: multithreading
has title: How to speed up computation of cosine similarity between set of vectors
has comment: http://stackoverflow.com/comment/84681170
has comment: http://stackoverflow.com/comment/84681297
has comment: http://stackoverflow.com/comment/84681313
has comment: http://stackoverflow.com/comment/84681431
score: 4
has answer: http://stackoverflow.com/a/48839668
has comment: http://stackoverflow.com/comment/84694223
has comment: http://stackoverflow.com/comment/84681252
tagged with: python-multiprocessing
tagged with: multiprocessing
type: Question
tagged with: cosine-similarity
has comment: http://stackoverflow.com/comment/84681209

http://stackoverflow.com/comment/84761681
comment on: http://stackoverflow.com/q/48878848
type: Comment
score: 2
has text: The problem was your that `search` returned None, and you called `None.group()` which is invalid in python. The real problem is your regex...
type: QuestionComment

http://stackoverflow.com/comment/84775809
score: 0
type: AnswerComment
has text: @Saranaone use `readlines()` instead of `read`. Check the edit in my answer
type: Comment
comment on: http://stackoverflow.com/a/48885026

http://stackoverflow.com/comment/84870084
has text: It would cost you nothing to have hundreds of factories.
comment on: http://stackoverflow.com/q/48929299
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/138951403
type: Comment
has text: Did you solve this problem?
score: 0
comment on: http://stackoverflow.com/q/48904495
type: QuestionComment

http://stackoverflow.com/q/48812613
downvote count: 3
has body: I'm now trying to implement GAN in keras. I want to use both the GAN loss and the generator loss at the same time when I train the network. Because I've found from some papers that this might contribute to some performance gain. It is a little bit like the loss function in the paper 'Multi-Scale Video Frame-Synthesis Network with Transitive Consistency Loss': Loss function The original code with the GAN loss alone is like the following: self.generator = generator self.discriminator = discriminator self.gan = Sequential([generator, discriminator]) gen, dis, gendis = self.generator, self.discriminator, self.gan gendis.compile(optimizer=opt, loss='binary_crossentropy') I'd like to combine the generator loss together. Thus, I tried the following: gendis.compile(optimizer=opt, loss={'generator_output': 'mse', 'model_2':'binary_crossentropy'}, loss_weights=[1., 0.2]) But it doesn't work and show the error message: ' ValueError: Unknown entry in loss dictionary: "generator_output". Only expected the following keys: ['model_2']'. How can I add the generator loss into this training procedure? Thanks a lot!
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48896645
upvote count: 0
tagged with: loss
type: UnansweredQuestion
tagged with: keras
score: -3
favorite count: 0
type: Question
tagged with: deep-learning
has title: Combine generator loss with GAN loss in Generative Adversarial Network
tagged with: python
answer count: 1

http://stackoverflow.com/a/48808886
type: Answer
score: 2
downvote count: 0
has body: You don't need a decorator for this. This is how methods already work; the instance is passed as first argument – implicitly when method is called from instance and explicitly from the class – with the instance available, you can retrieve the class by calling type on the instance: class Foo(object): def __repr__(self): return 'Foo()' def method(self): print((type(self), self)) class Bar(Foo): def __repr__(self): return 'Bar()' On another note, in the __str__ (or __repr__) special methods, you should return a string, not print. I have used __repr__ since __str__ is not called for printing the instance when inside a container object (tuple here). Update: Considering the issues with class/instance printing in the above approach, you can use a descriptor instead to properly manage correct class and instance selection within the method: class classinstancemethod(): def __get__(self, obj, cls): def method(inst=None): print(cls, inst if inst else obj) return method class Foo(object): method = classinstancemethod() def __str__(self): return 'Foo()' class Bar(Foo): def __str__(self): return 'Bar()'
has comment: http://stackoverflow.com/comment/84621752
answers question: http://stackoverflow.com/q/48808788
has comment: http://stackoverflow.com/comment/84621261
upvote count: 2
has comment: http://stackoverflow.com/comment/84621866
has comment: http://stackoverflow.com/comment/84621628
has comment: http://stackoverflow.com/comment/84621089
has comment: http://stackoverflow.com/comment/84621335

http://stackoverflow.com/q/48953277
tagged with: http://stackoverflow.com/tag/xml
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has body: When using XML in something like Python, (e.g. xml Python package) and calling getchildren() on a tag, the output is often of the form: [&lt;Element 'date' at 0x2b15236f4e08&gt;] ...but what is the name of this bit 0x2b15236f4e08? Is it the position of the tag in the file? I can't find out anywhere what it means!
type: Question
has title: What is the position hash value and what does it do in XML?
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48953478
favorite count: 0
accepted answer: http://stackoverflow.com/a/48953478

http://stackoverflow.com/comment/84774269
type: Comment
comment on: http://stackoverflow.com/a/48884896
has text: Isn't that just for .docx files? The documentation says it won't work with files older than 2007.
type: AnswerComment
score: 5

http://stackoverflow.com/comment/84772114
type: Comment
type: QuestionComment
has text: You should explain what you are doing and why. "Finding a class by a string" is not something you would normally need to do.
score: 5
comment on: http://stackoverflow.com/q/48883863

http://stackoverflow.com/q/48820939
tagged with: python
has answer: http://stackoverflow.com/a/48821164
has title: How to append all the arrays inside a list into a single array combined by the depth in numpy
type: Question
tagged with: numpy
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/84645735
answer count: 1
has body: I have a list which contains a variable amount of [n,1,2] numpy arrays. I need a way of combining all those arrays into one [n+however many,1,2] arrays. I have tried to create a loop with an empty array and then using dstack to sort of combine them. But I have to 1) predefine the size of the array in advance which won't do as I do not know it 2) The array has values that I must overwrite and thus dstack dosen't work too well. Is there a more elegant and easier solution? I have to use an array of this particular setup as I must pass it on to a method that I have not wrote that requires it.
favorite count: 0
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/comment/84745495
type: QuestionComment
comment on: http://stackoverflow.com/q/48869861
has text: Sorry, I am still not clear on how Jeff's answer applies here. He never mentioned setting df.is_copy = None. He mentions False, which he states will effectively turn off the check (ie ignore). He does mention using df.copy(). I am trying to fix the problem where it occurs. If i have something I am doing wrong prior to this, I would rather fix it there.
score: 0
type: Comment

http://stackoverflow.com/comment/84678937
type: AnswerComment
comment on: http://stackoverflow.com/a/48837077
score: 0
type: Comment
has text: more about Django models: https://docs.djangoproject.com/en/2.0/topics/db/models/

http://stackoverflow.com/comment/84670974
type: QuestionComment
score: 0
has text: Its probably the way I worded my question but I meant in a way where they could automatically do the convert, every time they got a new audit, without my input. Maybe them uploading > python code > displaying new data as a webpage, would be better than needing a second excel file.
comment on: http://stackoverflow.com/q/48832529
type: Comment

http://stackoverflow.com/comment/84766953
type: Comment
comment on: http://stackoverflow.com/q/48881297
score: 1
type: QuestionComment
has text: @ReutSharabani yes they are

http://stackoverflow.com/a/48807938
accepted answer of: http://stackoverflow.com/q/48807821
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48807821
type: AcceptedAnswer
has body: Okay, I founded solution in Python Docs: Both list.sort() and sorted() accept a reverse parameter with a boolean value. This is used to flag descending sorts. For example, to get the student data in reverse age order: &gt;&gt;&gt; student_tuples = [('jane', 'B', 12), ('dave', 'B', 10), ('john', 'A', 15)] &gt;&gt;&gt; sorted(student_tuples, key=itemgetter(2), reverse=True) [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] See: https://docs.python.org/3/howto/sorting.html#ascending-and-descending
downvote count: 0

http://stackoverflow.com/q/48912756
answer count: 1
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/5121931
has comment: http://stackoverflow.com/comment/84833111
has answer: http://stackoverflow.com/a/48914150
has body: I have the python code below for generating (dumping) a YAML document to a file. import yaml import os device_name = "NN41_R11" ip = "10.110.11.11" port = "2022" def genyam(): data = { "testbed" : { "name" : "boot_ios"}, "devices" : { device_name : { "type" : "IOS", "connections" : { "defaults" : { "class" : "con.con", "a" : { "protocol" : "telnet", "ip" : ip, "port" : port, } } } } } } with open('/tmp/testbed.yaml', 'w') as outfile: yaml.dump(data, outfile, default_flow_style=False)` which generates the following YAML file devices: NN41_R11: connections: defaults: a: ip: 10.110.11.11 port: '2022' protocol: telnet class: con.con type: IOS testbed: name: boot_ios Though the key value indentation is correct it's not generating in right order. I would like to have testbed first &amp; then devices however it's opposite now. I am suspecting it's dumping in alphabetical order. NN41_R11 is again a dictionary which contains type &amp; connections (type &amp; connections are generated at same level but need first type:IOS and under that connections). Looking for ordered dump basically The generated YAML document should be like the following: testbed: name: "boot-ios" devices: NN41_R11: type: IOS connections: defaults: class: 'con.con' a: protocol: telnet ip: 10.110.11.11 port: 2022
accepted answer: http://stackoverflow.com/a/48914150
tagged with: pyyaml
type: Question
has comment: http://stackoverflow.com/comment/84833306
has comment: http://stackoverflow.com/comment/84832406
has title: How to preserve the order of Key Value in YAML file using python (not alphabetical order)
upvote count: 2
tagged with: python-2.7
tagged with: yaml

http://stackoverflow.com/comment/84651828
has text: @PatrickArtner Hi I tried your method.. No error is being thrown but the code kind of stuck / froze. Nothing is moving forward. I gave sleep time as 60.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48822773
type: Comment

http://stackoverflow.com/comment/84826163
comment on: http://stackoverflow.com/q/48909487
has text: Ok, if I understand correctly, you want to transpose your DataFrame, i.e. swap the rows and the columns. You can do this with `csvfile.T`. Depending on whether column A in your spreadsheet is the index in your DataFrame, you may need to update the column names to the first row in this transposed DataFrame, and then drop the first row.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/comment/84709760
has text: @match just tried running `pip install Distribute` and the install failed with the following message `Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-oet1oon2/Distribute/`
score: 0
comment on: http://stackoverflow.com/q/48852137
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84717568
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48856969
has text: Have you looked at selenium? (not that I know much about it, but it is the go-to package for webpage automatization)

http://stackoverflow.com/q/48811596
answer count: 1
favorite count: 0
upvote count: 2
has body: I have a dataframe with scores of three persons (John, Terry, Henry) from day 1 to day 7. 1 2 3 4 5 6 7 John 1.3 2.8 3.0 4.4 2.6 3.1 4.8 Terry 1.1 2.3 4.1 5.5 3.7 2.1 3.8 Henry 0.3 1.0 2.0 3.0 2.7 1.1 2.8 How do I set a score ceiling such that once a score hits > 2.5, all scores from that day onwards is FIXED no matter what the score is The output should be: 1 2 3 4 5 6 7 John 1.3 2.8 2.8 2.8 2.8 2.8 2.8 Terry 1.1 2.3 4.1 4.1 4.1 4.1 4.1 Henry 0.3 1.0 2.0 3.0 3.0 3.0 3.0 Tried the following didn't work. I first do a boolean on all numbers > 2.5 to "1", then apply a mask to the cumulative sum: df = df.mask((df &gt; 2.5).cumsum(axis=1) &gt; 0, df)
tagged with: python
accepted answer: http://stackoverflow.com/a/48811687
type: AnsweredQuestion
has title: Pandas dataframe threshold -- Keep number fixed if exceed
type: Question
tagged with: numpy
tagged with: dataframe
tagged with: boolean
has answer: http://stackoverflow.com/a/48811687
tagged with: pandas
score: 2
downvote count: 0

http://stackoverflow.com/a/48940542
type: Answer
upvote count: 1
has body: You have not define a placeholder for X.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48940189

http://stackoverflow.com/comment/85057226
type: Comment
comment on: http://stackoverflow.com/a/48986374
has text: Could you share some code on how you are currently using FileSystems in your ParDo?
type: AnswerComment
score: 0

http://stackoverflow.com/q/48895889
has answer: http://stackoverflow.com/a/49272205
has title: What is the different between datum and ellps in pyproj?
upvote count: 1
answer count: 1
accepted answer: http://stackoverflow.com/a/49272205
downvote count: 0
has body: I am converting from ECEF to lla using def ecef_to_lla(x, y, z): lla = pyproj.Proj(proj='latlong', ellps='WGS84', datum='WGS84') ecef = pyproj.Proj(proj='geocent', ellps='WGS84', datum='WGS84') lon, lat, alt = pyproj.transform(ecef, lla, x, y, z) return lon, lat, alt I'm not sure how the ellps and datum keywords differ. Documentation points me here: http://proj4.org/parameters.html#parameter-list but it's still unclear how they differ?
score: 1
tagged with: proj
type: Question
type: AnsweredQuestion
tagged with: python
tagged with: pyproj
favorite count: 0

http://stackoverflow.com/comment/84865362
comment on: http://stackoverflow.com/q/48929281
score: 1
type: Comment
type: QuestionComment
has text: I don't understand your question, if they are evenly spaced, they are an [arithmetic progression with](https://en.wikipedia.org/wiki/Arithmetic_progression) an explicit formula for their sum.

http://stackoverflow.com/a/71496339
upvote count: 1
has body: I know i'm late to this topic but I have been running into a similar issue. I found a workaround, it is quick but not elegant. Therefore I'm also looking for a better solution. Basically I define this function in terms of a vectorised lambda function. from scipy.integrate import quad from scipy.special import jn import numpy as np integrand = np.vectorize(lambda x, r: np.exp(-x**2) * jn(0, r*x) * x) intensity = np.vectorize(lambda r: quad(lambda x: integrand(x, r), 0, 5)) The rest of the code will now work as intended because it is vectorised. Therefore it can be applied to a an array. rho = np.linspace(0, 1.25, 50) p = np.linspace(0, 2*np.pi, 50) R, P = np.meshgrid(rho, p) Z = intensity(R)
downvote count: 0
answers question: http://stackoverflow.com/q/48926212
type: Answer
score: 1

http://stackoverflow.com/q/48840117
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84685516
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/47698720
tagged with: python
has body: When i try to format dates using Pandas to_datetime(), i get the error: AttributeError: 'tuple' object has no attribute 'lower' he following is the code that produced the error : data = pd.read_csv('EURUSD.csv') data.columns = 'Date', 'open', 'high', 'low', 'close', 'vol' data.Date = pd.to_datetime(data.Date, format='%d.%m.%Y %h:%m%:%S.%f') why isn't it working?
has title: Strange error when using Pandas to_datetime()
type: Question
has comment: http://stackoverflow.com/comment/84684546
duplicate of: http://stackoverflow.com/q/47698720
has comment: http://stackoverflow.com/comment/84684415

http://stackoverflow.com/comment/84891856
type: Comment
comment on: http://stackoverflow.com/q/48942570
type: QuestionComment
has text: Thanks a lot, Looks like using `rb` does the task. Please post an answer if you'd like and I'd be happy to accept it.
score: 0

http://stackoverflow.com/comment/138413927
type: AnswerComment
has text: `venv` and `virtualenv` are two distinct packages even tho they achieve similar things
type: Comment
score: 0
comment on: http://stackoverflow.com/a/78512098

http://stackoverflow.com/q/48835609
tagged with: orange
score: 13
type: Question
has body: I am developing an add-on widget for Orange3. Is there any way to handle the event of connection/disconnection of widget output? I would like to postpone heavy calculations for one of the outputs until this output is connected with the input of another widget.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/55426662
favorite count: 0
tagged with: python
answer count: 1
upvote count: 13
downvote count: 0
has title: How to handle the connection event of widget output in Orange3?
has answer: http://stackoverflow.com/a/55426662

http://stackoverflow.com/q/48883427
has answer: http://stackoverflow.com/a/48883760
downvote count: 3
tagged with: rows
has comment: http://stackoverflow.com/comment/84771136
has comment: http://stackoverflow.com/comment/84772570
type: Question
answer count: 2
upvote count: 0
has title: Extract data from .txt files and take those data in rows and column
possible better answer: http://stackoverflow.com/a/48883760
accepted answer: http://stackoverflow.com/a/48883740
tagged with: python
has body: I have a set of datas from a .txt file in this format: 30 1 2477.25 0.00 1 M 40 2 11 0.17100 0.08600 0.11500 0.10800 0.05600 0.07500 9.60000 -1009.00000 -1009.00000 -1009.00000 2.70000 36 1 1 a.a.Sbargang 30 1 2477.45 0.00 2 M 40 2 11 0.52100 0.27400 0.35900 -1009.00000 -1009.00000 -1009.00000 14.30000 -1009.00000 -1009.00000 -1009.00000 2.66000 36 1 1 a.a M-gr. The format is quite messy, and I want to make it in rows and columns so my output will be like this: 30 1 2477.25 0.00 1 M 40 2 11 0.17100 0.08600 0.11500 0.10800 0.05600 0.07500 9.60000 -1009.00000 -1009.00000 -1009.00000 2.70000 36 1 1 a.a.Sbargang 30 1 2477.45 0.00 2 M 40 2 11 0.52100 0.27400 0.35900 -1009.0 -1009.0 -1009.00 14.3000 -1009.00000 -1009.00000 -1009.00000 2.66000 36 1 1 a.a M-gr. I am quite new to python and not sure how to write python3 to do this task? Thanks in advance I have tried to like this: with open ('textdata3.txt') as f: inputString = f.read() inputString = re.sub(r" +"," ", inputString) itemInString = inputString.split(" ") row1 = [] for index, item in enumerate(itemInString): if index % 1 == 0: row1.append(str(item)) print(row1) I'm not sure if this is the right approach, but here I get everything in 1 row. Output: ['30', '1\n', '2477.25', '0.00', '1', 'M\n40', '2', '11\n', '0.17100', '0.08600', '0.11500', '0.10800', '0.05600', '0.07500', '9.60000', '-1009.00000', '-1009.00000', '-1009.00000\n', '2.70000\n36', '1', '1\n', 'Sst.Lt-gry.F-gr.Sbang.VW-cmt.VP-srt.w/Mic.Calc.Glauc.\n30', '1\n', '2477.45', '0.00', '2', 'M\n40', '2', '11\n', '0.52100', '0.27400', '0.35900', '-1009.00000', '-1009.00000', '-1009.00000', '14.30000', '-1009.00000', '-1009.00000', '-1009.00000\n', '2.66000\n36', '1', '1\n', 'a.a', 'M-gr.']
has comment: http://stackoverflow.com/comment/84771104
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48883740
score: -3
has comment: http://stackoverflow.com/comment/84771381
type: AnsweredQuestion

http://stackoverflow.com/comment/84673993
has text: Why is it an issue that the *internal representation* of a string is not the way you want it?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48829046
type: Comment

http://stackoverflow.com/q/48893474
has comment: http://stackoverflow.com/comment/84792657
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48893614
tagged with: dataframe
has body: My sample dataframe consists of: dictx = {'col':[20,'nan',22,'nan','nan','nan',30,'nan',28,'nan',25]} df = pd.DataFrame(dictx).astype(float) df = df.reset_index() PART 1 I need to fill those missing data with either the mean of the extremities, e.g. df1 = df.iloc[:3,[1]] col 0 20.0 1 NaN 2 22.0 The value for the index 1should be 21. This problem will reappear on other situations which also need the same treatment PART 2 Or when the NaN's are more than one, I need to plot the data from a line chart as follow: df2 = df.iloc[2:7,[1]] col 2 22.0 3 NaN 4 NaN 5 NaN 6 30.0 x = df.iat[6,1] x0 = df.iat[2,1] y = df.iat[6,0] y0 = df.iat[2,0] slope = (x - x0)/(y-y0) value = slope*(x - x0) + y0 So the value would vary for each index My objectives are: The real dataframe is constantly changing and has 1440 rows so this problem repeats over and over. I need more help in part 1, because I can apply a similar approach for part 2 using the logic from the first.
type: Question
has title: Working with missing data, using dataframe values to fill nan, interpolate
has comment: http://stackoverflow.com/comment/84792762
downvote count: 0
has comment: http://stackoverflow.com/comment/84792622
tagged with: python-2.7
linked to: http://stackoverflow.com/q/18689823
accepted answer: http://stackoverflow.com/a/48893614
tagged with: pandas
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84657293
has text: Seems like the Python interpreter itself has some problem, irrespective of whether the program exits with an error or normally. Do you get the same error when running a different script? Starting with your script, what's the most you can prune away while still getting the error?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48820732
score: 0

http://stackoverflow.com/comment/84733343
type: AnswerComment
has text: Thank you for the comment. I'm new to python. I'm trying the later one you suggested. Thanks
comment on: http://stackoverflow.com/a/48850663
type: Comment
score: 2

http://stackoverflow.com/comment/84880378
has text: @heemayl you may want to check **then** now.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48936348
type: Comment

http://stackoverflow.com/q/48923170
tagged with: find
downvote count: 0
tagged with: string
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48923363
tagged with: file
upvote count: 1
has title: How to extract a string from the file list in Python?
type: Question
has comment: http://stackoverflow.com/comment/84852675
score: 1
has body: I have a folder with a list of 425 similar files named “00001q1.txt, 00002w2.txt, 00003e3.txt... 00425q1.txt”. Each file contains a line of text between two rows. These rows are constant in all files. I need to extract these lines and save it to output file as column of lines. This is script which able to loop all the files in a folder, but it doesn't extract desired lines from the list of files to otput file. #!/usr/bin/python # Open a file import re import os import sys import glob outfile = open("list7.txt", "w") # This would print all the files and directories (in sorted order) full_path = r"F:\files\list" filelist = sorted(os.listdir( full_path )) print filelist # This would scan the filelist and extract desired line that located between two rovs: # 00001q1.txt: # Row above line # line # Row under line buffer = [] for line in filelist: if line.startswith("Row above line"): buffer = [''] elif line.startswith("Row under line"): outfile.write("".join(buffer)) buffer = [] elif buffer: buffer.append(line) # infile.close() outfile.close() If I define a single file (for example 00001q1.txt“) instead filelist in the script, then desired line is written to the outfile successfully. What should I do that script scan the list of files? Thanks in advance.
tagged with: python-2.7
has answer: http://stackoverflow.com/a/48923347
answer count: 2

http://stackoverflow.com/q/48841180
has comment: http://stackoverflow.com/comment/84688561
has answer: http://stackoverflow.com/a/48841568
has comment: http://stackoverflow.com/comment/84686635
has body: This is my first app/site. I am trying to implement a search option. I have these to implement the search view: def normalize_query(query_string, findterms=re.compile(r'"([^"]+)"|(\S+)').findall, normspace=re.compile(r'\s{2,}').sub): return [normspace('',(t[0] or t[1]).strip()) for t in findterms(query_string)] def get_query(query_string, search_fields): ''' Returns a query, that is a combination of Q objects. That combination aims to search keywords within a model by testing the given search fields. ''' query = None # Query to search for every search term terms = normalize_query(query_string) for term in terms: or_query = None # Query to search for a given term in each field for field_name in search_fields: q = Q(**{"%s__icontains" % field_name: term}) if or_query is None: or_query = q else: or_query = or_query | q if query is None: query = or_query else: query = query | or_query return query def search_doctor(request): query_string = '' found_entries = None query_string = request.POST.get('doctor', None).strip() if query_string: entry_query = get_query(query_string, ['full_name']) found_entries = User.objects.filter(entry_query, groups__name='Doctor') #.order_by('first_name') context = { 'query_string': entry_query, 'doctors': found_entries } #return redirect('health:doctors' ) return render(request,'doctors_search_list.html', context ) It does search records but I am looking for a way to show records that have most matching search terms in them come up higher in the order. Can anyone guide me. Thank you.
type: Question
tagged with: django
tagged with: python
answer count: 1
has title: Django: records that have most matching words should come up higher in the result set
has comment: http://stackoverflow.com/comment/84687821
score: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84922808
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48957721
has text: Maybe start by reading up on decorators, then: https://docs.python.org/3/glossary.html#term-decorator

http://stackoverflow.com/q/48809990
tagged with: python
favorite count: 0
has body: I have a excel file with 6 columns and i want use the 3 column for my index when I print without changing the index the output like this df = pd.read_excel('sp500.xlsx') print(df.head()) close ctm Date high low open 0 1831.9 1389135600000 Jan 8, 2014 12:00:00 AM 1834.7 1825.5 1830.5 1 1833.6 1389222000000 Jan 9, 2014 12:00:00 AM 1838.7 1824.3 1831.0 2 1836.5 1389308400000 Jan 10, 2014 12:00:00 AM 1842.1 1826.3 1832.8 3 1815.0 1389567600000 Jan 13, 2014 12:00:00 AM 1838.0 1809.5 1837.5 4 1832.8 1389654000000 Jan 14, 2014 12:00:00 AM 1834.0 1812.5 1815.0 but when i change the index like this df = pd.read_excel('sp500.xlsx', parse_dates=True, index_col=3) print(df.head()) i have this close ctm Date high low open 2014-01-08 0 1831.9 1389135600000 1834.7 1825.5 1830.5 2014-01-09 1 1833.6 1389222000000 1838.7 1824.3 1831.0 2014-01-10 2 1836.5 1389308400000 1842.1 1826.3 1832.8 2014-01-13 3 1815.0 1389567600000 1838.0 1809.5 1837.5 2014-01-14 4 1832.8 1389654000000 1834.0 1812.5 1815.0 each column are moved from one and my close column is my old index
downvote count: 0
has comment: http://stackoverflow.com/comment/84623886
type: Question
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48810301
accepted answer: http://stackoverflow.com/a/48810301
has comment: http://stackoverflow.com/comment/84623922
upvote count: 1
answer count: 1
tagged with: pandas
has title: Change index col with pandas and read_excel

http://stackoverflow.com/q/48887830
type: UnansweredQuestion
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/96162907
type: Question
has title: Ipython double prompt after error within spyder
downvote count: 0
tagged with: python
favorite count: 0
answer count: 0
has body: I am using Ipython 6.1.0 / python 3.6.2 in the anaconda distribution. Within the spyder 3.2.3 iPython console, after an error, I get two input prompts, which prevents pdb being used in post-mortem mode [pdb.pm()]. Standalone ipython works fine. Does anyone know a fix for this?

http://stackoverflow.com/comment/84842742
type: Comment
type: QuestionComment
has text: You close the `today.csv` file at the end, after `writer = csv.writer(file)`. Be sure to indent those next two lines (`writer.writerow()`). Otherwise, you're just opening the CSV, creating a writer, then closing it. *Then* do you try to access the, now closed, csv file.
comment on: http://stackoverflow.com/q/48918137
score: 0

http://stackoverflow.com/q/48837606
accepted answer: http://stackoverflow.com/a/48837631
upvote count: 3
duplicate of: http://stackoverflow.com/q/285061
type: Question
has body: If I have Bag(a=1,b=2,c=3) and I want to change the individual values. I can call self.a = 10 so my updated output would be: Bag(a=10,b=2,c=3). If k = a and I have the code: temp = ("self." + str(k)) print(temp) --&gt; self.a How can I do something like: temp = 10 So it updates the bag (not temp itself to 10)? Thanks
has answer: http://stackoverflow.com/a/48837631
linked to: http://stackoverflow.com/q/285061
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/84679962
has title: Mutate Variables with String Names (Python)

http://stackoverflow.com/comment/84918865
has text: Thank you for explaining that, it was very helpful.
type: AnswerComment
comment on: http://stackoverflow.com/a/48955976
score: 0
type: Comment

http://stackoverflow.com/q/48903079
tagged with: list
has comment: http://stackoverflow.com/comment/84811576
type: Question
has comment: http://stackoverflow.com/comment/84811629
accepted answer: http://stackoverflow.com/a/48903879
answer count: 1
score: 0
tagged with: compare
tagged with: string
has body: I tried the following here target_conditions is the list which is to be compared with a column in PLM csv file with open('PLM.csv', 'rt') as f: reader = csv.reader(f, delimiter=',') for row in reader: for str in target_conditions: str=str.split(',') if str in row[3]: print ("is in file") #but i need the patient name to be displayed
tagged with: python
has answer: http://stackoverflow.com/a/48903879
has title: How to check if a string in a list is present in a particular column in a CSV file using python?
type: AnsweredQuestion

http://stackoverflow.com/a/48878455
upvote count: 2
has body: def is_number(s): try: if str(s).lower() != "nan": float(s) return True except ValueError: pass return False data_2 = [['nan', -5891.3764, -5901.0081390000005, -5939.977304, -5921.11797], ['nan', 3339.025337, 3346.9211149999996, 3356.405148, 3412.836335]] visuals = [[],[]] visuals[0].extend([float(_) for _ in data_2[0] if is_number(_)]) visuals[1].extend([float(_) for _ in data_2[1] if is_number(_)]) print visuals output: [[-5891.3764, -5901.0081390000005, -5939.977304, -5921.11797], [3339.025337, 3346.9211149999996, 3356.405148, 3412.836335]]
has comment: http://stackoverflow.com/comment/84766352
has comment: http://stackoverflow.com/comment/84772646
accepted answer of: http://stackoverflow.com/q/48878219
has comment: http://stackoverflow.com/comment/84773222
has comment: http://stackoverflow.com/comment/84767520
has comment: http://stackoverflow.com/comment/84762479
answers question: http://stackoverflow.com/q/48878219
has comment: http://stackoverflow.com/comment/84762895
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84896442
score: 0
comment on: http://stackoverflow.com/a/48943615
type: Comment
has text: @AntonvBR - Thank you, I test it and it working for positive timedelta very nice. But for negative timedeltas seems better is `total_seconds`.
type: AnswerComment

http://stackoverflow.com/a/76251433
has body: Is form an app? If yes, then you need to register this app in the INSTALLED_APP setting. Next to all the other elements in the list, just add a new element 'form' Only then {% load static %} will work. Hope this helps!
type: Answer
answers question: http://stackoverflow.com/q/48819066
score: 0

http://stackoverflow.com/comment/84896294
type: Comment
has text: After some tests I saw that it works for BasicRNNCell and for GRUCell, but when I use it with BasicLSTMCell I get this message: `Tensor` objects are not iterable when eager execution is not enabled. To iterate over this tensor use `tf.map_fn`.
comment on: http://stackoverflow.com/a/48929229
type: AnswerComment
score: 0

http://stackoverflow.com/a/48924691
downvote count: 0
upvote count: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/48911572
score: 8
has body: Looking at the documentation, it seems that sns.set() was called on import in versions &lt; 0.8. The reason why calling sns.set without any arguments changes your plot, is that it has some default parameters. Looking at the documentation: seaborn.set(context='notebook', style='darkgrid', palette='deep', font='sans-serif', font_scale=1, color_codes=False, rc=None) So, using sns.set(font_scale=2) will change the fontscale, but will also change everything else to the default arguments of sns.set
answers question: http://stackoverflow.com/q/48911572
has comment: http://stackoverflow.com/comment/115417911
type: AcceptedAnswer

http://stackoverflow.com/comment/89947925
comment on: http://stackoverflow.com/q/48920059
type: Comment
type: QuestionComment
has text: Did you ever find an answer here? I noticed the same thing, even in python. If I use scipy.io.wavfile and then normalize between -1 and 1 I get the same values as I do in iOS.
score: 1

http://stackoverflow.com/a/48894947
score: 1
upvote count: 1
downvote count: 0
has body: Ok, a few hours on the problem and I came up with a solution which, if I'm correct to assume there's no easy way to do this through Scapy itself (probably due to the way CoAP Options are implemented in the CoAP contrib layer), seems to be a fair enough one. The following function can be used to "nullify" an entire CoAP Option field: def coap_option_to_null(pkt, opt_idx): ''' Changes the whole CoAP Option field at @opt_idx to null ''' opt = pkt.options[opt_idx] l = pkt.options # Sort the list of options by option number l.sort( lambda x, y: cmp(coap_options[1][x[0]], coap_options[1][y[0]]) ) # Replace options for the sorted one and grabs new opt_idx pkt.options = l opt_idx = pkt.options.index(opt) cur_delta = 0 opt_total_len = [] for opt in pkt.options: if (option_model[opt[0]][0] - cur_delta) &lt; 13: delta_extended = 0 elif (option_model[opt[0]][0] - cur_delta) &lt; 269: delta_extended = 1 else: delta_extended = 2 cur_delta += (option_model[opt[0]][0] - cur_delta) if len(opt[1]) &lt; 13: len_extended = 0 elif len(opt[1]) &lt; 269: len_extended = 1 else: len_extended = 2 opt_total_len.append(1+delta_extended+len_extended+len(opt[1])) opt_lidx = sum(opt_total_len[:opt_idx]) opt_hidx = sum(opt_total_len[opt_idx+1:]) new_pkt = str(pkt)[:4+pkt.tkl+opt_lidx] + '\x00'*opt_total_len[opt_idx] + str(pkt)[-(len(pkt.payload)+1+sum(opt_total_len[opt_idx+1:])):] return CoAP(new_pkt) Below is a demonstration: &gt;&gt;&gt; pkt &lt;CoAP ver=1L type=CON tkl=8L code=PUT msg_id=&lt;RandShort&gt; token=&lt;RandBin&gt; options=[('If-Match', '\x04\xfc\xbbL'), ('Content-Format', ''), ('Uri-Path', 'separate')] paymark='\xff' |&lt;Raw load='CC22 at 12:39:31.495' |&gt;&gt; &gt;&gt;&gt; str(pkt) 'H\x03*\x88%T\xbe\xac\xd9\xee\xcd\xbd\x14\x04\xfc\xbbL\xa8separate\x10\xffCC22 at 12:39:31.495' &gt;&gt;&gt; npkt = coap_option_to_null(pkt, 1) &gt;&gt;&gt; npkt &lt;CoAP ver=1L type=CON tkl=8L code=PUT msg_id=47784 token='\x90L\x0f\xd4u\xbe&amp;\xd7' options=[('If-Match', '\x04\xfc\xbbL'), ('Uri-Path…
type: Answer
answers question: http://stackoverflow.com/q/48892682

http://stackoverflow.com/q/48939676
tagged with: raspberry-pi
score: 0
tagged with: keyerror
has comment: http://stackoverflow.com/comment/84887759
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84887169
has comment: http://stackoverflow.com/comment/84886377
answer count: 0
has title: Key Error 'Out of Range' When Running Python Program on Pi
tagged with: index-error
has comment: http://stackoverflow.com/comment/84886498
has body: In the picture, below... I am receiving both a "KeyError" and "IndexError: Index Out of Range" two days into running a program on my Raspberry Pi. Unplugging the Pi and plugging it back in fixes the issue. What would be an underlying issue that would cause this and a good way to troubleshoot? Thank you! def UpdateWeather( self ): # Use Weather.com for source data. cc = 'current_conditions' f = 'forecasts' # This is where the majic happens. self.w = pywapi.get_weather_from_weather_com( '48085', units='imperial' ) w = self.w try: if ( w[cc]['last_updated'] != self.wLastUpdate ): self.wLastUpdate = w[cc]['last_updated'] print "New Weather Update: " + self.wLastUpdate self.temp = string.lower( w[cc]['temperature'] ) self.feels_like = string.lower( w[cc]['feels_like'] ) self.wind_speed = string.lower( w[cc]['wind']['speed'] ) self.baro = string.lower( w[cc]['barometer']['reading'] ) self.wind_dir = string.upper( w[cc]['wind']['text'] ) self.humid = string.upper( w[cc]['humidity'] ) self.vis = string.upper( w[cc]['visibility'] ) self.gust = string.upper( w[cc]['wind']['gust'] ) self.wind_direction = string.upper( w[cc]['wind']['direction'] ) self.day[0] = w[f][0]['day_of_week'] self.day[1] = w[f][1]['day_of_week'] self.day[2] = w[f][2]['day_of_week'] self.day[3] = w[f][3]['day_of_week'] self.sunrise = w[f][0]['sunrise'] self.sunset = w[f][0]['sunset'] self.icon[0] = getIcon( w, 0 ) self.icon[1] = getIcon( w, 1 ) self.icon[2] = getIcon( w, 2 ) self.icon[3] = getIcon( w, 3 ) print 'Icon Index: ', self.icon[0], self.icon[1], self.icon[2], self.icon[3] #print 'File: ', sd+icons[self.icon[0]] self.rain[0] = w[f][0]['day']['chance_precip'] self.rain[1] = w[f][1]['day']['chance_precip'] self.rain[2] = w[f][2]['day']['chance_precip'] self.rain[3] = w[f][3]['day']['chance_precip'] if ( w[f][0]['high'] == 'N/A' ): self.temps[0][0] = '--' else: self.temps[0][0] = w[f][0]['high'] + unichr(0x2109) self.temps[0][1] = w[f][0]['low'] + unichr(0x2109) self.temps[1][0] = w[f][1]['high'] + …
type: Question

http://stackoverflow.com/comment/84634722
comment on: http://stackoverflow.com/a/48814305
has text: Ok, the link in your comment solves the question using python built-in `exec` function. Specifically the `exec(open('add_initial-data.py').read())` command as I'm using python 3. Thank you.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48856602
accepted answer: http://stackoverflow.com/a/48857046
tagged with: python
type: AnsweredQuestion
tagged with: matplotlib
type: Question
answer count: 1
has body: How my polar chart looks like I'm trying to move the ytick labels so that they are aligned similarly to the axis labels. For example the 'PTS' label is aligned horizontally to its axis, but the ytick labels are shifted to the right. For the y-value labels i'm using set_rgrids() function to specify angle and label values and tick_params() function to specify label properties like rotation. However this function does not allow me to set label's textbox alignement. How can i move the y-values to the left so that they are directly under respective axis labels? for i in range(N): #rgrids() for y-labels, tick_params() for properties of y-labels axes[i].set_rgrids(rgrids, angle=angles[i], labels=rlabels[i]) axes[i].tick_params('y', labelrotation=(angles[i]-180 if 90&lt;angles[i]&lt;270 else angles[i])) axes[i].set_ylim(ymin, ymax) axes[i].set_theta_offset(np.deg2rad(90)) #text() for axis label axes[i].text(np.deg2rad(angles[i]), 1.08*ymax,cat[i], va="center", ha='center', size=13, rotation=(angles[i]-180 if 90&lt;angles[i]&lt;270 else angles[i])) Full code: import numpy as np import matplotlib.pyplot as pl def normalize(val, min=0, max=100): value = val-min range = max-min frac = float(value)/range return frac*100 cat = ['PTS', 'FG%', 'FGM', '3PM', '3FG%'] N = len(cat) angles = np.arange(0, 360, 360.0/N) rcount = 9 ranges = [[5, 33], [30, 55], [3, 10.2], [0.1, 4.5], [22, 46]] rlabels = [[0]*rcount] * N ymin = 0 ymax = 100 for i in range(N): size = ranges[i][1] - ranges[i][0] step = float(size)/rcount rlabels[i] = list(np.arange(ranges[i][0] + step, ranges[i][1] + step, step)) rlabels[i] = [round(x,1) for x in rlabels[i]] step = (ymax - ymin)/float(rcount) rgrids = list(np.arange(ymin + step, ymax + step, step)) rect = [0.05, 0.05, 0.8, 0.8] fig = pl.figure(figsize=(7, 7)) axes = [fig.add_axes(rect, projection="polar", label="axes%d" % i) for i in range(N)] axes[0].set_thetagrids(angles, labels=cat, fontsize=14, visible=False)#jesli visible=False to trzeba dodac recznie za …
has answer: http://stackoverflow.com/a/48857046
score: 0
has title: How to move ytick labels in a polar plot in Matplotlib
linked to: http://stackoverflow.com/q/46719340

http://stackoverflow.com/comment/84808105
has text: Could you explain what exactly the problem is? What is the output you're getting and what's the expected output
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48901319

http://stackoverflow.com/a/48920769
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48920638
has body: If in race_names are all possible extracted words use str.extract: import re race_names = ['japanese'] pat = '|'.join(r"{}".format(x) for x in race_names) df['name'] = df['race'].str.extract('('+ pat + ')', expand=False, flags=re.I) + " Grand Prix" print (df) driverRef driver_no milliseconds name \ 151 button 22 1339994.0 JAPANESE Grand Prix 152 button 22 692245.0 JAPANESE Grand Prix 153 button 22 96286.0 JAPANESE Grand Prix 154 button 22 94548.0 JAPANESE Grand Prix 155 button 22 114725.0 JAPANESE Grand Prix race time 151 2016_Lap_JAPANESE_Third_Times.csv 1339.994 152 2016_Lap_JAPANESE_Third_Times.csv 692.245 153 2016_Lap_JAPANESE_Third_Times.csv 96.286 154 2016_Lap_JAPANESE_Third_Times.csv 94.548 155 2016_Lap_JAPANESE_Third_Times.csv 114.725 Maybe is possible also use replace and str.strip: df = pd.DataFrame({'race':['2016_Lap_ABU_Third_Times.csv', '2016_Lap_BRASIL_Third_Times.csv', '2016_Lap_CHINESE_Third_Times.csv', '2016_Lap_JAPANESE_Third_Times.csv', '2016_Lap_MAGYAR_Third_Times.csv', '2016_Lap_SINGAPORE_Third_Times.csv', '2016_Lap_Third_Times.csv', '2016_Lap_UNITED_Third_Times.csv', 'AUSTRALIAN_2016_Lap_Third_Times.csv', 'BAHRAIN_2016_Lap_Third_Times.csv', 'BELGIAN_2016_Lap_Third_Times.csv', 'CANADA_2016_Lap_Third_Times.csv', 'ESPANA_2016_Lap_Third_Times.csv', 'EUROPE_2016_Lap_Third_Times.csv', 'MALAYSIA_2016_Lap_Third_Times.csv', 'Mexico_2016_Lap_Third_Times.csv', 'RUSSIAN_2016_Lap_Third_Times.csv']}) df['name'] = (df['race'].replace(['_Third_Times.csv','Lap', '\d+'], '', regex=True) .str.strip('_')) print (df) race name 0 2016_Lap_ABU_Third_Times.csv ABU 1 2016_Lap_BRASIL_Third_Times.csv BRASIL 2 2016_Lap_CHINESE_Third_Times.csv CHINESE 3 2016_Lap_JAPANESE_Third_Times.csv JAPANESE 4 2016_Lap_MAGYAR_Third_Times.csv MAGYAR 5 2016_Lap_SINGAPORE_Third_Times.csv SINGAPORE 6 2016_Lap_Third_Times.csv 7 2016_Lap_UNITED_Third_Times.csv UNITED 8 AUSTRALIAN_2016_Lap_Third_Times.csv AUSTRALIAN 9 BAHRAIN_2016_Lap_Third_Times.csv BAHRAIN 10 BELGIAN_2016_Lap_Third_Times.cs…
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48920638

http://stackoverflow.com/q/48922003
score: 2
tagged with: xlsxwriter
type: Question
has title: Python xlswriter setting format after writing a line
downvote count: 0
has body: In the following loop I'm writting cells and formating some of them. In some cases I'd like to set bg_color def WriteExcelData(workbook,worksheet,row,datas): col = 0 formatDate = workbook.add_format({'num_format': 'dd/mm/yy'}) formatHour = workbook.add_format({'num_format': 'hh:mm'}) for data in datas: if re.match('^\d{2}\/\d{2}\/\d{4}$', data): #print 'date:',data worksheet.write(row,col,datetime.strptime(data, '%d/%m/%Y'),formatDate) elif re.match('^\d{2}\:\d{2}\:\d{2}$', data): worksheet.write(row,col,datetime.strptime(data, '%H:%M:%S'),formatHour) else: worksheet.write(row,col,data) col += 1 return Is there a way to apply a format on a line after it has been written ? If not, is it possible to combine several format ? something like : format1 = workbook.add_format({'num_format': 'hh:mm'}) format2 = workbook.add_format({'bg_color': '#dcdcdc'}) format3 = format1 + format2 Thanks
has answer: http://stackoverflow.com/a/48924653
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/84928024
has text: Try using the full path name for the python script.
comment on: http://stackoverflow.com/q/48960598
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48815646
has title: Open a csv file from S3 in write mode and write content to the file
has answer: http://stackoverflow.com/a/48822534
has answer: http://stackoverflow.com/a/48815783
answer count: 3
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48815792
has body: I have function to get the billing amount by AWS account and by application using the Boto3 cost explorer. I get a json response as a result. Currently, I am converting the json to a csv file and storing it on my local machine. All works good. However, I would like to have the csv file directly in S3. Like create a csv file in S3, create headers and copy the contents from json to csv. Is it possible to do this using s3.Object? I am trying to use something like this: bucket = s3.Bucket('my-bucket') header = 'Account Number;Application;Amount\n' with open('test.csv', 'wt') as file_object: file_object.write(header) I dont get any errors, but no results either. Updated question - This is how I am converting my json to csv to get only the columns that I need: import boto3 import json import csv import yaml client = boto3.client('ce', region_name='us-east-1', aws_access_key_id='AWS Access Key', aws_secret_access_key='AWS Secret Access Key') response = client.get_cost_and_usage( TimePeriod={ 'Start': '2018-01-01', 'End': '2018-02-01' }, Granularity='MONTHLY', Metrics=[ 'BlendedCost', ], GroupBy=[ { 'Type': 'DIMENSION', 'Key': 'LINKED_ACCOUNT' }, { 'Type': 'TAG', 'Key': 'Application' }, ], ) response_ser = json.dumps(response) # decode the unicode strings without converting the datatype decode_response = yaml.safe_load(response_ser) # get the first object in the response json results_obj = decode_response['ResultsByTime'] results_dict = results_obj[0] #get the groups response_groups = results_dict['Groups'] raw_data = open(local_file, "w") csvwriter = csv.writer(raw_data) fieldnames = ['Account Number', 'Application', 'Amount'] writer = csv.DictWriter(raw_data, fieldnames=fieldnames) writer.writeheader() for i in response_groups: accountNumber = i['Keys'][0] application = i['Keys'][1] amount = i['Metrics']['BlendedCost']['Amount'] writer.writerow({'Account Number': accountNumber, 'Application': application, 'Amount': amount}) raw_data.close() Hence, instead of creating the …
favorite count: 0
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84635325
tagged with: python
tagged with: amazon-s3
score: 1
downvote count: 1
type: Question
tagged with: boto3

http://stackoverflow.com/comment/84674433
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48834813
score: 0
has text: Hi @wiktor Stribizew , thank you! I am going to edit my question above that incorporates your comment

http://stackoverflow.com/a/48845423
score: 0
has comment: http://stackoverflow.com/comment/84695587
has body: Open the file using given path P Read the file into a variable Search that variable for the target string S Close the file Print the output
answers question: http://stackoverflow.com/q/48845287
type: Answer

http://stackoverflow.com/q/48837146
tagged with: dataframe
type: Question
has title: python passing variable name to function
has comment: http://stackoverflow.com/comment/84679123
tagged with: function
has answer: http://stackoverflow.com/a/48837204
answer count: 1
score: 0
tagged with: eval
tagged with: pandas
has comment: http://stackoverflow.com/comment/84679242
has comment: http://stackoverflow.com/comment/84680804
tagged with: python
has comment: http://stackoverflow.com/comment/84679105
type: AnsweredQuestion
has body: I have various pd.DataFrames that I'd like to write to an hdf store by passing them to a function. Is there a way to programmatically generate key names based on the variable name of any given dataframe? from sklearn import datasets import pandas as pd df1 = pd.DataFrame(datasets.load_iris().data) df2 = pd.DataFrame(datasets.load_boston().data) def save_to_hdf(df1): with pd.HDFStore('test.h5') as store: store.put('df1', df1) save_to_hdf(df1)
accepted answer: http://stackoverflow.com/a/48837204

http://stackoverflow.com/a/48908255
score: 9
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/136946219
type: Answer
has comment: http://stackoverflow.com/comment/136937632
accepted answer of: http://stackoverflow.com/q/48908116
has body: It's a very personal answer, but I like to initalize some boolean before the if statement. I find it more readable (because you can give some meaningful name to your variable), and I'm pretty sure the compiler can easily optimize it. cond1 = a == 1 and b == 2 and c == 4 cond2 = d == 4 and e == 5 if cond1 or cond2: print("Yeah, working") else: print("ooops")
answers question: http://stackoverflow.com/q/48908116
upvote count: 9

http://stackoverflow.com/a/48832615
has body: The standard idiom is useful here: if __name__ == '__main__': main()
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48832559
accepted answer of: http://stackoverflow.com/q/48832559

http://stackoverflow.com/q/48959547
score: 1
tagged with: cgi
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/49000650
tagged with: javascript
has title: How do I call a python function from a cgi script with javascript?
tagged with: http://stackoverflow.com/tag/html
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49000650
tagged with: python
tagged with: xmlhttprequest
has body: I also want to use the XMLHttpRequest object in a javascript function to send info about the currently selected option from a dropdown list (the one called 'Users' in the code below) as an argument to a function in my Python script, and then get the return value from that function and use it to setup another list ('Tasks' in the code below) I want to do this so that I can update the information in "Tasks" using data that I have gotten as a return value from the Python function I am doing it this way because I need the page to not have to reload. If you know a better way to implement this I would be open to ideas. def main(): with open("Users.json", 'r') as data_file: usersDictionary = json.load(data_file) Users=usersDictionary["Users"] print "Content-Type: text/html" print "" print """ TestPage """ print """ """ for user in Users: if(not(len(user["Tasks"]["High"])==0 and len(user["Tasks"]["Med"])==0 and len(user["Tasks"]["Low"])==0)): print """ {1} """.format(user["UID"], user["name"]) print " " print """ """ print " " print""" Delete Task """ print""" """ main() For the code below, I want to be able to get the data from input boxes when submit is clicked, and send the info gotten from the input boxes and radio buttons to a python function to process it and add it as a JSON object to a JSON dictionary and then update a JSON file, and then return to the previous page (which is the one with the code above) (assume that is called index.py). print "Content-Type: text/html" print "" print""" Title Task Name: Task Description: User ID: Priority High Medium Low """ Can anyone help, I'm really new to this CGI stuff, and would really appreciate it. Also if you know a better for me to do this, please let me know. Thanks!
type: AnsweredQuestion

http://stackoverflow.com/comment/84635392
type: Comment
comment on: http://stackoverflow.com/q/48814941
type: QuestionComment
has text: That works perfectly. Thanks @pault
score: 0

http://stackoverflow.com/a/78608995
has body: Don't use inplace=True and try this instead: df.fillna(0)
answers question: http://stackoverflow.com/q/48956789
score: 0
type: Answer

http://stackoverflow.com/q/48825957
tagged with: flask-restplus
answer count: 1
tagged with: python
has title: How can I log marshaled messages sent by Flask-Restplus
score: 0
has body: Consider following bare minimum example: from flask_restplus import Api, Resource, fields from .models import User ns = api.namespace('users', description='User related operations') user = api.model('User', { 'id': fields.Integer(readOnly=True, description='The user identifier'), 'name': fields.String(required=True, description='The users name'), 'password': fields.String(required=True, description='The users password') }) @ns.route('/') class UserList(Resource): @ns.doc('list_users') @ns.marshal_list_with(user) def get(self): data = User.query.all() print "Print the response here!" return data I'm troubleshooting and I would like to be able to print/log the JSON response being returned by Flask-RestPlus, how could I do this?
has answer: http://stackoverflow.com/a/48826073
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48826073
tagged with: flask
tagged with: flask-sqlalchemy

mime-mail
type: Tag
tags question: http://stackoverflow.com/q/48927303
tag name: mime-mail

http://stackoverflow.com/comment/84639712
comment on: http://stackoverflow.com/q/48817659
score: 0
type: Comment
has text: I don't see why its an issue to search twice -- python doesn't make it that hard: https://www.tutorialspoint.com/python/string_index.htm
type: QuestionComment

http://stackoverflow.com/comment/84880215
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48936697
type: AnswerComment
has text: in this case assignment to the left becomes unnecessary. however, it's arguable that in python, if it's a good idea to modify the parameters of a function.

http://stackoverflow.com/a/48962608
has body: You are really close, need join all values in state_list by | for regex OR for check substrings by state_list: Thanks @Jon Clements for better solution with word boundary: pat = r'\b{}\b'.format('|'.join(state_list)) df.loc[df.location.str.contains(pat, na=False), 'location'] = 'USA' EDIT1: Thanks @Håken Lid For another suggestion - If the state always comes after a comma and a space, you can speed up the regex by making it even more specific. pat = r', ({})$'.format('|'.join(state_list)) Sample: print (df) location 0 Scottsdale, AZ 1 London, UK 2 USA 3 NaN 4 Mission Viejo, CA state_list = ['AZ','CA'] pat = r'\b{}\b'.format('|'.join(state_list)) df.loc[df.location.str.contains(pat, na=False), 'location'] = 'USA' print (df) location 0 USA 1 London, UK 2 USA 3 NaN 4 USA
has comment: http://stackoverflow.com/comment/84931315
has comment: http://stackoverflow.com/comment/84931452
has comment: http://stackoverflow.com/comment/84932448
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84931596
type: Answer
has comment: http://stackoverflow.com/comment/84931144
has comment: http://stackoverflow.com/comment/84931113
accepted answer of: http://stackoverflow.com/q/48962555
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48962555

http://stackoverflow.com/comment/136810345
has text: @mojoken I basically have to do this right now and I just wanted to say I know this is over five years old and I haven't even tried your solution yet but I really have to say what a great job you did on describing the process end to end with all the configuration. Thanks for the great answer!
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/52936631

http://stackoverflow.com/q/48907216
type: AnsweredQuestion
tagged with: performance
has answer: http://stackoverflow.com/a/48907717
accepted answer: http://stackoverflow.com/a/48907717
upvote count: 5
possible better answer: http://stackoverflow.com/a/48907901
tagged with: numpy
score: 5
answer count: 3
has body: Let X be a Bxn numpy matrix, i.e., import numpy as np B = 10 n = 2 X = np.random.random((B, n)) Now, I'm interested in computing the so-called kernel (or even similarity) matrix K, which is of shape BxB, and its {i,j}-th element is given as follows: K(i,j) = fun(x_i, x_j) where x_t denotes the t-th row of matrix X and fun is some function of x_i, x_j. For instance, this function could be the so-called RBF function, i.e., K(i,j) = exp(-|x_i - x_j|^2). For doing so, a naive way would be the following: K = np.zeros((B, B)) for i in range(X.shape[0]): x_i = X[i, :] for j in range(X.shape[0]): x_j = X[j, :] K[i, j] = np.exp(-np.linalg.norm(x_i - x_j, 2) ** 2) What I want is to do the above operation in a vectorized way, for the sake of efficiency. Could you help?
downvote count: 0
favorite count: 0
tagged with: similarity
tagged with: python
has answer: http://stackoverflow.com/a/48907901
has answer: http://stackoverflow.com/a/48949157
has title: Efficient computation of similarity matrix in Python (NumPy)
tagged with: vectorization
type: Question

http://stackoverflow.com/q/48952467
tagged with: list
score: 0
linked to: http://stackoverflow.com/q/47131096
has answer: http://stackoverflow.com/a/48952554
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48952498
type: Question
tagged with: python-2.7
possible better answer: http://stackoverflow.com/a/48952498
duplicate of: http://stackoverflow.com/q/47131096
has body: For instance, myList = ['string1', 'string2', 'string3']... now I want my result to be this: ['1gnirts', '2gnirts', '3gnirts'] I've found few examples on how to reverse strings in general but not specific to this problem ... I'm bit confused on how to do a reverse of strings that are in a list.
tagged with: string
has answer: http://stackoverflow.com/a/48952612
tagged with: reverse
accepted answer: http://stackoverflow.com/a/48952612
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/48994566
has title: Python: How do I reverse every character in a string list?

http://stackoverflow.com/q/48813627
tagged with: subprocess
tagged with: popen
has comment: http://stackoverflow.com/comment/84634520
score: 0
has comment: http://stackoverflow.com/comment/84632550
has answer: http://stackoverflow.com/a/48813871
type: Question
has title: How to return args of a subprocess.Popen
has comment: http://stackoverflow.com/comment/84630909
tagged with: bash
has comment: http://stackoverflow.com/comment/84634306
has comment: http://stackoverflow.com/comment/84631115
answer count: 1
has comment: http://stackoverflow.com/comment/84634352
has comment: http://stackoverflow.com/comment/84634856
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84632501
has body: I'm running a bash script which consist of many other commands within the python mybash.sh: #!/bin/bash var=10 echo variable is equal to $var and inside the python while running .sh if echo variable is equal to $var == echo variable is equal to 10: print ('variable is 10') and I try to do it by: process = Popen('sh mybash.sh', shell=True, stdout=PIPE, stdin=PIPE) I'm try to get the args value of each commands inside the bash script, but process.args just return sh mybash.sh. how can I return the args value of each commands inside the script line by line while it executed?

http://stackoverflow.com/a/48813273
upvote count: 2
type: Answer
score: 2
downvote count: 0
has body: If you want to ensure you skip all hidden files use something like filename.startswith('.')
answers question: http://stackoverflow.com/q/48812737

http://stackoverflow.com/a/48957173
has body: If all variable are only number and you want a matrix whit all your values you can simply do something like: [int(line.strip().split('|')) for line in your_data.splitlines()]
score: 0
answers question: http://stackoverflow.com/q/48957099
type: Answer

http://stackoverflow.com/q/48895975
accepted answer: http://stackoverflow.com/a/48919490
has title: Why does pytest sometimes report two dicts as unequal?
type: Question
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/84807960
tagged with: django-rest-framework
has comment: http://stackoverflow.com/comment/84824934
answer count: 1
has body: The Problem I have a comparison between two dictionaries, say d1 and d2, that look something like this: { 'id': 1, 'name': 'Foo', 'data': [ OrderedDict(('name', 'bar'), ('id', 3)), ], } When I assert that these two dictionaries are equal, the assertion sometimes fails. What gets me is that the following code passes: for key in d1.keys(): assert d1[key] == d2[key] Can anyone shed some light on why this happens, and why it occurs seemingly at random? Possible Causes What I'm really trying to do here is test the output of a serializer from Django Rest Framework. That data is not always returned as a plain dictionary, but other tests against non-nested output work as expected. I also considered that the assertion might be failing to test the nested list, but the following passes without error: d3 = {'data': d1['data']} d4 = {'data': d2['data']} assert d3 == d4 Example I have two models, Foo and Bar. Each Bar is owned by a Foo. I have the following serializers: class BarSerializer(serializers.ModelSerializer): class Meta: fields = ('id', 'name') model = Bar class FooSerializer(serializers.ModelSerializer): bars = BarSerializer(many=True, read_only=True) class Meta: fields = ('id', 'name', 'bars') model = Foo I am trying to unit test the output of FooSerializer with the following test: # Assume my_foo_instance is an instance of Foo with one associated Bar # instance. This should avoid any problems with the ordering of BarSerializer # affecting the outcome. serializer = FooSerializer(my_foo_instance) bar_serializer = BarSerializer(my_foo_instance.bars.all(), many=True) expected = { 'id': my_foo_instance.id, 'name': my_foo_instance.name, 'bars': bar_serializer.data, } assert serializer.data == expected As I said above, the assertion sometimes fails.
favorite count: 0
has comment: http://stackoverflow.com/comment/84808043
has answer: http://stackoverflow.com/a/48919490
tagged with: python
has comment: http://stackoverflow.com/comment/84808028
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84845189
tagged with: pytest
downvote count: 2

http://stackoverflow.com/q/48851220
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84712678
accepted answer: http://stackoverflow.com/a/48852568
tagged with: python-3.x
upvote count: 3
tagged with: django
has title: Images are not displayed on web-page (Django)
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/84706326
has comment: http://stackoverflow.com/comment/84708264
type: Question
has answer: http://stackoverflow.com/a/48852568
has body: the problem is this, using Bootstrap 3, created the "Carousel" from the images, then in Views wrote a loop that adds all the images with paths to the dictionary, then through the loop, output all the images in HTML-views. HTML {% for picture in picture_list %} {% endfor %} Previous Next Views def recipes_list(request): recipes = Recipe.objects.filter(created_date__lte=timezone.now()).order_by('created_date') pictures = os.listdir(os.path.join(settings.STATIC_PATH, 'images/carousel')) picture_list = [] for picture in pictures: path = str(os.path.join(settings.STATIC_PATH, 'images\carousel').replace('\\', '/')) picture_list.append('%s/%s' % (path, picture)) return render(request, 'Recipes/recipes_list.html', {'recipes': recipes, 'sub_form': sub_form, 'picture_list': picture_list}) In browser

http://stackoverflow.com/a/48842130
score: 6
accepted answer of: http://stackoverflow.com/q/48841889
upvote count: 6
has body: from urllib import request, parse data = parse.urlencode({"data":"Hello Word?"}).encode() req = request.Request("http://www.naver.com", data=data) # this will make the method "POST" resp = request.urlopen(req) If run this code, packet looks like this. POST / HTTP/1.1 Accept-Encoding: identity Host: www.naver.com Content-Type: application/x-www-form-urlencoded Connection: close Content-Length: 18 User-Agent: Python-urllib/3.4 data=Hello+Word%3F If I change data = parse.urlencode({"data":"Hello Word?"}).encode() to data = parse.urlencode({"oauth_verifier":"uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY"}).encode() Packet will look like this POST / HTTP/1.1 Accept-Encoding: identity Host: www.naver.com Content-Type: application/x-www-form-urlencoded Connection: close Content-Length: 57 User-Agent: Python-urllib/3.4 oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY Isn't this what you want?
answers question: http://stackoverflow.com/q/48841889
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84688892
type: Answer
downvote count: 0

http://stackoverflow.com/a/48880939
answers question: http://stackoverflow.com/q/48866205
type: Answer
has body: I think you don't even need to use hierarchy information, Just count the number of contours and use to classify your image. I am giving a simple python implementation to view the individual contours. Contour hierarchy representation in OpenCV has been explained here Contour Hierachy img = cv2.imread(r'D:/Image/cross.png') gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) ret,bw = cv2.threshold(gray,220,255,cv2.THRESH_BINARY_INV) _,contours,hierarchy = cv2.findContours(bw, cv2.RETR_CCOMP,1) cntLen = 10 ct = 0 #number of contours for cnt in contours: if len(cnt) &gt; cntLen: #eliminate the noises ct += 1 newimg = img.copy() cv2.drawContours(newimg,[cnt],0,(0,0,255),2) cv2.imshow('Win', newimg) cv2.waitKey(0) print('Total contours: ',ct)
upvote count: 9
score: 9
has comment: http://stackoverflow.com/comment/111246027
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48866205

http://stackoverflow.com/a/48917534
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48917186
has comment: http://stackoverflow.com/comment/84841887
type: AcceptedAnswer
downvote count: 0
has body: First, determine what consecutive values repeat, and then use pd.Series.mask to hide them. Thanks to piR for the improvement: df.Jan.mask(df.Jan.eq(df.Jan.shift()), '') 0 try 1 2 bbbbb Name: Jan, dtype: object You can assign this back to df.Jan.
type: Answer
answers question: http://stackoverflow.com/q/48917186
score: 2

http://stackoverflow.com/comment/85134557
has text: @dragon951 yes. Inside the [] is a Boolean array of equal to the series. This is called Boolean slicing and will leave you with an array of values coinciding with where those values are not equal to “.”
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48895589
type: AnswerComment

http://stackoverflow.com/q/48840884
upvote count: 1
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/113950193
tagged with: neural-network
has comment: http://stackoverflow.com/comment/84689662
downvote count: 0
has body: I have a data set that comprises rate vs. time data for flow performance. It is typically structured as: time = [1,2,4,5,6,7, 8, 9 10] rate = [100, 62, 40, 31, 25, 21, 18, 16, 14, 13] This data is described by a hyperbolic decline model of the form: Q = Qi*(1+Di*b*Ti)^-(1/b) with the constraints: 0 &lt;b &lt;= 2 Di &gt; 0 Qi &gt; 0 Ti = time(i) Although the data is quite noisy, in many cases it is very, very well described by the equation above, and using something like a least-squares curve fitting method you often get an answer that a human interpreter would validate. However, there are cases when the mathematically best solution is not the desirable solution (there is an emphasis by human interpreters on ignoring noise and matching late time data), so a human interpreter would need to override the results. Obviously the solution is non-unique, so there are many acceptable answers I have gone through a data set of nearly 4000 rate-time pairs and manually evaluated the least-squares generated solution, and corrected it if necessary. My question: I would like to train a model to "guess" the best solution for Qi, Di, and b in the equation above, with the my manually evaluated data set serving as the training data. Is this a valid use case for implementing a neural network?
has title: Using Neural Net to determine variables to use in curve fitting equation
favorite count: 0
type: UnansweredQuestion
tagged with: curve-fitting
tagged with: python
answer count: 0
score: 1

http://stackoverflow.com/comment/84698812
type: Comment
has text: How can I use the id instead of room_number in the url but retain the room_number as text?
comment on: http://stackoverflow.com/a/48843502
type: AnswerComment
score: 0

http://stackoverflow.com/a/48891252
has comment: http://stackoverflow.com/comment/106164180
upvote count: 61
accepted answer of: http://stackoverflow.com/q/48884796
type: Answer
answers question: http://stackoverflow.com/q/48884796
has comment: http://stackoverflow.com/comment/105599931
has body: The section must be [options.entry_points]. See an example at https://github.com/github/octodns/blob/4b44ab14b1f0a52f1051c67656d6e3dd6f0ba903/setup.cfg#L34 [options.entry_points] console_scripts = octodns-compare = octodns.cmds.compare:main octodns-dump = octodns.cmds.dump:main octodns-report = octodns.cmds.report:main octodns-sync = octodns.cmds.sync:main octodns-validate = octodns.cmds.validate:main
has comment: http://stackoverflow.com/comment/106165025
downvote count: 1
score: 60
type: AcceptedAnswer

http://stackoverflow.com/q/48938120
has answer: http://stackoverflow.com/a/49374066
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: conv-neural-network
score: 1
upvote count: 1
tagged with: machine-learning
tagged with: tensorflow
type: Question
has body: I am trying to train a convolutional network in Python and Tensorflow. The out put will be the bounding boxes of the detected objects. I have made the output a 20 x 20 grid and each grid will detect a bounding box together with the probability. So my output will be 20 x 20 x 5. 20 x 20 for the grid 5 for probability + center within the grid (x, y) + height + width of bounding box When there are no objects within a grid box the probability is zero and the bounding box values should be don't care values. My question is how do I define the output with don't care values. That is Tensorflow should exclude these in the cost calculation. If I use zero that would be so wrong as I would be telling Tensorfow that there is a 0 x 0 box. So how do I define don't care values?
tagged with: neural-network
has comment: http://stackoverflow.com/comment/84897485
has comment: http://stackoverflow.com/comment/84894196
has title: Make Tensorflow Ignore Values
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48831802
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/48832218
type: Question
tagged with: numpy
downvote count: 0
has answer: http://stackoverflow.com/a/68883311
has comment: http://stackoverflow.com/comment/84668150
has answer: http://stackoverflow.com/a/48832098
accepted answer: http://stackoverflow.com/a/48832098
tagged with: file-io
has comment: http://stackoverflow.com/comment/84667896
tagged with: pandas
has answer: http://stackoverflow.com/a/51799939
has body: I have a pandas series object &lt;class 'pandas.core.series.Series'&gt; that look like this: userId 1 3072 1196 838 2278 1259 2 648 475 1 151 1035 3 457 150 300 21 339 4 1035 7153 953 4993 2571 5 260 671 1210 2628 7153 6 4993 1210 2291 589 1196 7 150 457 111 246 25 8 1221 8132 30749 44191 1721 9 296 377 2858 3578 3256 10 2762 377 2858 1617 858 11 527 593 2396 318 1258 12 3578 2683 2762 2571 2580 13 7153 150 5952 35836 2028 14 1197 2580 2712 2762 1968 15 1245 1090 1080 2529 1261 16 296 2324 4993 7153 1203 17 1208 1234 6796 55820 1060 18 1377 1 1073 1356 592 19 778 1173 272 3022 909 20 329 534 377 73 272 21 608 904 903 1204 111 22 1221 1136 1258 4973 48516 23 1214 1200 1148 2761 2791 24 593 318 162 480 733 25 314 969 25 85 766 26 293 253 4878 46578 64614 27 1193 2716 24 2959 2841 28 318 260 58559 8961 4226 29 318 260 1196 2959 50 30 1077 1136 1230 1203 3481 642 123 593 750 1212 50 643 750 671 1663 2427 5618 644 780 3114 1584 11 62 645 912 2858 1617 1035 903 646 608 527 21 2710 1704 647 1196 720 5060 2599 594 648 46578 50 745 1223 5995 649 318 300 110 529 246 650 733 110 151 318 364 651 1240 1210 541 589 1247 652 4993 296 95510 122900 736 653 858 1225 1961 25 36 654 333 1221 3039 1610 4011 655 318 47 6377 527 2028 656 527 1193 1073 1265 73 657 527 349 454 357 97 658 457 590 480 589 329 659 474 508 1 288 477 660 904 1197 1247 858 1221 661 780 1527 3 1376 5481 662 110 590 50 593 733 663 2028 919 527 2791 110 664 1201 64839 1228 122886 1203 665 1197 858 7153 1221 6539 666 318 300 161 500 337 667 527 260 318 593 223 668 161 527 151 110 300 669 50 2858 4993 318 2628 670 296 5952 508 272 1196 671 1210 1200 7153 593 110 What is the best way to go about outputting this to a txt file (e.g. output.txt) such that the format look like this? User-id1 movie-id1 movie-id2 movie-id3 movie-id4 movie-id5 User-id2 movie-id1 movie-id2 movie-id3 movie-id4 movie-id5 The values on the far left are the userId's and the other values are the movieId's. Here is the code that generated the above:…
has answer: http://stackoverflow.com/a/48832218
favorite count: 0
has comment: http://stackoverflow.com/comment/84668445
has title: Outputting pandas series to txt file
answer count: 5
has answer: http://stackoverflow.com/a/48841479
tagged with: python
has comment: http://stackoverflow.com/comment/84668358
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/a/48854212
has body: Use pandas library to handle table-like data: import pandas as pd # Read to dataframe df = pd.read_json("https://www.bicing.cat/availability_map/getJsonObject") def return_stations(df, n=10, ascending=False): """a function allowing to order the bike-stations by available “slots” and display first N stations. The user can also choose to have the results in ascending or descending order (by default descending). The parameters are: -N: number of stations to display. It is optional and by default N=10. -order: It is optional and the default value is descending""" return (df.sort_values(by='slots',ascending=ascending) .head(n).set_index('id').to_dict('i')) # Let's print the first 3 in descending order print(return_stations(df, n=3, ascending=False)) Returns the following: {10: {'address': 'Carrer Comerç', 'addressNumber': '27', 'bikes': 0, 'district': 1, 'lat': 41.38498, 'lon': 2.18417, 'name': '10 - C/ COMERÇ, 27', 'nearbyStations': '9,14,115,389', 'slots': 33, 'stationType': 'BIKE', 'status': 'CLS', 'zip': 8003}, 213: {'address': 'Sant Fe de Nou Mèxic', 'addressNumber': '2', 'bikes': 0, 'district': 6, 'lat': 41.393783, 'lon': 2.135078, 'name': '213 - C/ SANTA FE DE NOU MÈXIC, 2', 'nearbyStations': '207,208,214,215', 'slots': 33, 'stationType': 'BIKE', 'status': 'OPN', 'zip': 8017}, 326: {'address': 'Balmes', 'addressNumber': '409', 'bikes': 0, 'district': 6, 'lat': 41.407384, 'lon': 2.1383, 'name': '326 - C/BALMES, 409', 'nearbyStations': '321,327,328,330', 'slots': 33, 'stationType': 'BIKE', 'status': 'OPN', 'zip': 8022}} Ohh and another thing... saw you got lat lng there: We could write a geojson file and plot it on map dropping the file on geojson.io. Here is a function for that: def return_geojson(df, latlng): d = dict(type="FeatureCollection",features=[]) for ind,row in df.fillna('').iterrows(): p = row.drop(latlng).to_dict() g = dict(type="Point",coordinates=list(row[latlng])[::-1]) f = dict(type="Feature", properties=p, geometry=g) d['features'].append(f) return…
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48853899
answers question: http://stackoverflow.com/q/48853899
type: Answer
upvote count: 2
downvote count: 1
score: 1

http://stackoverflow.com/comment/84831412
type: QuestionComment
score: 1
has text: ["delegation"](http://numpy-discussion.10968.n7.nabble.com/ufunc-delegation-to-object-method-td30270.html) is what I've heard people use but don't know whether that's an official technical term
comment on: http://stackoverflow.com/q/48912313
type: Comment

http://stackoverflow.com/comment/84727347
has text: Use `res = gray * mask[..., np.newaxis]` to expand the mask to all three channels.
type: AnswerComment
comment on: http://stackoverflow.com/a/48861545
score: 0
type: Comment

http://stackoverflow.com/a/48839529
has body: Since you claim that you can update the temperature measurement every 3 seconds, assuming update_every_3_seconds is the function to do that, add: high_temp_seconds = 0 ... def update_every_3_seconds(): ... global high_temp_seconds if high_temp: high_temp_seconds += 3 else: high_temp_seconds = 0 if high_temp_seconds &gt;= (10 * 60): activate_AC_relay()
answers question: http://stackoverflow.com/q/48839155
score: 0
type: Answer

http://stackoverflow.com/comment/85115623
type: Comment
comment on: http://stackoverflow.com/q/48840025
score: 0
type: QuestionComment
has text: Have you tried PCF (https://pivotal.io/platform)?

http://stackoverflow.com/comment/84853914
type: QuestionComment
has text: Is line 7 indented with 4 spaces or with tabs? Could the interpreter somehow expect a different number of spaces as indentation? What changes if you do 2, 4, 6 or 8 spaces?
score: 0
comment on: http://stackoverflow.com/q/48923721
type: Comment

http://stackoverflow.com/a/48959322
has body: you probably need this documentation. 1) from the documentation: invalid request: An API (URI) that does not exist including missing a required parameter. May also include an incorrect HTTP operation on a valid URI (such as a GET on a registration). Could also be POST multipart data that is syntactically invalid such as missing required headers or if the end-of-line characters are not CR-LF. 2) As far as I understand, this API accepts XML requests. See what appears after clicking on 'View XML' on the web page with results (https://ui.eidr.org/search/results). For the 'anderson cooper 360' you can use the XML data in Python like this: import requests import xml.etree.ElementTree as ET url = 'https://resolve.eidr.org/EIDR/query/' headers = {'Content-Type': 'text/xml', 'Authorization': 'Eidr 10.5238/webui:10.5237/D4C9-7E59:9kDMO4+lpsZGUIl8doWMdw==', 'EIDR-Version': '2.1'} xml_query = """ ASCII(((/FullMetadata/BaseObjectData/ResourceName "anderson" AND /FullMetadata/BaseObjectData/ResourceName "cooper" AND /FullMetadata/BaseObjectData/ResourceName "360") OR (/FullMetadata/BaseObjectData/AlternateResourceName "anderson" AND /FullMetadata/BaseObjectData/AlternateResourceName "cooper" AND /FullMetadata/BaseObjectData/AlternateResourceName "360")) AND /FullMetadata/BaseObjectData/Status "valid") 1 25 """ r = requests.post(url, data=xml_query, headers=headers) root = ET.fromstring(r.text) for sm in root.findall('.//{http://www.eidr.org/schema}SimpleMetadata'): print({ch.tag.replace('{http://www.eidr.org/schema}',''):ch.text for ch in sm.getchildren()}) 3) I don't think you need the session object.
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48955150

http://stackoverflow.com/comment/84678840
has text: @Piotr please check the last edit. I have tried to make it using the DRF's implemented exception but didn't work. Also I added `exception` parameter to the handler function to bind with handler404
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48836179

http://stackoverflow.com/q/48885836
tagged with: python
tagged with: pythonanywhere
has answer: http://stackoverflow.com/a/48891486
score: 0
tagged with: google-oauth
type: Question
tagged with: http-status-code-302
has body: I get this error : HttpResponseRedirect' object has no attribute 'authorize' I've printed HttpResponseRedirect object and I have something like this: HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="https://accounts.google.com/o/oauth2/auth?client_id=..." I've copied this url to my browser and it does work. When I run app locally everything works fine, but now I moved my app to pythonanywhere recently and it stopped working. Here is my code: def get_credentials(user): home_dir = os.path.expanduser('~') home_dir = BASE_DIR + '/oauth2/' + user.username credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'calendar-python-quickstart.json') storage = Storage(credential_path) credentials = storage.get() if not credentials or credentials.invalid: print(True) FLOW = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES,redirect_uri="http://XXXXXX.pythonanywhere.com/accounts/google/login/callback/") FLOW.params['state'] = xsrfutil.generate_token(SECRET_KEY, user) authorize_url = FLOW.step1_get_authorize_url() return HttpResponseRedirect(authorize_url) return credentials class EventTeamToggleAPI(LoginRequiredMixin, APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, *args, **kwargs): self.slug = self.kwargs.get('slug') team = get_object_or_404(Team,slug=self.slug) updated = False added = False user_other_teams = Team.objects.filter(user_team_events=self.request.user).exclude(pk=team.pk) games = Game.objects.filter(Q(team_home=team) | Q(team_away=team)) if self.request.user.google_cal==True: credentials = get_credentials(self.request.user) http = credentials.authorize(Http()) service = build('calendar', 'v3', http=http) {...} return(...) Can someone explain to me what is the problem ? Thanks
has title: Getting credential using GoogleAPI - HttpResponseRedirect status_code=302
answer count: 1
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/q/48831091
has comment: http://stackoverflow.com/comment/84670222
downvote count: 0
has answer: http://stackoverflow.com/a/50948931
has title: IPython console stuck on "Connecting to kernel..." (Spyder v3.2.6, Py 3.6, Windows 10, 64x)
has comment: http://stackoverflow.com/comment/84671421
has comment: http://stackoverflow.com/comment/84668061
type: Question
score: 3
has comment: http://stackoverflow.com/comment/84669072
tagged with: ipython
has answer: http://stackoverflow.com/a/48834580
upvote count: 3
answer count: 3
has body: Please bear with me, as I'm new to python and Stackoverflow. When starting Spyder (v3.2.6), my IPython console gets stuck on "Connecting to kernel..." All the solutions to similar inquiries that I can find seem to involve Anaconda, which I don't have installed (to my knowledge), and would prefer not to unless its absolutely necessary. I've tried opening new IPython consoles, restarting the kernel, restarting Spyder, resetting Spyder to factor default settings, but to no avail. Any help is appreciated!
linked to: http://stackoverflow.com/q/27802860
has answer: http://stackoverflow.com/a/63961137
favorite count: 0
type: UnansweredQuestion
tagged with: spyder
tagged with: python
tagged with: kernel

http://stackoverflow.com/q/48912526
upvote count: 3
type: Question
has body: I have Python Flask server and NodeJS server, I am running socket.io server on NodeJS and my static app is served using python Flask server. Is it possible to connect to the socket.io server through the Flask app? I am having difficulties proxying the /socket.io endpoint in NodeJS to Flask, any hints? I am using Socket.IO for NodeJS as server running at port 8888, python flask running at port 5000
score: 3
answer count: 1
downvote count: 0
tagged with: flask
favorite count: 0
has title: Websocket (socket.io) proxy with python flask and nodejs
type: UnansweredQuestion
tagged with: sockets
tagged with: python
has answer: http://stackoverflow.com/a/50473122
tagged with: node.js

http://stackoverflow.com/comment/84700082
comment on: http://stackoverflow.com/a/48848006
score: 0
type: AnswerComment
has text: Your code seems about right but I had a problem in line 5 where it says that the 'int' object is not callable.
type: Comment

http://stackoverflow.com/a/48855296
downvote count: 0
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48855261
has body: I think you should import this and then run your code : import mysql import mysql.connector
type: Answer

http://stackoverflow.com/comment/84930825
score: 0
has text: I would suggest follow KISS. Question being that *why* passing **method** which can be implemented more cleanly using Class itself. I would suggest try using methods as params to class objects only when they are dynamically validated and used (as in APIs).
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48962208

http://stackoverflow.com/comment/84737313
type: Comment
has text: you store them where you want, best is to store it as class attribute, then once set, you will be able to use them in all your class
score: 0
comment on: http://stackoverflow.com/q/48864655
type: QuestionComment

http://stackoverflow.com/q/48852125
type: Question
answer count: 2
downvote count: 0
has body: I'm experimenting with Text Summarization. I came across a github code which uses amazon food reviews dataset and Tensorflow 1.1.0 to write the code. I ran the code by putting a while loop on inference code so that I could check multiple summaries and worked well. checkpoint = "./best_model.ckpt" loaded_graph = tf.Graph() with tf.Session(graph=loaded_graph) as sess: # Load saved model loader = tf.train.import_meta_graph(checkpoint + '.meta') loader.restore(sess, checkpoint) input_data = loaded_graph.get_tensor_by_name('input:0') logits = loaded_graph.get_tensor_by_name('predictions:0') text_length = loaded_graph.get_tensor_by_name('text_length:0') summary_length = loaded_graph.get_tensor_by_name('summary_length:0') keep_prob = loaded_graph.get_tensor_by_name('keep_prob:0') while True: input_sentence = input() text = text_to_seq(input_sentence) #Multiply by batch_size to match the model's input parameters answer_logits = sess.run(logits, {input_data: [text]*batch_size, summary_length: [np.random.randint(5,8)], text_length: [len(text)]*batch_size, keep_prob: 1.0})[0] # Remove the padding from the tweet pad = vocab_to_int["&lt;PAD&gt;"] print('Original Text:', input_sentence) print('\nText') print(' Word Ids: {}'.format([i for i in text])) print(' Input Words: {}'.format(" ".join([int_to_vocab[i] for i in text]))) print('\nSummary') print(' Word Ids: {}'.format([i for i in answer_logits if i != pad])) print(' Response Words: {}'.format(" ".join([int_to_vocab[i] for i in answer_logits if i != pad]))) Some snippet of code to save the model: checkpoint = "best_model.ckpt" with tf.Session(graph=train_graph) as sess: sess.run(tf.global_variables_initializer()) # train the model if update_loss &lt;= min(summary_update_loss): print('New Record!') stop_early = 0 saver = tf.train.Saver() saver.save(sess, checkpoint) The whole code can be found on the link given above. When I stopped the model and rerun it but this time only commenting out the training the model part it didn't r…
has title: tensorflow: model is not restoring the weights
favorite count: 0
has answer: http://stackoverflow.com/a/48852451
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
has answer: http://stackoverflow.com/a/59468970
tagged with: tensorflow

http://stackoverflow.com/a/48828141
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48827611
has body: With the help of Jeremiah I was able to make it work in PyCharm and cmd. Here is the complete code: from colorama import Fore, Style, init import psutil import os if psutil.Process(os.getpid()).parent().name() == 'cmd.exe': init(convert=True) print(f'{Fore.GREEN}A') print(f'{Fore.RED}B') print('C') print(f'{Style.RESET_ALL}D') print('E')
upvote count: 1
score: 1

http://stackoverflow.com/comment/84630496
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48812559
type: QuestionComment
has text: There won’t be any change to this regular expression. Those are fixed and I was given input in that way. I don’t mind if regex is used or some other code. If there is solution without using regex, that’s absolutely fine. I just need to generate all possible finite sentences using these words. Thank you.

http://stackoverflow.com/q/48831544
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84686049
has comment: http://stackoverflow.com/comment/84684981
downvote count: 0
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84684915
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84685165
has answer: http://stackoverflow.com/a/54807580
tagged with: python
has body: Learning kivy. The script: from kivy.app import App from kivy.uix.button import Button class Test(App): def build(self): return Button() Test().run() The error: [INFO ] [Logger ] Record log in C:\Users\Paulo\.kivy\logs\kivy_18-02-16_2.txt [INFO ] [Kivy ] v1.10.0 [INFO ] [Python ] v3.6.2 (v3.6.2:5fd33b5, Jul 8 2017, 04:57:36) [MSC v.1900 64 bit (AMD64)] [INFO ] [Factory ] 194 symbols loaded [INFO ] [Image ] Providers: img_tex, img_dds, img_pil, img_gif (img_sdl2, img_ffpyplayer ignored) [INFO ] [Text ] Provider: pil(['text_sdl2'] ignored) [CRITICAL] [Window ] Unable to find any valuable Window provider. sdl2 - ImportError: DLL load failed: The specified module could not be found. File "C:\Users\Paulo\PycharmProjects\kivy\venv\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib fromlist=[modulename], level=0) File "C:\Users\Paulo\PycharmProjects\kivy\venv\lib\site-packages\kivy\core\window\window_sdl2.py", line 26, in &lt;module&gt; from kivy.core.window._window_sdl2 import _WindowSDL2Storage [CRITICAL] [App ] Unable to get a Window, abort. Exception ignored in: 'kivy.properties.dpi2px' Traceback (most recent call last): File "C:\Users\Paulo\PycharmProjects\kivy\venv\lib\site-packages\kivy\utils.py", line 496, in __get__ retval = self.func(inst) File "C:\Users\Paulo\PycharmProjects\kivy\venv\lib\site-packages\kivy\metrics.py", line 174, in dpi EventLoop.ensure_window() File "C:\Users\Paulo\PycharmProjects\kivy\venv\lib\site-packages\kivy\base.py", line 127, in ensure_window sys.exit(1) SystemExit: 1 [CRITICAL] [App ] Unable to get a Window, abort. Process finished with exit code 1
tagged with: kivy
has title: problems to run sdl2 under python 3.6.2
has comment: http://stackoverflow.com/comment/84671273
has comment: http://stackoverflow.com/comment/84685502
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84684957

http://stackoverflow.com/q/48909907
has title: Split data in columns in python
has answer: http://stackoverflow.com/a/48910086
has comment: http://stackoverflow.com/comment/84825985
score: 0
linked to: http://stackoverflow.com/q/15026698
has body: I'm trying to write a code that read from an external file a set of values like this: 4.87320984E-09 1 49.882684417026184 0.18691906898647714 0.22222662961584136 1.88917193E-09 2 49.882684417026184 0.18691906898647714 0.22222662961584136 1.30942168E-09 3 49.882684417026184 0.18691906898647714 0.22222662961584136 7.26580629E-10 4 49.882684417026184 0.18691906898647714 0.22222662961584136 5.39025047E-10 5 49.882684417026184 0.18691906898647714 0.22222662961584136 2.04686401E-08 1 68.253977742324736 -5.0977927905402787E-002 0.32783928527485512 3.08666603E-09 3 68.253977742324736 -5.0977927905402787E-002 0.32783928527485512 2.88387625E-09 4 68.253977742324736 -5.0977927905402787E-002 0.32783928527485512 1.15430343E-09 5 68.253977742324736 -5.0977927905402787E-002 0.32783928527485512 I want to store every column in a list and do some maths with them. import sys inFile = sys.argv[1] c1 = [] c2 = [] c3 = [] c4 = [] c5 = [] data = [c1,c2,c3,c4,c5] with open(inFile,'r') as i: lines = i.read().split('\n') for row in lines: #split in columns and do some maths print data
has answer: http://stackoverflow.com/a/48910059
has answer: http://stackoverflow.com/a/48910342
has comment: http://stackoverflow.com/comment/84825876
linked to: http://stackoverflow.com/q/25013792
answer count: 5
has comment: http://stackoverflow.com/comment/84825828
tagged with: python
has answer: http://stackoverflow.com/a/48909991
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48910161

event-handling
tag name: event-handling
tags question: http://stackoverflow.com/q/48938991
tags question: http://stackoverflow.com/q/48862090
type: Tag

http://stackoverflow.com/a/55120085
upvote count: 1
has body: If the kernel from another conda environment is not visible in Jupyter, have a look at the nb_conda_kernels package. It finds existing conda environments and dynamically adds ipython kernels to Jupyter.
answers question: http://stackoverflow.com/q/48820769
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/48830525
has comment: http://stackoverflow.com/comment/84666600
has comment: http://stackoverflow.com/comment/84665029
type: AcceptedAnswer
downvote count: 0
has body: Use sum with unstack and stack: df = df.sum(level=[0,1]).unstack(fill_value=0).stack() #same as #df = df.groupby(level=[0,1]).sum().unstack(fill_value=0).stack() Alternative with reindex: df = df.sum(level=[0,1]) #same as #df = df.groupby(level=[0,1]).sum() mux = pd.MultiIndex.from_product(df.index.levels, names = df.index.names) df = df.reindex(mux, fill_value=0) Alternative1, thanks @Wen: df = df.sum(level=[0,1]).unstack().stack(dropna=False) print (df) volume1 volume2 year product 2010 A 17 15 B 7 7 C 0 0 2011 A 10 10 B 7 6 C 5 5
score: 3
type: Answer
answers question: http://stackoverflow.com/q/48830485
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48830485

http://stackoverflow.com/q/48917186
has comment: http://stackoverflow.com/comment/84840890
has answer: http://stackoverflow.com/a/48917534
has comment: http://stackoverflow.com/comment/84840887
tagged with: pandas
has comment: http://stackoverflow.com/comment/84840914
tagged with: python
favorite count: 0
score: 2
has comment: http://stackoverflow.com/comment/84840963
upvote count: 2
has body: I have a dataframe like below. I would like to remove duplicates from only one column while keeping the rest of the row intact. The logic that i want is - For the column Jan, start from the last row for the last cell, if the value in the second last row is same as the current value then delete just the cell value (don't delete row). and continue till you reach the first row sales = [{'account': '3', 'Jan': 'try', 'Feb': '200 .jones', 'URL': 'ea2018-001.pdf try bbbbb why try'}, {'account': '1', 'Jan': 'try', 'Feb': '210', 'URL': 'try '}, {'account': '2', 'Jan': 'bbbbb', 'Feb': '90', 'URL': 'ea2017-104.pdf bb cc for why' }] df = pd.DataFrame(sales) df df Out[105]: Feb Jan URL account 0 200 .jones try ea2018-001.pdf try bbbbb why try 3 1 210 try try 1 2 90 bbbbb ea2017-104.pdf bb cc for why 2 Output that i want is as below Feb Jan URL account 0 200 .jones try ea2018-001.pdf try bbbbb why try 3 1 210 try 1 2 90 bbbbb ea2017-104.pdf bb cc for why 2
accepted answer: http://stackoverflow.com/a/48917534
type: AnsweredQuestion
has title: pandas drop duplicates from a single column while keeping remaining row intact
tagged with: duplicates
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84840924
possible better answer: http://stackoverflow.com/a/48917658
downvote count: 0
has answer: http://stackoverflow.com/a/48917658

http://stackoverflow.com/comment/84876386
type: Comment
has text: thanks for the script. I am trying to run the script and facing few errors. Can you please let me know version and ide tool you using to compile the script.
comment on: http://stackoverflow.com/a/48931322
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84738860
comment on: http://stackoverflow.com/a/48867498
score: 0
type: AnswerComment
type: Comment
has text: I edited my file to put `[ ]` as outermost bracket, still getting this error ``Expecting value: line 1 column 1 (char 0)``

http://stackoverflow.com/a/48857085
has body: I don't think this question would help anyone but you in its current state but I think what you're trying to achieve can be done by replacing: def button_function(): a = float( mydict[get(entry1)] ) * float( mydict[get(entry1)] ) * float( mydict[get(entry1)] ) *float( mydict[get(entry2)] ) * float( mydict[get(entry3)] ) *float( mydict[get(entry4)] ) * float( mydict[get(entry5)] ) * float( mydict[get(entry5)] ) * float( mydict[get(entry6)]) ... with: def button_function(): a = float( mydict[entry1.get()] ) * float( mydict[entry1.get()] )\ * float( mydict[entry1.get()] ) *float( mydict[entry2.get()] )\ * float( mydict[entry3.get()] ) *float( mydict[entry4.get()] )\ * float( mydict[entry5.get()] ) * float( mydict[entry5.get()] )\ * float( mydict[entry6.get()]) ... Additionally, add: label16.grid() button1.grid() in order to display, not shown but obviously required to be shown widgets.
has comment: http://stackoverflow.com/comment/84717968
type: Answer
answers question: http://stackoverflow.com/q/48856920
score: 0

http://stackoverflow.com/q/48877457
has body: My project involves reading CSV files concering city data and then computing various statistics. I am trying to create a function that will take city data from a CSV and the create a copy of the data except with a date filter applied. The user is prompted to enter a starting and ending date. I am currently just testing and trying to get the data to print with the correct date filters applied. My biggest problem so far is that I can't seem to convert the strings entered by the user into a datetime format. Is there a way for the user to directly enter the data in datetime format? def date_filtering(city_file): date1 = input('Please enter a valid start date that you wish to explore?\n' date2 = input('Please enter a valid end date.') print(city_file.loc[date1:date2]) Thanks in advance!
has answer: http://stackoverflow.com/a/48877541
has comment: http://stackoverflow.com/comment/84759031
score: -2
has comment: http://stackoverflow.com/comment/84759052
has comment: http://stackoverflow.com/comment/84758997
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84759019
downvote count: 3
has comment: http://stackoverflow.com/comment/84759053
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/84758966
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48877541
has comment: http://stackoverflow.com/comment/84758977
has title: How to specify input as datetime?
type: Question

twilio
tag name: twilio
tags question: http://stackoverflow.com/q/48822760
tags question: http://stackoverflow.com/q/48952723
tags question: http://stackoverflow.com/q/48864442
tags question: http://stackoverflow.com/q/48958682
type: Tag

http://stackoverflow.com/q/48905974
has title: Django Rest Framework: Overwriting validation error keys
tagged with: serialization
type: UnansweredQuestion
tagged with: django
has answer: http://stackoverflow.com/a/48906865
score: 3
downvote count: 0
has body: When translating my site to another language a problem occurred. I want to handle Validation Errors properly and allow my front-end friends to display them well. Is there a way to overwrite keys in response message of DRF when Validation Error happend? What do I mean by that - I want to change this: { "name": ["This field is required."] } into: { "username": ["This field is required."] } Is there a way to do that without writing each and every one of validators?
type: Question
tagged with: validation
tagged with: django-rest-framework
upvote count: 3
answer count: 1
tagged with: python
favorite count: 0

http://stackoverflow.com/q/48823942
has title: python: remove type from defaultdict
upvote count: 0
has body: i have the following code: #!/usr/bin/python farm_sub_count = [[['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium'], 2], [['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Standard'], 2], [['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium'], 1]] from collections import defaultdict d = defaultdict(lambda: defaultdict(int)) for (a, b), c in farm_sub_count: d[a][b] += c print( dict(d) ) print( dict.__repr__(d) ) i am getting the following output: {Farm - defaultdict(&lt;type 'int'&gt;, {u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Standard': 2, u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium': 3}) i dont want to see the type ,i just want to see the date: {Farm: {u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Standard': 2, u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium': 3})} i looked at other thrieds ,and they recomended to convert it to dic: print( dict(d) ) or print( dict.__repr__(d) ) i am still getting the type
type: Question
score: -2
has comment: http://stackoverflow.com/comment/84651409
downvote count: 2
answer count: 2
favorite count: 0
has answer: http://stackoverflow.com/a/48826124
tagged with: defaultdict
has answer: http://stackoverflow.com/a/48823983
type: UnansweredQuestion
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/84838602
comment on: http://stackoverflow.com/q/48913757
score: 0
type: Comment
type: QuestionComment
has text: @ScottBoston, Let me know if this is what you were looking for!

http://stackoverflow.com/q/48867800
favorite count: 0
upvote count: 5
tagged with: focus
has title: Tk Treeview Focus(). How do I Get Multiple Selected Lines?
tagged with: python
tagged with: tkinter
type: UnansweredQuestion
tagged with: treeview
type: Question
has body: ttk.treeview.focus() returns the iid of a single line. The treeview box allows you to select multiple lines. How do I get a list of iids for the selected lines?
tagged with: ttk
has answer: http://stackoverflow.com/a/48867937
answer count: 2
downvote count: 1
has answer: http://stackoverflow.com/a/48867913
score: 4

http://stackoverflow.com/a/48815765
upvote count: 1
has body: This is happening because you are calling functions before you define them. Remove the calls to the functions before the definitions i.e. delete: circle() rectangle() triangle() that occur right above def circle ():....
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48815486
type: Answer
accepted answer of: http://stackoverflow.com/q/48815486
score: 1

http://stackoverflow.com/q/48895676
has body: I'm learning Python as my first language and now I trying to resolve this problem: I have to make a loop where I ask the user which elements from a list they want to remove and then remove the elements selected. The loop stops only when the user insert a specific number that corresponds to the length of the list increased by 1 (so I won't have any problem). I have another problem related to this: elements_list = ['a','b','c','d'] length_list = len(elements_list) for i in range(0, length_list): print (str(i) + str(')') + elements_list[i]) This will print the list starting with 0: 0) a 1) b 2) c 3) d What do I have to do if I want the list start with 1? (if I use 1 instead of 0 in the range it doesn't print the first element of the list)
answer count: 2
downvote count: 0
favorite count: 0
has title: Input in a cycle (Python)
has answer: http://stackoverflow.com/a/48895698
tagged with: python
type: UnansweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84797140
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48895712

qevent
tags question: http://stackoverflow.com/q/48873483
type: Tag
tag name: qevent

http://stackoverflow.com/comment/84663282
type: Comment
has text: The point with proper packaging + pip is that you can use them in a virtualenv (both for dev and deployment). Using a requirement file, you can make sure you have a stable environment with all dependencies.
comment on: http://stackoverflow.com/a/48828803
type: AnswerComment
score: 0

http://stackoverflow.com/a/49017278
type: Answer
answers question: http://stackoverflow.com/q/48893881
score: 0
has body: While getHexChar returns a single character string, decToHex does print individual digits on the fly instead. Minimal change to get your expected output out of your code could be: def main(): og_dec_value = int(input("Enter decimal value: ")) print(og_dec_value,"is equal to",decToHex(og_dec_value), "in hexadecimal") def decToHex(dec_value): ret_val = str() while dec_value &gt; 0: hex_value=dec_value%16 dec_value=dec_value//16 ret_val = getHexChar(hex_value) + ret_val return ret_val def getHexChar(dec_digit): if dec_digit &lt; 10: return str(dec_digit) if dec_digit == 10: return "A" if dec_digit == 11: return "B" if dec_digit == 12: return "C" if dec_digit == 13: return "D" if dec_digit == 14: return "E" if dec_digit == 15: return "F" main() That out of the way. I really am not sure what the problem with hex() is. And if I was looking for another way of converting into hex string representation, I would (as suggested by Moinuddin Quadri) opt for corresponding formatting '{0:x}'.format(int(dec)) or '%x' % int(dec) if you'd prefer the older style (you probably should not). If that is still now what you want and you wanted to maintain your course of cation, you could at least significantly simplify the getHexChar() for instance by doing this: def getHexChar(dec_digit): return '{:x}'.format(range(16)[dec_digit]) Or we formatting really is an anathema: def getHexChar(dec_digit): return str((tuple(range(10)) + ('a', 'b', 'c', 'd', 'e', 'f'))[dec_digit])

http://stackoverflow.com/q/48843761
tagged with: http://stackoverflow.com/tag/csv
answer count: 1
tagged with: python
favorite count: 0
has body: I am trying to scrape some .csv files from a website. I currently have a list of links: master_links = [ 'http://mis.nyiso.com/public/csv/damlbmp/20161201damlbmp_zone_csv.zip', 'http://mis.nyiso.com/public/csv/damlbmp/20160301damlbmp_zone_csv.zip', 'http://mis.nyiso.com/public/csv/damlbmp/20160201damlbmp_zone_csv.zip'] when I try to use: pd.read_csv(master_links[0])] it returns an error because each .zip file contains multiple .csv within them. I understand why this isn't working, but I haven't figured out how to unzip these files, and then put the .csv files into pd.read_csv without saving everything to my computer. Is this possible?
tagged with: http://stackoverflow.com/tag/zip
has answer: http://stackoverflow.com/a/48844157
upvote count: 1
type: AnsweredQuestion
score: 1
accepted answer: http://stackoverflow.com/a/48844157
type: Question
linked to: http://stackoverflow.com/q/50991084
has title: How to scrape .csv files from a url, when they are saved in a .zip file in Python?
downvote count: 0
tagged with: pandas

http://stackoverflow.com/q/48881586
has title: matplotlib says image is too large when it's not
has answer: http://stackoverflow.com/a/48882419
has body: I'm doing this plotting in Jupyter Notebook: fig = plt.figure() fig.suptitle("{0} nodes".format(i*4)) print("put suptitle") fig.text(0,0,s="error: {0}".format(errors[i-1])) print("put text") plt.plot(means, np.zeros(means.shape), "go") print(means.shape) plt.plot(patterns_test, outputs, "r.", label="outputs") print(patterns_test.shape, outputs.shape) plt.plot(patterns_test, targets_test, "b.", label="targets") print(patterns_test.shape, targets_test.shape) plt.legend() print("legend") I've printed the shape of everything that it plotted, and the values returned are: put suptitle put text (16,) (62,) (62,) (62,) (62,) legend Clearly nothing is large. But here's the error message: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) /anaconda3/lib/python3.6/site-packages/IPython/core/formatters.py in __call__(self, obj) 339 pass 340 else: --&gt; 341 return printer(obj) 342 # Finally look for special method names 343 method = get_real_method(obj, self.print_method) /anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py in &lt;lambda&gt;(fig) 236 237 if 'png' in formats: --&gt; 238 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs)) 239 if 'retina' in formats or 'png2x' in formats: 240 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs)) /anaconda3/lib/python3.6/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs) 120 121 bytes_io = BytesIO() --&gt; 122 fig.canvas.print_figure(bytes_io, **kw) 123 data = bytes_io.getvalue() 124 if fmt == 'svg': /anaconda3/lib/python3.6/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs) 2265 orientation=orientation, 2266 bbox_inches_restore=_bbox_inches_restore, -&gt; 2267 **kwargs) 2268 finally: 2269 if bbox_inches and restore_bbox: /anaconda3/lib/python3.6/site-packages/matplotlib/backends/backend…
upvote count: 3
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/84767730
has answer: http://stackoverflow.com/a/50116472
score: 1
tagged with: matplotlib
type: Question
has answer: http://stackoverflow.com/a/55745262
answer count: 3
favorite count: 0
tagged with: python
tagged with: jupyter-notebook

http://stackoverflow.com/comment/84932068
type: Comment
type: QuestionComment
has text: thanks sean, its only printing 4.0 now though
comment on: http://stackoverflow.com/q/48962922
score: 0

http://stackoverflow.com/q/48818406
has comment: http://stackoverflow.com/comment/84640831
has answer: http://stackoverflow.com/a/48818502
tagged with: pandas
tagged with: python
accepted answer: http://stackoverflow.com/a/48818502
upvote count: 1
possible better answer: http://stackoverflow.com/a/48818461
type: AnsweredQuestion
has title: Python append dataframe such that only columns remain the same
has answer: http://stackoverflow.com/a/48818461
has comment: http://stackoverflow.com/comment/84640718
score: 1
tagged with: dataframe
type: Question
answer count: 2
downvote count: 0
has body: I have the following dataframes in python pandas: A: 1 2 3 4 5 6 7 8 9 10 0 1 1 1 1 1 1 1 0 0 1 1 B: 1 2 3 4 5 6 7 8 9 10 1 0 1 1 1 1 1 1 0 0 1 0 C: 1 2 3 4 5 6 7 8 9 10 2 0 1 1 1 0 0 0 0 0 1 0 I want to concatenate them together such that the column titles remain the same while row index and values get appended so the new dataframe is: df: 1 2 3 4 5 6 7 8 9 10 0 1 1 1 1 1 1 1 0 0 1 1 1 0 1 1 1 1 1 1 0 0 1 0 2 0 1 1 1 0 0 0 0 0 1 0 I have tried using append and concat but none seem to be fulfilling the output I am trying to achieve. Any suggestions? Here is what I tried: df = pd.concat([df,pd.concat([A,B,C], ignore_index=True)], axis=1)
favorite count: 0

http://stackoverflow.com/a/48941430
has body: mylist is a two dimensional structure - a list of tuples; with your current loop, you will actually get the first four tuples in the list - not the 4 tuples members, as you would expect. Presuming you want each tuple, on a separate line, this will get it for you: body = '' for line in mylist: body += "'%s,%s,%s,%s\n'"% (line[0],line[1],line[2],line[3]) Note each new line is appended (+=), and finishes with a newline chapter (\n). That will get you the message content you might actually expect, but will most probably not resolve your issue "But I receive an email with an empty body.". The reason for it is the lack of any headers in the message; according to RFC 5322 - the latest standard, there must be at least a From and Date headers. Some MTAs are quite forgiving and will accept the message without them, but those are minorities. So the actual body initialization should be (instead of the empty string up there): import datetime date = datetime.datetime.now().strftime( "%d/%m/%Y %H:%M" ) body = 'From: %s\r\nDate: %s\r\n\r\n'% (sender, date) # the loop follows Note the delimiter between the headers is \r\n - CRLF, and the headers are separated from the message body with a blank line. By the way, the majority of the users go with the email.mime.text.MIMEText class and its surrounding package, precisely not to deal with this low-level operations.
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84889922
accepted answer of: http://stackoverflow.com/q/48940997
answers question: http://stackoverflow.com/q/48940997

http://stackoverflow.com/comment/84845182
has text: @SruthiV: That'd accomplish nothing, given that `r` is already cast to a `float` by the time they're using it.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48919353

http://stackoverflow.com/q/48837476
favorite count: 0
type: Question
tagged with: legend
has answer: http://stackoverflow.com/a/48839022
tagged with: python
has title: Set up labels and legend using plt.subplots()
upvote count: 1
answer count: 1
tagged with: matplotlib
tagged with: dataframe
type: UnansweredQuestion
tagged with: label
has body: I am using plt.sublot to create a figure with 12 subplots that share the same data so I want to show the labels and legend for one of them. I am accessing and plotting the data from a dictionary that contains pandas dataframes each with 20 columns(labels). Here my code: fig, axes = plt.subplots(nrows=3, ncols=4, sharex=True, sharey=True) plt.subplots_adjust(left = 0.06, bottom = 0.1, right = 0.8, top=0.9, wspace=0.15, hspace=0.15) fig.suptitle('HMC Water Balance', fontsize = 20, y= 0.95, x=0.45) axes[0,0].plot(HMC_hydrographs['outlet']) axes[0,1].plot(HMC_hydrographs['Outlet00']) axes[0,2].plot(HMC_hydrographs['Outlet01']) axes[0,3].plot(HMC_hydrographs['Outlet02'], label = 'Q_total','Q_reset','Q_river_initial', ...'20th_column_name') ax = axes[0,3] ax.legend(loc=0, prop={'size':8}) axes[1,0].plot(HMC_hydrographs['Outlet03']) ax = axes[1,0] ax.set_ylabel('Flux (m$^3$/s)', labelpad=10, fontsize = 18) axes[1,1].plot(HMC_hydrographs['Outlet04']) axes[1,2].plot(HMC_hydrographs['Outlet05']) axes[1,3].plot(HMC_hydrographs['Outlet06']) axes[2,0].plot(HMC_hydrographs['Outlet07']) axes[2,1].plot(HMC_hydrographs['Outlet08']) ax = axes[2,1] ax.set_xlabel('Time (days)', fontsize = 18) ax.xaxis.set_label_coords(1.1,-0.2) axes[2,2].plot(HMC_hydrographs['Outlet09']) axes[2,3].plot(HMC_hydrographs['Outlet10']) I get the error: File "&lt;ipython-input-249-7e4552c68d90&gt;", line 8 axes[0,3].plot(HMC_hydrographs['Outlet02'], label = 'Q_total','Q_reset','Q_river_initial') ^ SyntaxError: positional argument follows keyword argument For what I understand the label argument takes only one argument but I have more than one label! Please help me understand how to call the labels so they show like when I plot a single graph like: fig = plt.figure() ax = HMC_hydrographs['Outlet01'].plot() Individual plot showing the correct labels
downvote count: 0
score: 1

http://stackoverflow.com/q/48950073
favorite count: 0
tagged with: generator
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/68236779
upvote count: 1
has answer: http://stackoverflow.com/a/58164522
has answer: http://stackoverflow.com/a/48950445
has answer: http://stackoverflow.com/a/75181787
has answer: http://stackoverflow.com/a/78540683
downvote count: 5
has comment: http://stackoverflow.com/comment/84906569
has body: #function def fact(x): a = 1 b = 1 if x == 0: a = 1 if x &lt; 0: print('enter valid whole number!') if x &gt; 0: while b &lt; x: a = a * b b += 1 yield a #main z = input('Enter a number') g = (fact(n) for n in range (0,int(z))) print(next(g)) When I am running the above program the output is showing a generator object at some block like this: Enter a number4 &lt;generator object fact at 0x03DF6930&gt;
type: Question
has answer: http://stackoverflow.com/a/77251481
has answer: http://stackoverflow.com/a/73657565
answer count: 8
tagged with: function
score: -4
has comment: http://stackoverflow.com/comment/84906516
tagged with: factorial
has answer: http://stackoverflow.com/a/53219130
has title: Factorial Program in Python using generator
tagged with: python

http://stackoverflow.com/comment/84739249
type: QuestionComment
comment on: http://stackoverflow.com/q/48866978
has text: Sorry, what is `ACTUAL_COVER`?
score: 0
type: Comment

http://stackoverflow.com/comment/84637816
comment on: http://stackoverflow.com/a/48810638
type: Comment
score: 0
has text: The only difference that I can see is that I put ``django.contrib.admin`` at the very end of my ``INSTALLED_APPS `` like so: https://pastebin.com/raw/CdnAdNmy
type: AnswerComment

http://stackoverflow.com/q/48897369
tagged with: python
tagged with: php
answer count: 0
has comment: http://stackoverflow.com/comment/84840252
has comment: http://stackoverflow.com/comment/84841341
type: Question
has comment: http://stackoverflow.com/comment/84837347
has title: Open a new HTML page with PHP and populate HTML page with string
tagged with: fgets
score: 0
has comment: http://stackoverflow.com/comment/84800432
has comment: http://stackoverflow.com/comment/84840193
has comment: http://stackoverflow.com/comment/84837710
has body: I am running a python script inside my PHP file to do some analysis. After, "fgets" is used to extract the output and store the extraction in a string variable. What I am trying to do: -I have an echo statement in my PHP file that outputs a button called "Full analysis." When a user clicks on that button, I want to open up a new page on a new tab and the new page will contain the output stored on the string variable. Is this possible? I've tried searching around and not getting much luck. Could you guys point me in the right direction? Thank you. Edit: Code to run python script: $output= popen("python param1 param2 " 2&gt;&amp;1", "r"); if ($output) { while (($line = fgets($output)) !== false) { #echo $line; $str_var .= $line . '&lt;br&gt;'; } if ($str_var == ""){ $str_var = "ERR: "; } }else{ $analysis_output = "Cannot run $str_var "; } fclose($output); } PHP code to out a button using HTML: echo "&lt;pre&gt;&lt;a target='_blank' href='http://" . param . "'&gt;" . "&lt;button&gt;" . "More info" . "&lt;/button&gt;" ."&lt;a/&gt;\n";
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/comment/84822188
type: Comment
has text: I like to save off the "pieces" into their own variables. e.g. `is_valid = (a == 1 and b == 2 and c == 4)`, `has_some_atttribute = (d == 4 and e == 5)`, `if is_valid or has_some_attribute: ...`
type: QuestionComment
comment on: http://stackoverflow.com/q/48908116
score: 1

http://stackoverflow.com/comment/84866845
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48927439
type: Comment
has text: What happens when you set `filter_fields` like `filter_fields = ['customer_id']` ?

http://stackoverflow.com/q/48821520
has body: I need to create 189 instances of class.Name that contains string. How can I do that? Following code does not work. def naming_of_sequence_neurons(): letters_list = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "y"] input_neuron_web = [] def naming_cycle(number): for j in range(0, 21): input_neuron_web[j][number] = Neuron.name = (letters_list[j] + str(number)) for i in range(0, 9): naming_cycle(i) return input_neuron_web inputed = naming_of_sequence_neurons() for a in range(0, 21): for b in range(0, 9): print(inputed[a][b].name)
has answer: http://stackoverflow.com/a/48821944
tagged with: python
has title: How to create multiple count of classes instances in Python?
favorite count: 0
tagged with: python-3.x
tagged with: instance
upvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48821944
score: 1
tagged with: class
type: Question
has comment: http://stackoverflow.com/comment/84646811
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/84794159
type: QuestionComment
has text: I added a simplified version of the code I was using with DataFrame with some fake data.
comment on: http://stackoverflow.com/q/48893893
score: 0
type: Comment

http://stackoverflow.com/q/48865303
accepted answer: http://stackoverflow.com/a/48865745
score: 2
has comment: http://stackoverflow.com/comment/84737886
favorite count: 0
has comment: http://stackoverflow.com/comment/84734997
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84737619
upvote count: 2
tagged with: python
has title: How to get Json's parent element using Python
has body: There is json like the following. { { "id": 1, "child": [ { "id": 4, "child": [], }, { "id": 2, "child": [ { "id": 37, "child": [], }, { "id": 39, "child": [], } ] }, { "id": 3, "child": [], }, ] }, { "id": 120, "child": [], }, { "id": 121, "child": [ { "id": 122, "child": [], } ] } } For example, what would you do if you wanted to get the id of the parent element of an element whose id is 37? In this case we want to get in a list such as [1, 2]. I thought that we should recursively process as below, but I do not know how to get parent elements when id matches. def get_parent(self, json_tree, target_id): for element in json_tree: if element['id'] == target_id: ???? else: if element['child']: self.get_routes_tree(element['child'], target_id)
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48865745
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/48872569
type: Question
answer count: 2
possible better answer: http://stackoverflow.com/a/48872569
downvote count: 0
has comment: http://stackoverflow.com/comment/84744154
has comment: http://stackoverflow.com/comment/84738976
has comment: http://stackoverflow.com/comment/84734028

http://stackoverflow.com/comment/84884120
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48937882
has text: It has to be instances of a class. So a list would not work in this scenario

http://stackoverflow.com/comment/84783331
has text: I want to thank you looking into this issue! You say _"This implies that, for whatever reason (maybe cache?), creating such a large array filled with the same constant once may be less efficient than creating k smaller arrays with the same constant ..."_ I am not sure this is the case in *your* functions: in both methods you create one large array `np.ones_like(arr)`. In `method2()` you just create views into that array inside the loop - you do not *create* many smaller arrays. Am I missing something?
comment on: http://stackoverflow.com/a/48888971
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84870590
type: Comment
type: QuestionComment
has text: I created a [minimal example](https://gist.github.com/six8/41d5f2fd59e7f5ed87dc10e8f250d91c) and did not have issues running this. Is something possibly wrong with your setup.py? If you run Python interpreter in the container can you `import pkg_name`?
comment on: http://stackoverflow.com/q/48911094
score: 0

http://stackoverflow.com/a/48921839
has comment: http://stackoverflow.com/comment/84850316
has body: You may can check if concatenate works for this. t1 = np.arange(0.0, 150.0, 0.01) t2 = np.arange(150.0, 200.0, 0.01) t = np.concatenate((t1,t2)) vE1 = np.where(t1&lt;50, 2580, 0) vE2 = np.where(t2&gt;150, 5000, 0) vE = np.concatenate((vE1,vE2))
type: Answer
score: 0
answers question: http://stackoverflow.com/q/48921583

http://stackoverflow.com/comment/84761820
type: Comment
type: QuestionComment
has text: You should probably look into `__radd__`
score: 3
comment on: http://stackoverflow.com/q/48878949

http://stackoverflow.com/a/48818513
upvote count: 9
has body: You should load image with IMREAD_UNCHANGED, i.e. import cv2 as cv img = cv.imread("./Green/imgage-000.png", cv.IMREAD_UNCHANGED) Then, your image will have 4 channels (BGRA), and you can use alpha channel mask to turn the corresponding part to white: alpha_channel = img[:, :, 3] _, mask = cv.threshold(alpha_channel, 254, 255, cv.THRESH_BINARY) # binarize mask color = img[:, :, :3] new_img = cv.bitwise_not(cv.bitwise_not(color, mask=mask)) I tested this code with a transparent PNG where the color channels were black and the information was in the transparency: The nested bitwise_not is ugly but is the only way I found to make it work.
score: 9
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48816703
answers question: http://stackoverflow.com/q/48816703

http://stackoverflow.com/q/48925255
type: Question
tagged with: python-2.7
answer count: 2
has comment: http://stackoverflow.com/comment/84857020
has title: FBProphet giving error when growth='logistic' python
accepted answer: http://stackoverflow.com/a/48926703
score: 4
favorite count: 0
has comment: http://stackoverflow.com/comment/84857123
has comment: http://stackoverflow.com/comment/84856728
possible better answer: http://stackoverflow.com/a/68233500
tagged with: python
has answer: http://stackoverflow.com/a/68233500
tagged with: facebook-prophet
has comment: http://stackoverflow.com/comment/84857166
downvote count: 1
has answer: http://stackoverflow.com/a/48926703
type: AnsweredQuestion
has body: Here is the code data and the error that I am facing while using Fbprophet library in python. DATA Timestamp Open High Low y Volume \ 0 1519084800 11379.2 11388.9 11379.2 11388.9 0.083001 1 1519084860 11362.0 11362.0 11362.0 11362.0 0.017628 2 1519084920 11383.9 11395.0 11370.7 11393.0 3.023621 3 1519084980 11384.3 11399.0 11379.9 11387.3 2.979175 4 1519085040 11395.0 11400.0 11390.1 11390.1 1.430360 ds y_orig y_pred 0 2018-02-20 00:00:00 11388.9 9.340394 1 2018-02-20 00:01:00 11362.0 9.338030 2 2018-02-20 00:02:00 11393.0 9.340754 3 2018-02-20 00:03:00 11387.3 9.340254 4 2018-02-20 00:04:00 11390.1 9.340500 Code: model = Prophet(growth='logistic') model.fit(data); #create 12 months of future data future_data = model.make_future_dataframe(periods=1, freq = 'M') #forecast the data for future data forecast_data = model.predict(future_data) Error: --------------------------------------------------------------------------- AssertionError Traceback (most recent call last) &lt;ipython-input-25-c41038b3c799&gt; in &lt;module&gt;() 1 model = Prophet(growth='logistic') ----&gt; 2 model.fit(data); 3 4 #create 12 months of future data 5 future_data = model.make_future_dataframe(periods=1, freq = 'M') /usr/local/lib/python2.7/dist-packages/fbprophet/forecaster.pyc in fit(self, df, **kwargs) 776 self.history_dates = pd.to_datetime(df['ds']).sort_values() 777 --&gt; 778 history = self.setup_dataframe(history, initialize_scales=True) 779 self.history = history 780 self.set_auto_seasonalities() /usr/local/lib/python2.7/dist-packages/fbprophet/forecaster.pyc in setup_dataframe(self, df, initialize_scales) 242 df['floor'] = 0 243 if self.growth == 'logistic': --&gt; 244 assert 'cap' in df 245 df['cap_scaled'] = (df['cap'] - df['floor']) / self.y_scale 246 AssertionError: Please let me know how I can resolve this issue.
upvote count: 5
has comment: http://stackoverflow.com/comment/84856895

http://stackoverflow.com/q/48948308
score: 34
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84902978
has body: On a numpy array, why is it I can successfully use / 2: &gt;&gt;&gt; a=np.array([2, 4, 6]) &gt;&gt;&gt; a = a / 2 &gt;&gt;&gt; a array([ 1., 2., 3.]) But I cannot use a /= 2? &gt;&gt;&gt; a=np.array([2, 4, 6]) &gt;&gt;&gt; a /= 2 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; TypeError: No loop matching the specified signature and casting was found for ufunc true_divide I've seen numpy Issue 6464, but don't understand from reading it and the linked release notes the reason this doesn't work. Is there any way to get /= to work as expected?
type: Question
tagged with: numpy
answer count: 2
accepted answer: http://stackoverflow.com/a/48948461
upvote count: 35
tagged with: arrays
has title: Can't use /= on numpy array
tagged with: array-broadcasting
favorite count: 0
possible better answer: http://stackoverflow.com/a/48948504
has answer: http://stackoverflow.com/a/48948504
has answer: http://stackoverflow.com/a/48948461
tagged with: python

http://stackoverflow.com/comment/84922680
has text: I expected the same number repeated many times, whatever the formula calculated it to be. The fact that `paths[0][1]` is being interpreted like `paths[i][1]` is throwing a hitch in my code elsewhere.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48957769

http://stackoverflow.com/comment/84787438
type: QuestionComment
has text: "I have tried many things" Like what?
score: 1
comment on: http://stackoverflow.com/q/48891038
type: Comment

http://stackoverflow.com/comment/84661701
score: 0
type: Comment
has text: @creedqq pass it as `r"""a."b.t".qq"""` or `"""a.\"b.t\".qq"""` or `'a.\"b.t\".qq'`
comment on: http://stackoverflow.com/a/48826935
type: AnswerComment

http://stackoverflow.com/a/48823796
type: Answer
has body: Adding global result to the main body of main() does the job. Credits to A False Name for the answer. Thanks! def main(): global result ......
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84651103
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48823387
answers question: http://stackoverflow.com/q/48823387
has comment: http://stackoverflow.com/comment/84651190

http://stackoverflow.com/comment/84728074
type: QuestionComment
type: Comment
has text: Why do you want to store profile images in the first place? You can just use the URL that automatically redirects to the user’s _current_ profile picture ... You are supposed to keep such data up-to-date anyways, and even if you did this every time I logged in to your app ... if I did _not_ log in to your app for a longer period of time, you might be showing other users an outdated profile picture of me, because in the meantime I already changed it on Facebook.
comment on: http://stackoverflow.com/q/48857762
score: 0

http://stackoverflow.com/comment/84972390
type: QuestionComment
has text: Thanks for the feedback! An issue has been posted on the issue tracker as requested.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48881224

http://stackoverflow.com/q/48806407
favorite count: 0
type: Question
answer count: 2
tagged with: django
tagged with: python
has body: I have a Post model: class Post(models.Model): headline = models.CharField(max_length=255) ... What I am, unsuccessfully, trying to achieve, is to get two random groups of 5 posts each, where the 2nd group records that the 1st group does NOT have. Now I know how to do this using Python, but I was wondering if there is a more elegant, ORM-like solution. I have tried the following: posts = Post.objects.all().order_by('?') first_group = posts[:5] second_group = posts[5:] But this will, sometimes, return the same posts in both groups. I have also tried to trick the system doing the following: posts = Post.objects.all().order_by('?') first_group = posts[:5] second_group = Post.objects.exclude(id__in=first_group) But again no luck. Can someone give me a few pointers so I don't have to loop over the records in pure Python?
has title: Django ORM - Get N random records, and then split them in 2 groups
upvote count: 2
tagged with: django-orm
accepted answer: http://stackoverflow.com/a/48806467
possible better answer: http://stackoverflow.com/a/48807231
score: 2
has answer: http://stackoverflow.com/a/48807231
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48806467

http://stackoverflow.com/comment/84918908
has text: Hello, I think the problem comes from the fact that you have more features than datas. As a result, the model is not able to create a proper mapping and tend to output the average of your datas. Did you try some dimensions reductions (PCA or TF-IDF if you are working on BoW) ?
comment on: http://stackoverflow.com/q/48955231
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48891298
linked to: http://stackoverflow.com/q/11037005
possible better answer: http://stackoverflow.com/a/48891584
has answer: http://stackoverflow.com/a/48891509
tagged with: arrays
has comment: http://stackoverflow.com/comment/84788022
score: 0
has body: So i'm trying to count the most repeated values in an text file. By using the Counter method it returns exaclty what im looking for file.txt 12334 99965 99965 44144 99965 00000 44144 script.py pArray=[] with open("file.txt") as my_file: for line in my_file: pArray.append((line.split('\n'))[0]) dictn = Counter(pArray) print(dictn) for key, value in dictn.items(): print("KEY",key) print("VALUE",value) print(dictn) OUTPUT Counter({'99965': 3, '44144': 2, '12334': 1, '00000': 1}) KEY 12334 VALUE 1 KEY 99965 VALUE 3 KEY 44144 VALUE 2 KEY 00000 VALUE 1 ['12334', '99965', '44144', '00000'] But as you can see the output of the final array is not in the same order as the dictionary (value should be in descending order) I am expecting an output like ['99965', '44144', '12334', '00000'] I also tried list(dictn.keys()) but i got the same output :/ Why is the order changing and how can I fix it?
favorite count: 0
tagged with: python-3.x
has title: Python dictionary counter positions change
has comment: http://stackoverflow.com/comment/84790692
has answer: http://stackoverflow.com/a/48891584
upvote count: 2
downvote count: 2
tagged with: python
tagged with: dictionary
tagged with: collections
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48891509
type: Question
answer count: 2

http://stackoverflow.com/q/48862205
tagged with: python
favorite count: 0
downvote count: 0
has body: I am getting this error: Unhandled exception in thread started by &lt;function check_errors.&lt;locals&gt;.wrapper at 0x7f78dfe090d0&gt; Traceback (most recent call last): File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/webapps/onehyr/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/autoreload.py", line 249, in raise_last_exception six.reraise(*_exception) File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/webapps/onehyr/lib/python3.6/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/webapps/onehyr/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/webapps/onehyr/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/webapps/onehyr/lib/python3.6/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/webapps/onehyr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "/webapps/onehyr/ladislist/blog/models.py", line 5, in &lt;module&gt; from django.shortcuts import reverse ImportError: cannot import name 'revers…
accepted answer: http://stackoverflow.com/a/48862230
tagged with: django
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48862230
score: 1
upvote count: 1
answer count: 1
has title: from django.shortcuts import reverse ImportError: cannot import name 'reverse'

http://stackoverflow.com/q/48852777
has body: How to execute below command in python script. echo "\n" | sosreport #command to generate report in linux os. Thanks for all your efforts. sorry if my question not understanding. I have achieved this by below code: from subprocess import Popen, PIPE p = Popen(['sosreport'], stdin=PIPE, shell=True) p.communicate(input='\n')
type: Question
has title: echo "\n" equivalent in python
upvote count: 0
score: -2
favorite count: 0
has comment: http://stackoverflow.com/comment/84709199
tagged with: python-2.7
tagged with: linux
answer count: 1
has comment: http://stackoverflow.com/comment/84709059
has answer: http://stackoverflow.com/a/48852862
type: UnansweredQuestion
downvote count: 2
tagged with: python

http://stackoverflow.com/comment/84896822
type: AnswerComment
type: Comment
has text: You are welcome. Please accept answer if it solved your problem. Thanks
comment on: http://stackoverflow.com/a/48945134
score: 0

http://stackoverflow.com/q/48962932
has answer: http://stackoverflow.com/a/48965737
tagged with: user-interface
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: pyqt5
upvote count: 1
downvote count: 1
type: Question
has body: It only shows e that error message when i run this script: import tkinter as tk import sys from PyQt5 import QtCore, QtWidgets from PyQt5.QtGui import QImage, QPalette, QBrush from PyQt5.QtWidgets import * from PyQt5.QtCore import QSize class MainWindow(QMainWindow): def __init__(self): QMainWindow.__init__(self) self.setMinimumSize(QSize(500, 500)) self.setWindowTitle("Chercher des Personnes") oImage = QImage("i.jpg") sImage = oImage.scaled(QSize(300,200)) # resize Image to widgets size palette = QPalette() palette.setBrush(10, QBrush(sImage)) # 10 = Windowrole self.setPalette(palette) self.nameLabel = QLabel(self) self.label = QLabel(self) self.Name = QLabel(self) self.Age = QLabel(self) self.Telnum = QLabel(self) self.Mail = QLabel(self) self.Adress = QLabel(self) self.nameLabel.setText('Prenom du personne:') self.Name.setText('Nom et Prenom: ') self.Age.setText('Age: ') self.Telnum.setText('Numero de Tel: ') self.Mail.setText('Email adress: ') self.Adress.setText('Adress: ') self.line = QLineEdit(self) self.line.move(150, 50) self.line.resize(200, 32) self.nameLabel.move(150, 20) self.Name.move(20, 150) self.Age.move(20, 180) self.Telnum.move(20, 210) self.Mail.move(20, 240) self.Adress.move(20, 270) pybutton = QPushButton('OK', self) pybutton.clicked.connect(self.clickMethod) pybutton.resize(200, 32) pybutton.move(150, 85) def clickMethod(self): class people: def __init__(self, full_name, birthday, telnum, mail, adress, other): self.name = full_name self.full_name = full_name self.birthday = birthday #ddmmyyyy self.telnum = telnum self.mail = mail self.adress = adress self.other = other #Peoples info john = people("Full name: John Doe", "Birthday: ??/01/2005 Age: 12", "Telephone number: +41 12 345 67 89", "Educanet2: fake@example", "Adress: 123 Fake Street, 1721 Suisse", "Other: John is a known programmer and plays ice hockey. He participates in robotics competitions. But he's bullied and made fun of at times") self.Name.setText(str(locals()[self.line.text().lo…
has title: Python stopped working error message while using this script?
score: 0
tagged with: pyqt

http://stackoverflow.com/q/48807559
has comment: http://stackoverflow.com/comment/84624243
score: 1
has comment: http://stackoverflow.com/comment/84623876
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48811140
tagged with: python
upvote count: 1
tagged with: gurobi
has body: I am writing an optimization modell in python that I will solve with Gurobi. However I have got one problem with one constraint. I want to multiply my decision variable with the index of j: x[i,j] * j , with j as the index of j used in x[i,j]. i and j are both are modeled as lists. The decisionvariable x[i,j] is binary. I tried with for i in I: m.addConstr (x[i,j]*J.index(j)) But this will always take the last element of the list j. How can I make the constraint to take in the index of j used in x[i,j]?
type: UnansweredQuestion
has title: Multiply decision variable with index used in it
has comment: http://stackoverflow.com/comment/84621400
downvote count: 0
answer count: 1

http://stackoverflow.com/comment/84804086
type: Comment
type: QuestionComment
has text: I have updated your question with my best understanding of what you are trying to ask, and retracted my close vote. This might still not be clear enough, or exactly what you want; please review and if necessary [edit] some more.
comment on: http://stackoverflow.com/q/48899062
score: 0

http://stackoverflow.com/comment/84645111
comment on: http://stackoverflow.com/q/48820691
type: Comment
type: QuestionComment
has text: Yes, df is a slice taken out of the original df. Just tell pandas you are aware of what you are doing by `df = df[my_selection].copy()`
score: 1

http://stackoverflow.com/q/48875596
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48875701
accepted answer: http://stackoverflow.com/a/48875680
upvote count: 1
type: Question
has title: Python: run python script as subprocess and get the output
has answer: http://stackoverflow.com/a/48875680
score: 1
has body: I have a python script calculate.py with a function in it like below def mytest(): Y_pred = {} Y_pred['a'] = [1,2,3] Y_pred['b'] = [45,54,77] return Y_pred Now from python console I want to run the python script using subprocess and get the return value `Y_pred' into a variable. So I want something like the pseudocode below from the terminal python3 &gt;&gt;&gt; import subprocess &gt;&gt;&gt; returned_val = subprocess.call([run calculate.py here and call mytest() ]) In the end, I want the returned value of mytest() to a variable returned_val.
answer count: 2
possible better answer: http://stackoverflow.com/a/48875701
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/a/48896065
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48895952
type: Answer
upvote count: 3
has body: Here is a workflow: # Setting initial datetime In [116]: dt = datetime.datetime(2018, 2, 20, 14, 25, 43, 215000) In [117]: dt.microsecond Out[117]: 215000 # Setting new microsecond value # You can add you logic here e.g. if you want to # convert to seconds and then check In [118]: new_ms = 200000 if dt.microsecond &lt; 250000 else 300000 # Replacing the old with the new value In [119]: new_dt = dt.replace(microsecond=new_ms) In [120]: new_dt Out[120]: datetime.datetime(2018, 2, 20, 14, 25, 43, 200000) Hope this will get you started.
score: 3
answers question: http://stackoverflow.com/q/48895952

http://stackoverflow.com/a/48930292
has comment: http://stackoverflow.com/comment/84869018
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48929752
downvote count: 0
type: Answer
has body: pylint warns you that you have a function with two parameters you are not using inside the function, which is true and is a smell for common errors. It also warns about using a local function name that is equal to an outer scope name, which can sometimes lead to errors, because you might be inadvertently hiding the outer name. Sometimes you do it on purpose, so pylint just annoys a bit, but you can also rename the local, as you did and get rid of the danger. Those are just warnings not errors. Usually it is good to be warned about possible problems, even if they don't exist. The static checker does not know how will your handler be called by the signals library. But the warning hasn't to do with that. The static tool just noticed you claim to receive two parameters but you are not using them in the handler body. Usually when you receive a parameter you want to use it right? Except that as you are registering a handler in a library for callback, you have to respect the library "protocol", or you'll get a runtime error when the callback is done from there. The static tool does not know you don't care about the signals received info, and are just printing something else; It is just saying to you: that looks strange, are you sure?

http://stackoverflow.com/comment/84658072
type: QuestionComment
type: Comment
has text: The best thing you can do is to read a regex tutorial, something basic should suffice.
score: 1
comment on: http://stackoverflow.com/q/48827207

http://stackoverflow.com/q/48841782
accepted answer: http://stackoverflow.com/a/48843454
has answer: http://stackoverflow.com/a/63925865
tagged with: django-queryset
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/48841832
has answer: http://stackoverflow.com/a/48841832
tagged with: python
answer count: 4
score: 2
type: AnsweredQuestion
upvote count: 2
has answer: http://stackoverflow.com/a/48843454
tagged with: django
has title: Django append <queryset> for searching each words in a sentece using filter
type: Question
has body: I want to search each word in a sentence and put that in result['post'] dictionary and of course this code only looks for last query queries = querystring.split() for query in queries: results['posts'] = Post.objects.filter(text__icontains=query) i tried append,extend and a lot of things but it didn't work as expected. Edit Update: I also tried count = {} results = {} post_results = [] queries = querystring.split() for query in queries: post_results.append(Post.objects.filter(text__icontains=query)) results['posts'] = post_results count['posts'] = results['posts'].count() But this leads to another error count() takes exactly one argument (0 given) Error Image Also Post.objects.filter(text__icontains=query) this line returns a queryset value and Queryset type of django doesn't seem to have append. Is there it's own append like feature ? If so then that wouldn't change it's queryset type to list. Using temp variable like post_results = [] changes to list. Can we change that list back to queryset? If we can then that would work.
has answer: http://stackoverflow.com/a/48842653

http://stackoverflow.com/a/48815998
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48815924
has body: You can't change the value inside of a tuple, but what you can do is making it a list and making it a tuple after. Something like this: tupl = ("a", "b", "c") tupl = list(tupl) # will change it to a list: ["a", "b", "c"] tupl.append("d") # appends "d" to the list tupl = tuple(tupl) # changes it back to a tuple ("a", "b", "c", "d")

http://stackoverflow.com/comment/84801266
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48897561
score: 2
has text: @PatrickHaugh that's never sufficient to answer a question like this. You don't want to know if they *can* be the same, you want to know if they're *guaranteed* to be the same.

http://stackoverflow.com/q/48875501
score: 3
accepted answer: http://stackoverflow.com/a/48875869
has comment: http://stackoverflow.com/comment/84755849
has answer: http://stackoverflow.com/a/48892486
has comment: http://stackoverflow.com/comment/84755073
tagged with: search
has comment: http://stackoverflow.com/comment/84755788
answer count: 3
tagged with: lemmatization
has answer: http://stackoverflow.com/a/48875869
tagged with: pandas
has comment: http://stackoverflow.com/comment/84755168
downvote count: 0
has comment: http://stackoverflow.com/comment/84755120
favorite count: 0
has comment: http://stackoverflow.com/comment/84755272
has body: I have a text file containing words and their lemma - every line contains word form in the first column and word lemma in the second column. I have a list of tweets (sentences) which I need to convert to word lemmas - each word needs to be converted to their lemma (the second column from a text file) I tried opening and closing text file for each word but that takes too long (about 15 sec for every word to find their lemma in the text file). The function is below. def returnLemma(str): str= word_tokenize(str) end_str = "" for word in str: infile = open('MorphDict.txt', 'r') for line in infile: line.strip() prva=line.split()[0] druga=line.split()[1] if word==prva: end_str = end_str+" "+druga break; infile.close() return end_str Is it possible to search this text file (>100MB) more efficiently? Is it possible to use pandas package for this to solve it?
possible better answer: http://stackoverflow.com/a/48892486
has comment: http://stackoverflow.com/comment/84755345
has comment: http://stackoverflow.com/comment/84755680
tagged with: python
upvote count: 3
has title: How to search if large text file contains words from sentence using python?
has comment: http://stackoverflow.com/comment/84755810
has answer: http://stackoverflow.com/a/48875561
has comment: http://stackoverflow.com/comment/84756035
type: Question
has comment: http://stackoverflow.com/comment/84755069
type: AnsweredQuestion

http://stackoverflow.com/comment/84707951
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48852240
has text: It's not clear how you want to "sort". In the correct answer you gave no elements have changed order. You just removed some elements from `list1`.
score: 0

http://stackoverflow.com/a/64464658
downvote count: 0
answers question: http://stackoverflow.com/q/48937652
score: 3
has body: As far as I understand the implementation, tf.io.gfile.GFile is always using UTF-8: https://github.com/tensorflow/tensorflow/blob/b3376f73ccfd6ae8721a946daf064675ee19b427/tensorflow/python/lib/io/file_io.py#L100 def write(self, file_content): """Writes file_content to the file. Appends to the end of the file.""" self._prewrite_check() self._writable_file.append(compat.as_bytes(file_content)) It is converting str to bytes using tf.compat.as_bytes which encode to UTF-8:
upvote count: 3
type: Answer

http://stackoverflow.com/q/48931889
tagged with: environment
tagged with: anaconda
has title: conda, "Solving environment: failed" error on Linux CentOS 7
score: 1
has body: I installed Conda through Miniconda on my laptop running Linux CentOS 7. If I run the command conda update conda, I get the following error: conda update conda Solving environment: failed NotWritableError: The current user does not have write permissions to a required path. path: /path/to/custom/dir/pkgs/urls.txt uid: 1000 gid: 1000 If you feel that permissions on this path are set incorrectly, you can manually change them by executing $ sudo chown 1000:1000 /path/to/custom/dir/pkgs/urls.txt In general, it's not advisable to use 'sudo conda'. I've no idea on how to solve this issue; I also asked on the Bioconda GitHub page but nobody replied. Any suggestion on how to solve this problem? Thanks
tagged with: conda
type: Question
has comment: http://stackoverflow.com/comment/84871231
has answer: http://stackoverflow.com/a/55303451
has comment: http://stackoverflow.com/comment/84871464
downvote count: 0
answer count: 1
tagged with: python
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: miniconda

http://stackoverflow.com/q/48854765
has answer: http://stackoverflow.com/a/49142285
duplicate of: http://stackoverflow.com/q/19006960
tagged with: python
tagged with: string.format
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49142285
linked to: http://stackoverflow.com/q/19006960
type: Question
has title: python3: variable length values inside {} for print & .format()
possible better answer: http://stackoverflow.com/a/48854866
has body: Is there a way to create a formatted string in python with flexible {} adjustments? The default way is: In [1]: "{:20}Hey B! You are {} blocks away.".format("Hey A!", 20-6) Out[1]: 'Hey A! Hey B! You are 14 blocks away.' But is there a way to code the "distance between A and B" flexible? Like this..? #not working In [2]: x = 20 In [3]: "{:x}Hey! You are {} blocks away.".format("Hey! A", x-6) Out[3]: 'Hey A! Hey B! You are 14 blocks away.' In [2]: x = 30 In [3]: "{:x}Hey! You are {} blocks away.".format("Hey! A", x-6) Out[3]: 'Hey A! Hey B! You are 14 blocks away.' Or is there any other way simple and convenient way to accomplish it?
has answer: http://stackoverflow.com/a/48854866
score: 0
answer count: 2
tagged with: printing
tagged with: python-3.x

http://stackoverflow.com/q/48901075
upvote count: 5
has title: Python3 Pytracking Pixel data collection not showing
tagged with: email
downvote count: 0
has body: I'm writing a little script to send emails and I would like to track who opened the email with the python module pytracking like so: import smtplib import pytracking from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText fromaddr = "info@XXXXXXXXXX.com" toaddr = "XXXXXXXXa@gmail.com" msg = MIMEMultipart() #Not sure if this is the right location for the pixel pixel= (pixel_byte_string, mime_type) = pytracking.get_open_tracking_pixel() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "grande" body = "bla bla bla" msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('mail.XXXXXXXX.com', 587) server.ehlo() server.starttls() server.ehlo() server.login('info@XXXXXXXX.com','XXXXXXXX') text = msg.as_string() server.sendmail(fromaddr, toaddr, text) print('DONE') I read the full documentation of this module here , but I can not find from where to actually check if the pixel has been opend or which command shell I run to do so. Can anyone advise how to check if the pixel has been opened? Thanks
tagged with: smtp
favorite count: 0
score: 5
tagged with: python
tagged with: event-tracking
answer count: 0
tagged with: pixel
has comment: http://stackoverflow.com/comment/118957428
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/131170999
type: Question

http://stackoverflow.com/q/48919353
has comment: http://stackoverflow.com/comment/84845022
type: Question
answer count: 2
has body: I've been trying to make a circle area calculator, and I've got the basics. But if the user enters something like 5m, then I see an error. Instead of exiting with an error, I want to return "Enter a Number". Here is my code. from math import pi r = float(input("Input the radius of the circle : ")) print("The area of the circle with radius " + str(r) + " is: " + str(pi * r**2)) if r==(str): print("Enter a Number")
favorite count: 0
score: 0
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/48919420
has answer: http://stackoverflow.com/a/48919420
linked to: http://stackoverflow.com/q/17453626
has title: Python If/else statements with math
tagged with: python
type: AnsweredQuestion
tagged with: if-statement
has comment: http://stackoverflow.com/comment/84844961
has comment: http://stackoverflow.com/comment/84845182
has answer: http://stackoverflow.com/a/48919441
accepted answer: http://stackoverflow.com/a/48919441

http://stackoverflow.com/a/48959912
has comment: http://stackoverflow.com/comment/132121632
score: 9
downvote count: 2
accepted answer of: http://stackoverflow.com/q/48959833
answers question: http://stackoverflow.com/q/48959833
has comment: http://stackoverflow.com/comment/138238522
type: AcceptedAnswer
has body: This is documented here: str.rsplit() sentence = 'b a hello b Hi' sentence.rsplit('b', 1)
type: Answer
upvote count: 11

http://stackoverflow.com/a/66908053
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48812442
has body: For anyone who finds their way to this question in search of an on_load event in kivy, I have found a solution. The App class in kivy provides a member function on_start(self), which is called once the app is done building and loading. We simply need to add the functions we want to call after the app is done loading in its body. Ex: class MyApp(App): def build(self): ... def on_start(self): super().on_start(self) my_f() update_texts()
downvote count: 0

http://stackoverflow.com/comment/84873020
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48933025
has text: I thought I can simplify the question but I was wrong. I have updated the question and the expected output should be the same. Thx
score: 0

countvectorizer
type: Tag
tags question: http://stackoverflow.com/q/48962346
tag name: countvectorizer

http://stackoverflow.com/comment/84847015
type: QuestionComment
comment on: http://stackoverflow.com/q/48919331
has text: @PeterPhan I understand. I was simply curious if your use case had some useful constraints which would allow you to split on ".", for example. If it is as you describe than use nltk tokenization as in the answers below.
score: 0
type: Comment

http://stackoverflow.com/a/48941706
has body: When using super, self is passed automatically. Also, in Python3.3 and above, super does not even need to receive arguments to know from which class it is being called. You can simply do this. super().__init__(n) This greatly improves maintainability, so it would be the prefered approach.
type: Answer
upvote count: 4
downvote count: 0
score: 4
answers question: http://stackoverflow.com/q/48941173

http://stackoverflow.com/q/48879403
favorite count: 0
type: UnansweredQuestion
tagged with: apache-beam
upvote count: 1
tagged with: python
has title: Writing JSON data into BigQuery table as just one field of type string
score: 1
tagged with: google-bigquery
type: Question
has body: My input data looks like this: [someGarbagevalue]{"Id": 1, "Address": {"Street":"MG Road","City":"Pune"}} [someGarbagevalue]{"Id": 2, "Address": {"City":"Mumbai"}} [someGarbagevalue]{"Id": 3, "Address": {"Street":"XYZ Road"}} [someGarbagevalue]{"Id": 4} [someGarbagevalue]{"Id": 5, "PhoneNumber": 12345678, "Address": {"Street":"ABCD Road", "City":"Bangalore"}} I am striping the [someGarbagevalue] after reading the data as and then trying to write to BigQuery: class processFunction(beam.DoFn): def process(self, element): global line line = element[element.find(']') + 1:].strip() return [line] def run(argv=None): pipeline_options = PipelineOptions() p = beam.Pipeline(options=pipeline_options) first = p | 'read' &gt;&gt; ReadFromText(wordcount_options.input) second = (first | 'process' &gt;&gt; (beam.ParDo(processFunction())) | 'write' &gt;&gt; beam.io.WriteToBigQuery( 'myBucket:tableFolder.test_table') Question: How can I write the data to BigQuery as each line of type STRING. How would I query the BigQuery Table if I write the data to BigQuery as each line? Current error: Error while reading data, error message: JSON table encountered too many errors, giving up. Rows: 1; errors: 1. Error while reading data, error message: JSON parsing error in row starting at position 0: Value encountered without start of object.
tagged with: google-cloud-dataflow
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48879863

http://stackoverflow.com/comment/84810804
type: Comment
type: QuestionComment
has text: Is in one of the comments above: Training and test sizes: Samples Columns 1665 2134 555 2134
score: 0
comment on: http://stackoverflow.com/q/48901427

http://stackoverflow.com/comment/84632446
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48814315
type: Comment
has text: No need for regex sure but for extracting text from strings there is really no need not to use regex. It's easy to understand and adapt to new situations.

http://stackoverflow.com/a/49020828
score: 0
type: AcceptedAnswer
has body: The problem was submitting a POST request with pagination. if the current link is /survey/1/question?page=2 the form will submit to /submit/1/question?page=3. To remedy this, I just created a separate route for submission and handled logic there.
has comment: http://stackoverflow.com/comment/89965355
type: Answer
accepted answer of: http://stackoverflow.com/q/48936843
answers question: http://stackoverflow.com/q/48936843

http://stackoverflow.com/a/48952987
accepted answer of: http://stackoverflow.com/q/48952920
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84916792
has comment: http://stackoverflow.com/comment/84917713
has body: There is the easy (recommended) way, and the complex way. Easy: Just import pdb and experiment with functionality in your browser session. Once you've got everything working as desired, update your code and remove the pdb line. def fill_search(): import pdb; pdb.set_trace() # Experiment in the browser session for element in elements: element = driver.find_element_by_tag('input') if 'what are you looking for' in element.get_attribute('innerHTML'): search_box = element search_box.get_attribute('value') == 'happiness' Complex: driver = webdriver.Firefox() session_id = driver.session_id executor_url = driver.command_executor._url same_session_driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={}) same_session_driver.session_id = session_id same_session_driver.continue_doing_stuff
upvote count: 2
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48952920

http://stackoverflow.com/comment/84825537
has text: Thanks!! I can import it now!
comment on: http://stackoverflow.com/a/48909247
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48834691
accepted answer of: http://stackoverflow.com/q/48834565
upvote count: 2
has body: As mentioned by @chepner, you should be measuring the lengths of the innermost lists - not of the second-level list: for instance in freq_itemsets: freq_itemset_lengths.append(len(instance[0])) Alternatively, for instance, _ in freq_itemsets: freq_itemset_lengths.append(len(instance)) or, freq_itemset_lengths = [len(instance) for instance, _ in freq_itemsets]
answers question: http://stackoverflow.com/q/48834565
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 2

http://stackoverflow.com/q/48959662
has answer: http://stackoverflow.com/a/48959769
has body: For series pd.Series(['d', 'b', 'a', 'b', 'c', 'a', 'd']), how to sort it so that: a is the last item of the series all other items are ascending So desired outcome will be: pd.Series(['b', 'b', 'c', 'd', 'd', 'a', 'a']) Thanks
tagged with: sorting
has comment: http://stackoverflow.com/comment/84925968
has comment: http://stackoverflow.com/comment/84926105
has comment: http://stackoverflow.com/comment/84925946
linked to: http://stackoverflow.com/q/39525928
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84926049
tagged with: pandas
has comment: http://stackoverflow.com/comment/84926006
accepted answer: http://stackoverflow.com/a/48959769
has title: Pythonic way to put specified value at last position when sorting
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84925951
has answer: http://stackoverflow.com/a/48959757
has comment: http://stackoverflow.com/comment/84925983
type: Question
possible better answer: http://stackoverflow.com/a/48959757

http://stackoverflow.com/q/48937242
tagged with: django
tagged with: python
has body: How to get fields from child model in views.py? For example, I've parent model BasicOrder and child model (who extends BasicOrder) TouristVisa. I'm using Django 2.0.2 and Python 3.6.1. My models.py is: class BasicOrder(models.Model): user = models.ForeignKey(User, verbose_name=_('User'), on_delete=models.CASCADE) status = models.PositiveIntegerField(_('Status'), choices=ORDER_STATUS, default=0) def __str__(self): return 'Order #{}'.format(self.id) class TouristVisa(BasicOrder, models.Model): citizenship = models.ForeignKey( Citizenship, verbose_name=_('Citizenship'), on_delete=models.PROTECT ) invitation_entry = models.PositiveSmallIntegerField( _('Invitation entry'), choices=INVITATION_ENTRY ) class Meta: ordering = ['id'] Would be great to have access to field invitation_entry from child model (TouristVisa). I try this way in views.py: order = BasicOrder.objects.get(user=request.user.id) print(order.invitation_entry) But it's show error: AttributeError: 'BasicOrder' object has no attribute 'invitation_entry'
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84884103
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48938462
score: -1
accepted answer: http://stackoverflow.com/a/48938462
upvote count: 0
has title: Django. How to get fields from child model in views.py?
answer count: 1
favorite count: 0

literals
tags question: http://stackoverflow.com/q/48932685
type: Tag
tags question: http://stackoverflow.com/q/48896544
tag name: literals

http://stackoverflow.com/q/48882768
favorite count: 0
tagged with: python-3.x
upvote count: 2
has answer: http://stackoverflow.com/a/48883111
accepted answer: http://stackoverflow.com/a/48883111
tagged with: django
tagged with: python
has title: Django reading pdf files content
score: 2
type: AnsweredQuestion
tagged with: pdfminer
duplicate of: http://stackoverflow.com/q/26494211
has body: I'm trying to find a plugin that reads text from PDF files. I found an old post about this issue and the answer was to use the following plugin : pdfminer pluggin However, this does not support python 3. Any suggestions ?
type: Question
linked to: http://stackoverflow.com/q/26494211
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84769964
tagged with: http://stackoverflow.com/tag/pdf

google-oauth
tags question: http://stackoverflow.com/q/48911419
type: Tag
tags question: http://stackoverflow.com/q/48807108
tags question: http://stackoverflow.com/q/48885836
tag name: google-oauth

http://stackoverflow.com/q/48956602
type: UnansweredQuestion
has body: I'm trying to implement a decision tree algorithm in Python to predict missing input data. Say I have a column with 99 entries. Out of this 99 entries, 20 are NaN. I want to break up this single array into x numbers of size y (y = 5 in this case) sub-arrays. The sub-arrays with complete cells are assigned to features and the ones that contain NaN are assigned to target. # breaking target array into subarrays subarray_size = 5 target = [] features = [] # complete break up and assign to array "chunks" chunks = [test[x : x + subarray_size] for x in xrange(0, len(test), subarray_size)] # assigns NaN containg subarray to "target" and filled subarrays to "features" for i in chunks: if (np.where(np.isnan(i)))[0].shape[0]: target.append(i) else: features.append(i) Code works all the way till the end of for loop. Now that I have features and target, I tried the below code block from sklearn.cross_validation import train_test_split as tts X_train, X_test, y_train, y_test = tts(features, target, test_size=0.2) which yielded this error: 202 if len(uniques) &gt; 1: 203 raise ValueError("Found input variables with inconsistent numbers of" --&gt; 204 " samples: %r" % [int(l) for l in lengths]) 205 206 ValueError: Found input variables with inconsistent numbers of samples: [5, 15]. I think the error occurred somewhere during the array operations. I'm having trouble fixing it. Any advice/insights/suggestions? EDIT: below is the sample "test" column. Not sure how to put it in table format. Sorry about the bad visuals. Site2_ThirdIonizationEnergy 39.722 39.722 33.667 39.722 39.722 23.32 25.04 NaN 27.491 22.99 39.722 23.32 25.04 NaN 27.491 22.99 33.667 23.32 33.667 NaN 27.491 22.99 39.722 23.32 25.04 NaN 27.491 22.99 19.174 19.174 19.174 19.174 39.722 39.722 33.667 39.722 39.722 23.32 25.04 NaN 27.491 22.99 39.722 23.32 25.04 NaN 27.491 22.99 33.667 23.32 33.667 NaN 27.491 22.99 39.722 23.32 25.04 NaN 27.491 22.99 39.722 39.722 33.667 39.722 39.722 39.722 33.667 39.722 39.722 23.32 25.…
has title: Splitting a Single Column to Multiple sub-columns/arrays in Python
tagged with: python
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84920208
has answer: http://stackoverflow.com/a/49135267
type: Question
tagged with: cross-validation
tagged with: decision-tree
tagged with: train-test-split
upvote count: 1
tagged with: supervised-learning
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84920504

http://stackoverflow.com/a/48854078
has body: You can create DataFrame by constructor, reshape by stack and last join to original: df1 = (pd.DataFrame(df.c.values.tolist()) .stack() .reset_index(level=1) .rename(columns={0:'val','level_1':'key'})) print (df1) key val 0 c00 v00 0 c01 v01 1 c10 v10 2 c20 v20 2 c21 v21 2 c22 v22 df = df.drop('c', 1).join(df1).reset_index(drop=True) print (df) a b key val 0 a0 b0 c00 v00 1 a0 b0 c01 v01 2 a1 b1 c10 v10 3 a2 b2 c20 v20 4 a2 b2 c21 v21 5 a2 b2 c22 v22
downvote count: 0
score: 3
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48853989
answers question: http://stackoverflow.com/q/48853989
upvote count: 3
type: Answer

http://stackoverflow.com/a/48920578
type: AcceptedAnswer
type: Answer
has body: Example JSON response: https://bpaste.net/show/fcb53d9bc16f &gt;&gt;&gt; import requests ... ... BASE_URL = 'https://www.healthgrades.com/api3/usearch' ... ... params = { ... 'userLocalTime':'22:37', ... 'what':'Dentistry', ... 'where':'Canal Street, NY 10013', ... 'pt':'40.720901, -74.008904', ... 'sort.provider':'bestmatch', ... 'category':'provider', ... 'sessionId':'Sb93293f932c6bc56', ... 'requestId':'Rac7ffe6e6256eba3', ... 'pageSize.provider':'20', ... 'pageNum':'2', ... 'isFirstRequest':'true', ... 'debug':'false', ... 'isAtlas':'true', ... 'action':'refresh', ... 'neCorner':'40.744526282819244,-73.99060337556104', ... 'swCorner':'40.69723118200452,-74.02724113269275' ... } ... r = requests.get(BASE_URL, params=params) ... r.raise_for_status() &gt;&gt;&gt; dentists = r.json()['search']['searchResults']['provider']['results'] &gt;&gt;&gt; for dentist in dentists: ... print(dentist['displayName']) ... Dr. Raphael Santore, DDS Dr. Gain Lu, DDS Dr. Molly Lim, DDS Dr. Anne Yu, DDS Dr. Charmaine Ip, DMD Dr. Devi Konar, DDS Dr. Christopher Perez, DMD Dr. Lee Gold, DDS Dr. Elaine Wong, DDS Dr. Fan Mou, DDS Dr. Henry Wong, DDS Dr. Shauna Fung, DDS Dr. Emilie Fong, DDS Dr. Nancy Ma, DDS Dr. Charles Tiu, DDS Dr. Glenn Chiarello, DDS Dr. John Nosti, DMD Dr. Loi Chan, DDS Dr. Charles Hashim, DDS Dr. David Azar, DDS Dr. Jenny Zhu, DDS Dr. Stanton Young, DMD Dr. Pankaj Singh, DDS Dr. Lawrence Tam, DDS Dr. Alina Lukashevsky, DDS Dr. Maureen Khoo, DDS Dr. Mailin Lai, DDS Dr. Stewart Neidle, DDS Danielle Danzi, DDM Dr. Justin Cohen, DMD Dr. Weihsin Men, DMD Dr. Anthony Kail, DDS Sima Epstein Dr. Christian Bilius, DDS Dr. Jeffrey Shapiro, DDS Dr. Donald Ingerman, DDS &gt;&gt;&gt; featured_dentists = r.json()['featuredProviders'] &gt;&gt;&gt; for dentist in featured_dentists: ... print(dentist['displayName']) ... Dr. Ora Canter, DDS Dr. Alfred Shirzadnia, DDS Dr. Henry Nogid, DDS
accepted answer of: http://stackoverflow.com/q/48919871
answers question: http://stackoverflow.com/q/48919871
score: 0

http://stackoverflow.com/comment/84645547
type: Comment
has text: You will have to post some more details on the rest of your code. Which library are you using for the `fetch()` function?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48820924

http://stackoverflow.com/a/48821287
answers question: http://stackoverflow.com/q/48821178
type: Answer
has comment: http://stackoverflow.com/comment/84646175
has comment: http://stackoverflow.com/comment/84646504
has comment: http://stackoverflow.com/comment/84646423
has comment: http://stackoverflow.com/comment/84646047
upvote count: 3
score: 3
has comment: http://stackoverflow.com/comment/84646308
has body: Python exceptions are classes, and classes are executed at the time of definition. For example consider this code: import sys class test: print("hey") sys.exit() In this test is never instantiated but the print statement will be called. I suspect this is a surprise for you, but it is the cause of the behavior you see. If you want to have your exceptions quit the program have that behavior in the except block, not in the exception itself. How this would work with your current exception hierarchy would be something like this: import sys class DontThrow(Exception): pass class MyException(Exception): pass def main(): x = 5 try: if x &lt; 6: raise MyException except DontThrow: print("You shouldn't see this") sys.exit(1) except MyException: print("Bad exception") sys.exit(1) else: print("no exception was thrown") finally: print("This always gets called") if __name__ == "__main__": main() Note that an uncaught exception will exit the program anyway, so if something isn't caught there's no need to try to call sys.exit() directly
has comment: http://stackoverflow.com/comment/84646453
has comment: http://stackoverflow.com/comment/84645993
has comment: http://stackoverflow.com/comment/84646092
downvote count: 0
has comment: http://stackoverflow.com/comment/84646333
has comment: http://stackoverflow.com/comment/84646973
has comment: http://stackoverflow.com/comment/84646936

http://stackoverflow.com/q/48959698
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48959780
has comment: http://stackoverflow.com/comment/84926083
answer count: 1
tagged with: python
has body: In code listed in logistic regression code, I saw the following code snippet. What throws me off is the expression: probs[range(num_examples),y]. Can someone tell me what dimension this matrix has? My guess is that it's a N*K by N*K matrix, but I am not sure. Thanks. import numpy as np import matplotlib.pyplot as plt np.random.seed(0) N = 100 # number of points per class D = 2 # dimensionality K = 3 # number of classes X = np.zeros((N*K,D)) y = np.zeros(N*K, dtype='uint8') for j in xrange(K): ix = range(N*j,N*(j+1)) r = np.linspace(0.0,1,N) # radius t = np.linspace(j*4,(j+1)*4,N) + np.random.randn(N)*0.2 # theta X[ix] = np.c_[r*np.sin(t), r*np.cos(t)] y[ix] = j #Train a Linear Classifier # initialize parameters randomly W = 0.01 * np.random.randn(D,K) b = np.zeros((1,K)) # some hyperparameters step_size = 1e-0 reg = 1e-3 # regularization strength # gradient descent loop num_examples = X.shape[0] for i in xrange(200): # evaluate class scores, [N x K] scores = np.dot(X, W) + b # compute the class probabilities exp_scores = np.exp(scores) probs = exp_scores / np.sum(exp_scores, axis=1, keepdims=True) # [N x K] # compute the loss: average cross-entropy loss and regularization corect_logprobs = -np.log(probs[range(num_examples),y]) data_loss = np.sum(corect_logprobs)/num_examples reg_loss = 0.5*reg*np.sum(W*W) loss = data_loss + reg_loss if i % 10 == 0:
type: AnsweredQuestion
has title: Understanding matrix obtained from indexing with arrays
has answer: http://stackoverflow.com/a/48959780
score: 0

http://stackoverflow.com/comment/84904800
type: QuestionComment
comment on: http://stackoverflow.com/q/48949166
has text: one vector per document. so say i have 10 people i want to look at on a given day and they have a collective 20,000 documents. i need 20,000 vectors which will then be fed into TensorBoard and filtered on the front-end, so i am only looking at the vectors for a particular person.
score: 0
type: Comment

http://stackoverflow.com/q/48929950
has body: I am trying to update a label field dynamically from the contents of a TextInput in a ModalView. The idea is that in the TextInput one enters plain text including markup formatting and you will see the results directly in the Label field with markup = True. Unfortunately I do not know how to access the Label item in the ModalView. Who can help? See the example code below. Thanks in advance. from kivy.app import App from kivy.lang import Builder from kivy.uix.modalview import ModalView from kivy.uix.boxlayout import BoxLayout from kivy.uix.textinput import TextInput from kivy.uix.label import Label from kivy.uix.button import Button from kivy.properties import ObjectProperty, StringProperty kv = """ &lt;Test&gt;: canvas: Color: rgba: 0.4, 0.5, 0.6, 1 Rectangle: size: self.size pos: self.pos Button: size_hint: None, None size: 3 * dp(48), dp(48) text: 'Edit' on_press: root.showedit() """ Builder.load_string(kv) class Test(BoxLayout): minput_text = StringProperty('Welcome') txtresult = ObjectProperty() def showedit(self): mview = ModalView(id='mviewid', size_hint=(0.4, 0.6), auto_dismiss=False, background='./images/noimage.png') mblt = BoxLayout(orientation='vertical', padding=(24)) minp = TextInput(id='inptxt', text='', hint_text='Start typing text with markup here', size_hint=(1,0.5),multiline=True) minp.bind(text=self.on_inptext) mtxt = Label(id='txtresult',text='displays formatted text', color=(0.3,0.3,0.3), size_hint=(1,0.5),markup=True) mcnf = Button(text='OK', size=(144,48), size_hint=(None,None)) mcnf.bind(on_press=mview.dismiss) mblt.add_widget(minp) mblt.add_widget(mtxt) mblt.add_widget(mcnf) mview.add_widget(mblt) mview.bind(on_dismiss=self.print_text) mview.open() def on_inptext(self, instance, value): self.minput_text = value def print_text(self, *args): print self.minput_text class TestApp(App): def build(self): return Test() if __name__ == '__main__': TestApp().run()
has title: How to dynamically update markup text in kivy modalview
tagged with: python
tagged with: kivy
tagged with: modal-view
accepted answer: http://stackoverflow.com/a/48930551
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48930551
type: Question
tagged with: python-2.7
score: 0
answer count: 1

http://stackoverflow.com/a/48867890
type: Answer
has comment: http://stackoverflow.com/comment/84781826
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48867625
answers question: http://stackoverflow.com/q/48867625
type: AcceptedAnswer
has body: google API calendarList resource representation You could just print out the entry itself, instead of a single key. page_token = None while True: calendar_list = service.calendarList().list(pageToken=page_token).execute() for calendar_list_entry in calendar_list['items']: print calendar_list_entry page_token = calendar_list.get('nextPageToken') if not page_token: break Or directly get the id: print calendar_list_entry["id"]
downvote count: 0
score: 1

http://stackoverflow.com/a/48816304
has comment: http://stackoverflow.com/comment/84638646
has comment: http://stackoverflow.com/comment/84638043
has comment: http://stackoverflow.com/comment/84639785
has comment: http://stackoverflow.com/comment/84639356
has comment: http://stackoverflow.com/comment/84637375
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84639142
has comment: http://stackoverflow.com/comment/84637813
downvote count: 0
score: 4
has comment: http://stackoverflow.com/comment/84639206
has comment: http://stackoverflow.com/comment/84637290
has comment: http://stackoverflow.com/comment/84638954
has body: You don't need to know any framework to automate any page. You need to just access the DOM and you can do that with selenium and python. But sometimes some simple Vanilla JavaScript helps. To get those links you can try and paste this in console: images_links =[]; images = document.querySelectorAll("img"); for (image of images){images_links.push(image.src)} console.log(images_links) Also the selenium with python and the above JS snippet is: import selenium from selenium import webdriver from time import sleep driver = webdriver.Chrome() driver.get("https://imgur.com/a/JNzjB") for i in range(0,7): # here you will need to tune to see exactly how many scrolls you need driver.execute_script('window.scrollBy(0, 2000)') sleep(2) list_of_images_links=driver.execute_script('images_links =[]; images = document.querySelectorAll("img"); for (image of images){images_links.push(image.src)} return images_links;') list_of_images_links Update: you don't need selenium just paste this in an Opera console (see that you enable multiple Downloads) and voila: document.body.style.zoom=0.1; images=document.querySelectorAll("img"); for (i of images) { var a = document.createElement('a'); a.href = i.src; console.log(i); a.download = i.src; document.body.appendChild(a); a.click(); document.body.removeChild(a); } same thing beautified for reading: document.body.style.zoom=0.1; images = document.querySelectorAll("img"); for (i of images) { var a = document.createElement('a'); a.href = i.src; console.log(i); a.download = i.src; document.body.appendChild(a); a.click(); document.body.removeChild(a); } Update 2 Opera webdriver import os from time import sleep from selenium import webdriver from selenium.webdriver.common import desired_capabilities from selenium.webdriver.opera import options _operaDriverLoc = os.path.abspath('c:\\Python27\\Scripts\\operadriver.exe') # Replace this path with the actual path on your machine. _operaExeLoc = os.path.abspath('c:\\Program Files\\Opera\\51.0.2830.34\\oper…
has comment: http://stackoverflow.com/comment/84637910
type: Answer
accepted answer of: http://stackoverflow.com/q/48814810
has comment: http://stackoverflow.com/comment/84637526
answers question: http://stackoverflow.com/q/48814810
has comment: http://stackoverflow.com/comment/84637130
has comment: http://stackoverflow.com/comment/84638412
has comment: http://stackoverflow.com/comment/84638128
has comment: http://stackoverflow.com/comment/84637687
has comment: http://stackoverflow.com/comment/84637319
has comment: http://stackoverflow.com/comment/84637574
has comment: http://stackoverflow.com/comment/84638161
upvote count: 4
has comment: http://stackoverflow.com/comment/84639727

http://stackoverflow.com/q/48930135
type: UnansweredQuestion
tagged with: python-requests
tagged with: http
tagged with: urllib
type: Question
has body: I want to send image data via urllib python 3.6 library. i presently have an implementation of a python 2.7 with the help of requests library. Id there a way to replace the requests lib with the urllib in this code. import argparse import io import os import sys import base64 import requests def read_file_bytestream(image_path): data = open(image_path, 'rb').read() return data if __name__== "__main__": data=read_file_bytestream("testimg.png") requests.put("http.//0.0.0.0:8080", files={'image': data})
has title: python urllib alternative to requests.put command?
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/48930421
tagged with: python

http://stackoverflow.com/q/48836945
tagged with: python
has answer: http://stackoverflow.com/a/48837023
tagged with: pycharm
type: Question
tagged with: svm
score: 0
tagged with: libsvm
has body: I am having this issue. import svm import svmutil from svm import * It's telling me that "svmutil" isn't found. I am using the svm lib for my project on sentiment analysis.
answer count: 1
type: UnansweredQuestion
has title: How to install libsvm?

http://stackoverflow.com/comment/84762391
score: 0
comment on: http://stackoverflow.com/q/48878484
type: Comment
type: QuestionComment
has text: @SCB: I'm interested in whether Context Managers can serve as a hacky version of Ruby Code Blocks. They can only inject a single argument into context, but that doesn't really matter as you can make it a tuple and destructure it on the next line. But if you can only call the block once, then that would effectively sink this idea.

http://stackoverflow.com/q/48890702
has answer: http://stackoverflow.com/a/48939075
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48939075
has comment: http://stackoverflow.com/comment/84802589
type: AnsweredQuestion
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84787177
possible better answer: http://stackoverflow.com/a/48891067
has comment: http://stackoverflow.com/comment/84787063
has answer: http://stackoverflow.com/a/48891286
downvote count: 0
has title: Limit on Pandas groupby count
tagged with: pandas-groupby
answer count: 3
tagged with: pandas
favorite count: 0
has answer: http://stackoverflow.com/a/48891067
has body: I have DataFrame crimes_df: &gt;&gt; crimes_df.size 6198374 I need to calculate events with the same "s_lat", "s_lon" and "date". I use groupby: crimes_count_df = crimes_df\ .groupby(["s_lat", "s_lon", "date"])\ .size()\ .to_frame("crimes") But it doesn't give the correct answer because if you calculate sum you can see that most events were lost: &gt;&gt; crimes_count_df.sum() crimes 476798 dtype: int64 I've also tried agg: crimes_count_df = crimes_df\ .groupby(["s_lat", "s_lon", "date"])\ .agg(['count']) But the same result: crimes_count_df.sum() Unnamed: 0 count 476798 area count 476798 arrest count 476798 description count 476798 domestic count 476798 latitude count 476798 location_description count 475712 longitude count 476798 time count 476798 type count 476798 EDIT: I found out there is a limit on this aggregation functions! See this commands: crimes_df.head(100) \ .groupby(["s_lat", "s_lon", "date"]) \ .size() \ .to_frame("crimes")\ .sum() crimes 100 dtype: int64 crimes_df.head(1000) \ .groupby(["s_lat", "s_lon", "date"]) \ .size() \ .to_frame("crimes")\ .sum() crimes 1000 dtype: int64 crimes_df.head(10000) \ .groupby(["s_lat", "s_lon", "date"]) \ .size() \ .to_frame("crimes")\ .sum() crimes 10000 dtype: int64 crimes_df.head(100000) \ .groupby(["s_lat", "s_lon", "date"]) \ .size() \ .to_frame("crimes")\ .sum() crimes 100000 dtype: int64 crimes_df.head(1000000) \ .groupby(["s_lat", "s_lon", "date"]) \ .size() \ .to_frame("crimes")\ .sum() crimes 476798 dtype: int64 crimes_df.head(10000000) \ .groupby(["s_lat", "s_lon", "date"]) \ .size() \ .to_frame("crimes")\ .sum() crimes 476798 dtype: int64 crimes_df.head(476799) \ .groupby(["s_lat", "s_lon", "date"]) \ .size() \ .to_frame("crimes")\ .sum() crimes 476798 dtype: int64 If you want to check it yourself, here is file with data: https://www.dropbox.com/s/ib0kq16t4c2e5a2/CrimeDataWithSquare.csv?dl=0 You can load it this way: from pandas import read_csv, DataFrame crimes_df = read_csv("CrimeDataWithSquare.csv") I…

http://stackoverflow.com/a/48852911
has comment: http://stackoverflow.com/comment/84712050
answers question: http://stackoverflow.com/q/48852855
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/84928455
has comment: http://stackoverflow.com/comment/135286346
has comment: http://stackoverflow.com/comment/84712027
accepted answer of: http://stackoverflow.com/q/48852855
has comment: http://stackoverflow.com/comment/84928834
has comment: http://stackoverflow.com/comment/84928568
has comment: http://stackoverflow.com/comment/84928556
has body: In pandas the best is avoid loops, so better is use numpy.select and chain condition by &amp; for AND and | for OR: L1 = [10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 48] L2 = [30, 31, 32, 33, 34, 35, 57, 58] m1 = (df['colA'].isin(L1) &amp; df['colB'].isin(L2)) | (df['ColA'] &gt; df['ColB']) m2 = (df['colB'].isin(L1) &amp; df['colA'].isin(L2)) | (df['ColA'] &lt; df['ColB']) df['NewColumnName'] = np.select([m1, m2], [df['ColA'], df['ColB']], default=df['ColA'])
upvote count: 4

http://stackoverflow.com/comment/84865674
type: Comment
has text: Sampling rate and depth are the same on both tools?
comment on: http://stackoverflow.com/q/48923943
score: 0
type: QuestionComment

http://stackoverflow.com/a/48815063
type: Answer
has comment: http://stackoverflow.com/comment/84634397
has body: is this one of the times that i can't use comprehension? No, you've got several issues in here: lettersGuesseed has a typo your comprehension does not make sense. Why do you use letter_list.remove(x) in if ? After all fixes this works as your original code: def getAvailableLetters(letters_guessed): from string import ascii_lowercase as letters letter_list = list(letters) return ' '.join([x for x in letter_list if x not in letters_guessed]) print(getAvailableLetters(['a', 'b', 'x', 'z'])) Output: c d e f g h i j k l m n o p q r s t u v w y
has comment: http://stackoverflow.com/comment/84638277
has comment: http://stackoverflow.com/comment/84637485
answers question: http://stackoverflow.com/q/48815046
score: 0
has comment: http://stackoverflow.com/comment/84634296

http://stackoverflow.com/comment/84854096
type: QuestionComment
comment on: http://stackoverflow.com/q/48923810
score: 0
has text: You know that a cout statement after a return will never be shown right ? Is it a typo :p ?
type: Comment

http://stackoverflow.com/comment/85045346
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48895656
type: Comment
has text: My suggestion about `readlink` and `dirname` paths turned out to be wrong. I have edited the answer to describe possible debugging approach.

http://stackoverflow.com/a/53824494
has body: you can try latest dlami v20.0 which comes with Tensorflow 1.12, this warning disappears there.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48883332
downvote count: 0
score: 1

http://stackoverflow.com/q/48855717
has comment: http://stackoverflow.com/comment/84715855
has comment: http://stackoverflow.com/comment/100767112
has comment: http://stackoverflow.com/comment/84715902
upvote count: 2
has comment: http://stackoverflow.com/comment/84715953
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84715771
score: 2
answer count: 0
downvote count: 0
favorite count: 0
has title: Converting function based view to class based view to return JSON Response
tagged with: django-forms
type: Question
has body: I have a function based view which works fine with Bootstrap Modal dialog and returns the JSON Response. I am trying to implement this with CreateView but couldn't make it to work. Function Based View which works fine :- def task_create(request): form = CreateTaskForm(initial={'owner' : request.user, 'assignee' : request.user}) context = {'form': form} html_form = render_to_string('tasks/task_create_ajax.html', context, request=request) return JsonResponse({'html_form': html_form}) Attempt for Class Based View :- class CreateTaskView(LoginRequiredMixin, CreateView): form_class = CreateTaskForm def get_template_names(self): if self.request.is_ajax(): return ['tasks/task_create_ajax.html'] else: return ['tasks/createtask.html'] def get_form_kwargs(self): kwargs = super(CreateTaskView, self).get_form_kwargs() kwargs.update({'initial': {'owner' : self.request.user, 'assignee' : self.request.user}}) return kwargs def form_invalid(self, form): response = super(CreateTaskView,self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(CreateTaskView, self).form_valid(form) if self.request.is_ajax(): print(form.cleaned_data) data = { 'message': "Successfully submitted form data." } return JsonResponse(data) else: return response Problem :- In function based view, the html form is passed via variable html_form which I can view/debug in browser using console.dump command. When I use the class based view, my form didn't get populated. Can someone please suggest what should be the correct approach to make it work with class based view? How can I pass the JsonResponse for the form (get method) with CreateView?

http://stackoverflow.com/q/48939305
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has title: Custom tokenizer for scikit-learn vectorizers
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48941312
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/84885861
has answer: http://stackoverflow.com/a/48939447
has comment: http://stackoverflow.com/comment/84885921
has body: Given the following list of documents: docs = [ 'feature one`feature two`feature three', 'feature one`feature two`feature four', 'feature one' ] I want to use either of the vectorizer classes in scikit (CountVectorizer or TfidfVectorizer), with 'feature one', 'feature two', 'feature three', and 'feature four' should be the four features represented in the matrix. I tried this: vec = CountVectorizer(token_pattern='(?u)\w+\s.\w.`') But that returns only this: ['feature one`', 'feature two`']
accepted answer: http://stackoverflow.com/a/48939447
answer count: 2
possible better answer: http://stackoverflow.com/a/48941312

http://stackoverflow.com/q/48815210
has comment: http://stackoverflow.com/comment/84634399
tagged with: floating-point
has body: In Python, I receive two floats e.g. a = 0.123456 b = 0.012340 and a precision p = 0.000001 that tells me there will be no digits beyond the 6th decimal of the floats. I want to transform the floats to two integers, so that every information they carry is represented in the integers. int_a = 137632 int_b = 12340 The solution in this case is obviously to multiply them by 1000000, but I can't figure out a smart way to get there. I tried the workaround to get the number of digits in p by: len(str(p))-1 //-1 because of the dot. But: &gt;&gt;&gt; str(p) &gt;&gt;&gt; 1e-06 Well I could replace the "-" by a "+" in the string and transform it back to a float, but this seems for me to be a pretty ugly approach and I thought there must be a much cleaner, mathematical way to do that. Any suggestion?
has answer: http://stackoverflow.com/a/48815258
type: Question
has comment: http://stackoverflow.com/comment/84634433
tagged with: type-conversion
has title: Transform float to int so that every information is preserved OR how to get the lenght of a long float
answer count: 1
tagged with: python
favorite count: 0
tagged with: precision
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
downvote count: 1
score: 1

http://stackoverflow.com/comment/84791902
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48892959
has text: @coldspeed because honestly, I didn't know I could do that XD I thought math.ceil was its own line and couldnt be acted upon
score: 0

http://stackoverflow.com/q/48865627
tagged with: web-scraping
type: UnansweredQuestion
tagged with: python-3.x
type: Question
has title: Looking for an URL from Multiple Pages in Python
tagged with: python
tagged with: url-routing
answer count: 1
has body: I have written a code only to find out one hotel URL but the code only works in 1st page of list.If the hotel name is in 2nd page list or any other pages this code is unable to find out. I am Unable to search URL from Multiple Pages using Python This is not working to search from multiple pages.My code is given below: def parse(locality,checkin_date,checkout_date,sort,hotl_nam): checkIn = checkin_date.strftime("%Y/%m/%d") checkOut = checkout_date.strftime("%Y/%m/%d") # TA rendering the autocomplete list using this API geo_url = 'https://www.tripadvisor.com/TypeAheadJson?action=API&amp;startTime='+str(int(time()))+'&amp;uiOrigin=GEOSCOPE&amp;source=GEOSCOPE&amp;interleaved=true&amp;types=geo,theme_park&amp;neighborhood_geos=true&amp;link_type=hotel&amp;details=true&amp;max=12&amp;injectNeighborhoods=true&amp;query='+locality api_response = requests.get(geo_url, verify=False).json() #getting the TA url for th equery from the autocomplete response url_from_autocomplete = "http://www.tripadvisor.com"+api_response['results'][0]['url'] print ('URL found %s'%url_from_autocomplete) geo = api_response['results'][0]['value'] #Formating date for writing to file date = checkin_date.strftime("%Y_%m_%d")+"_"+checkout_date.strftime("%Y_%m_%d") #form data to get the hotels list from TA for the selected date I am not sure how to resolve this issue.
has answer: http://stackoverflow.com/a/48865994
score: 0

http://stackoverflow.com/q/48834015
has answer: http://stackoverflow.com/a/48834414
tagged with: google-cloud-storage
tagged with: google-cloud-platform
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has body: I have two api endpoints, one that takes a file from an http request and uploads it to a google cloud bucket using the python api, and another that downloads it again. in the first view, i get the file content type from the http request and upload it to the bucket,setting that metadata: from google.cloud import storage file_obj = request.FILES['file'] client = storage.Client.from_service_account_json(path.join( path.realpath(path.dirname(__file__)), '..', 'settings', 'api-key.json' )) bucket = client.get_bucket('storage-bucket') blob = bucket.blob(filename) blob.upload_from_string( file_text, content_type=file_obj.content_type ) Then in another view, I download the file: ... bucket = client.get_bucket('storage-bucket') blob = bucket.blob(filename) blob.download_to_filename(path) How can I access the file metadata I set earlier (content_type) ? It's not available on the blob object anymore since a new one was instantiated, but it still holds the file.
tagged with: python
has title: Get content_type from Google Cloud file
score: 3
upvote count: 3
type: Question

http://stackoverflow.com/a/48879870
has comment: http://stackoverflow.com/comment/84764226
downvote count: 0
has comment: http://stackoverflow.com/comment/84765539
type: Answer
has comment: http://stackoverflow.com/comment/84765021
has comment: http://stackoverflow.com/comment/84764510
has body: Option 1: Pandas import pandas as pd y = [10406.19,10995.72,11162.55,11256.7,11634.98,12174.25,13876.47,18491.18,16908,15266.43] series = pd.Series(y) print(series.rolling(window=6, center=True).mean().dropna().tolist()) Option 2: Numpy import numpy as np window=6 s=np.insert(np.cumsum(np.array(y)), 0, [0]) output = (s[window :] - s[:-window]) * (1. / window) print(list(output)) Output [11271.731666666667, 11850.111666666666, 13099.355, 14056.930000000002, 14725.218333333332] Timings (subject to size of data) # Pandas 59.5 µs ± 8 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) # Numpy 19 µs ± 4.38 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) # @PatrickArtner's solution 16.1 µs ± 2.98 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each) Update Check timings code (works on Jupyter notebook) %%timeit import pandas as pd y = [10406.19,10995.72,11162.55,11256.7,11634.98,12174.25,13876.47,18491.18,16908,15266.43] series = pd.Series(y)
upvote count: 2
answers question: http://stackoverflow.com/q/48879615
has comment: http://stackoverflow.com/comment/84765399
has comment: http://stackoverflow.com/comment/84765058
has comment: http://stackoverflow.com/comment/84764180
score: 2

http://stackoverflow.com/a/71176303
has body: In case anyone is still looking for the answer to this. the easiest way is to just pass an empty dictionary to the files parameter: requests.post(url,..., files={}) there is also another workaround found here (https://github.com/psf/requests/issues/1081) where you can generate an object of this class and pass it as the content for files: class ForceMultipartDict(dict): def __bool__(self): return True FORCE_MULTIPART = ForceMultipartDict() # An empty dict that boolean-evaluates as `True`. client.post(url, data={"some": "data"}, files=FORCE_MULTIPART)
upvote count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/137733923
score: 3
type: Answer
answers question: http://stackoverflow.com/q/48887367

http://stackoverflow.com/comment/84858010
type: QuestionComment
score: 0
has text: In addition to what Dan commented, ElasticNet also requires input to be numeric, so if you have any text/categorical data you'll need to either discard or convert it first (look at OneHotEncoder for categorical features).
type: Comment
comment on: http://stackoverflow.com/q/48925332

http://stackoverflow.com/comment/84865182
has text: And how would you name that app? I'm not quite sure who is responsible for what
comment on: http://stackoverflow.com/q/48929153
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48855204
answer count: 2
has title: Iterate over all current sessions in django
has comment: http://stackoverflow.com/comment/84713827
possible better answer: http://stackoverflow.com/a/66160562
has body: Is it possible in django to iterate all current sessions? I want to implement a calendar where it is impossible to book a timeslot that someone else is booking. I Keep a list of timeslots id's in the session before the user proceeds to checkout.
tagged with: django
tagged with: python
type: AnsweredQuestion
type: Question
tagged with: session
has comment: http://stackoverflow.com/comment/84725706
has answer: http://stackoverflow.com/a/48855694
accepted answer: http://stackoverflow.com/a/48855694
has answer: http://stackoverflow.com/a/66160562
score: 0

http://stackoverflow.com/a/48943512
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48943468
has comment: http://stackoverflow.com/comment/84894961
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84901334
score: 1
has body: The reason is that out2 is undefined in if __name__ == "__main__": because you don't save the returned value from removing_outliers(). So change to if __name__ == "__main__": out2 = removing_outliers() removing_unwanted_columns(out2) and it should be fine
answers question: http://stackoverflow.com/q/48943468
type: AcceptedAnswer

http://stackoverflow.com/comment/84674967
type: QuestionComment
comment on: http://stackoverflow.com/q/48831066
score: 0
has text: I don't have Shapely here at the moment. But you can modify this example with two more lines to find out: https://toblerity.org/shapely/code/multipolygon.py
type: Comment

http://stackoverflow.com/comment/84738868
comment on: http://stackoverflow.com/q/48867604
type: QuestionComment
has text: As an aside the recommendation in Django is to use a singular for the model, e.g. `class Partner(models.Model):`, `partner_list = Partner.objects.all()`, `{% for partner in partner_list %}` and so on.
type: Comment
score: 1

http://stackoverflow.com/comment/84772166
type: QuestionComment
comment on: http://stackoverflow.com/q/48883647
score: 1
has text: I don't know this is a duplicate. I am fully aware about the caching mechanism and that is why I stumbled on the difference in the timing which is substantial. That difference bothers me.
type: Comment

http://stackoverflow.com/comment/84659384
score: 0
comment on: http://stackoverflow.com/q/48806554
type: QuestionComment
has text: Thats why I am asking. I want to understand what you want to achive. b/c looks like you dont get the columns from the output of the `render_table`
type: Comment

http://stackoverflow.com/comment/84674638
comment on: http://stackoverflow.com/q/48834462
type: Comment
type: QuestionComment
has text: Please embed any code in your question rather than provide a link to it (most SO users won't follow links). Also, you might want to add the exact error you are getting.
score: 1

http://stackoverflow.com/a/48879768
downvote count: 0
has body: You chunkify your list and build averages over the chunks. The linked answer uses full chunks, I adapted it to build incremental ones: Sliding avg via list comprehension: # Inspiration for a "full" chunk I adapted: https://stackoverflow.com/a/312464/7505395 def overlappingChunks(l, n): """Yield overlapping n-sized chunks from l.""" for i in range(0, len(l)): yield l[i:i + n] somenums = [10406.19,10995.72,11162.55,11256.7,11634.98,12174.25,13876.47, 18491.18,16908,15266.43] # avg over sublist-lengths slideAvg5 = [ round(sum(part)/(len(part)*1.0),2) for part in overlappingChunks(somenums,6)] print (slideAvg5) Output: [11271.73, 11850.11, 13099.36, 14056.93, 14725.22, 15343.27, 16135.52, 16888.54, 16087.22, 15266.43] I was going for a partion of the list by incremental range(len(yourlist)) before averaging the partitions, but thats as full partitioning was already solved here: How do you split a list into evenly sized chunks? I adapted it to yield incremental chunks to apply it to your problem. What partitions are used for avg-ing? explained = {(idx,tuple(part)): round(sum(part)/(len(part)*1.0),2) for idx,part in enumerate(overlappingChunks(somenums,6))} import pprint pprint.pprint(explained) Output (reformatted): # Input: # [10406.19,10995.72,11162.55,11256.7,11634.98,12174.25,13876.47,18491.18,16908,15266.43] # Index partinioned part of the input list avg {(0, (10406.19, 10995.72, 11162.55, 11256.7, 11634.98, 12174.25)) : 11271.73, (1, (10995.72, 11162.55, 11256.7, 11634.98, 12174.25, 13876.47)) : 11850.11, (2, (11162.55, 11256.7, 11634.98, 12174.25, 13876.47, 18491.18)) : 13099.36, (3, (11256.7, 11634.98, 12174.25, 13876.47, 18491.18, 16908)) : 14056.93, (4, (11634.98, 12174.25, 13876.47, 18491.18, 16908, 15266.43)) : 14725.22, (5, (12174.25, 13876.47, 18491.18, 16908, 15266.43)) : 15343.27, (6, (13876.47, 18491.18, 16908, 15266.43)) : 16135.52, (7, (18491.18, 16908, 15266.43)) : 16888.54, (8, (16908, 15266.43)) : 16087.22, (9, (15266.43,)) : 15266.43}
upvote count: 2
answers question: http://stackoverflow.com/q/48879615
type: Answer
score: 2

http://stackoverflow.com/comment/84795401
comment on: http://stackoverflow.com/q/48885331
has text: Most probably you have a wheel uploaded to your repo, but no source dist package. `python setup.py` commands can't handle wheels, instead looking for source distributions. Building a source tar (`python setup.py sdist`) and uploading it to the repo should help.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84797048
has text: Thank you for your reply. You want to read/write the Google Document using the data of Spreadsheet. Is my understanding correct?
type: QuestionComment
comment on: http://stackoverflow.com/q/48893589
score: 0
type: Comment

http://stackoverflow.com/q/48910713
type: Question
has answer: http://stackoverflow.com/a/48911268
tagged with: odoo
accepted answer: http://stackoverflow.com/a/48911268
upvote count: 2
tagged with: odoo-10
answer count: 1
has title: Odoo creating an invoice with Web Service API (PHP)
favorite count: 0
tagged with: python
tagged with: php
score: 2
type: AnsweredQuestion
has body: I am trying to create an invoice on Odoo using Odoo Web Service API (via PHP) which is based on XML-RPC using the code example in the official API documentation. I have succeeded to create a customer using the code provided in the documentation : $id = $models->execute_kw($db, $uid, $password, 'res.partner', 'create', array(array('name'=>"New Partner")) ); But I can't create an invoice using the code sample provided: $client = $models->execute_kw( $db, $uid, $password, 'res.partner', 'search_read', array(array(array('customer', '=', true))), array( 'limit' => 1, 'fields' => array( 'property_account_receivable_id', 'property_payment_term_id', 'property_account_position_id' )))[0]; $invoice_id = $models->execute_kw( $db, $uid, $password, 'account.invoice', 'create', array(array( 'partner_id' => $client['id'], 'account_id' => $client['property_account_receivable_id'][0], 'invoice_line_ids' => array(array(0, false, array('name' => "AAA"))) ))); when I run the code I get an error response: array(2) { ["faultCode"]=> int(1) ["faultString"]=> string(989) "Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/odoo/service/wsgi_server.py", line 56, in xmlrpc_return result = odoo.http.dispatch_rpc(service, method, params) File "/usr/lib/python2.7/dist-packages/odoo/http.py", line 118, in dispatch_rpc result = dispatch(method, params) File "/usr/lib/python2.7/dist-packages/odoo/service/model.py", line 38, in dispatch res = fn(db, uid, *params) File "/usr/lib/python2.7/dist-packages/odoo/service/model.py", line 157, in execute_kw return execute(db, uid, obj, method, *args, **kw or {}) File "/usr/lib/python2.7/dist-packages/odoo/service/model.py", line 143, in wrapper raise ValidationError(msg) ValidationError: ('The operation cannot be completed, probably due to the following:\n- deletion: you may be trying to delete a record while other records still reference it\n- creation/update: a mandatory field is not correctly set\n\n[object with reference: price_uni…
downvote count: 0

http://stackoverflow.com/q/48806554
has comment: http://stackoverflow.com/comment/84629195
tagged with: django-tables2
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84659993
tagged with: django
upvote count: 1
has title: How add columns from a list?
has comment: http://stackoverflow.com/comment/84619156
has comment: http://stackoverflow.com/comment/84621974
has comment: http://stackoverflow.com/comment/84654653
type: Question
has body: (This is my first post on StackOverFlow and it's a great ressource and community &lt;3) I develop a website and I use django_tables2 to display my result. My problem is that i have my table model here (very simple)... #tables.py class myTable(TableReport, ColumnShiftTable): column_default_show = ['select']; class Meta: attrs = {'class': 'table table-bordered table-striped table-condensed'}; and I want to display dynamically a set of columns... #views.py def visualiserGeneByHost(request): #Get the list of Host ReferenceList = exportdata(); #Get a hash (in keys the name of the genes and in value an object with values and host name. geneByHostHash = exportGeneByHost(ReferenceList); data = []; for key in geneByHostHash: list=geneByIsolatHash.get(key); for element in list: data.append({'gene':key, element.Reference:element.pc_identity}) table = ResistanceTable(data=data) return render(request,'visualisation/page_bootstrap_GeneByHost.html' , {'table':table} ) The geneByHostHash look likes this : {'rrsH_[Escherichia coli]': [&lt; X instance at 0x7f4abdcef440&gt;, &lt;X instance at 0x7f4abdcef488&gt;, &lt;X instance at 0x7f4abdcef8c0&gt;], 'fusA1_[Klebsiella pneumoniae]': [&lt;X instance at 0x7f4abdcef878&gt;], ......} ...but I don't know how adding the columns because the list of columns is not stable. #page_bootstrap_GeneByHost.html &lt;!-- Table loader --&gt; &lt;div class="row"&gt; &lt;form action="{% url 'visualiserGeneByHost' %}" method="post"&gt; {% csrf_token %} {% load django_tables2 %} {% render_table table %} &lt;/form&gt; &lt;/div&gt; I will have a result like that table -> enter image description here I have already all the data like the name of the Genes, the values and the name of the each hosts. I hope that I have been understandable. EDIT I look up with extra_columns arg in django_tables2 but i have __init__ conflict with TableReport &amp; ColumnShiftTable. :/ EDIT I resolve this problem like this: tables.py class ResistanceTable(tables.Table): souche = tab…
has comment: http://stackoverflow.com/comment/84620872
has comment: http://stackoverflow.com/comment/84658877
downvote count: 0
has comment: http://stackoverflow.com/comment/84616053
has comment: http://stackoverflow.com/comment/84659384
favorite count: 0
has comment: http://stackoverflow.com/comment/84648347
tagged with: python
score: 1

http://stackoverflow.com/a/48853233
downvote count: 0
has comment: http://stackoverflow.com/comment/84713644
has comment: http://stackoverflow.com/comment/84716394
score: 1
has body: well its fairly simple.. first, you need pyserial library with proper setup (correct COM port and baud). Then in arduino in main function, add a code like: int incoming; void loop() { if(Serial.available() &gt; 0) { incoming = Serial.read(); } if(incoming == 1) { yourFunction(); } else { errorFunction(); } } expecting value "1" to be send from python script. If its sent and received by arduino, yourFunction() will be executed, otherwise errorFunction() will be. Change if(incoming == 1) to anything you want to.
type: Answer
has comment: http://stackoverflow.com/comment/84713175
has comment: http://stackoverflow.com/comment/84713590
has comment: http://stackoverflow.com/comment/84716347
answers question: http://stackoverflow.com/q/48841076
upvote count: 1
has comment: http://stackoverflow.com/comment/84713432
has comment: http://stackoverflow.com/comment/84710250
has comment: http://stackoverflow.com/comment/84713527

http://stackoverflow.com/comment/84841309
has text: thanks for the suggestion. When I run these within virtual env. with python3, the scripts are working fine. I will uninstall my python outside of the virtual env.
score: 0
comment on: http://stackoverflow.com/q/48915333
type: Comment
type: QuestionComment

google-cloud-functions
tag name: google-cloud-functions
tags question: http://stackoverflow.com/q/48851846
type: Tag
tags question: http://stackoverflow.com/q/48903222

http://stackoverflow.com/comment/84788823
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48891507
type: Comment
has text: thanks, I had already tried that solution too. For the distinct it works, but it does not filter on the product's queryset during the loop

http://stackoverflow.com/comment/84872936
comment on: http://stackoverflow.com/a/48933039
type: Comment
score: 1
has text: @xion If there are 983 columns, wouldn't index 982 be at the end anyways? The index of a list starts at 0. Are you saying you want the zeros added before the last element of the row/line?
type: AnswerComment

http://stackoverflow.com/a/48955045
type: AcceptedAnswer
downvote count: 1
type: Answer
has body: Unfortunately, kernels only support Python 3. ETA: If you're looking for a hosted notebook environment, I just checked and Google Colab does support Python 2, so I might check that out instead if you really need 2.7.
accepted answer of: http://stackoverflow.com/q/48953259
answers question: http://stackoverflow.com/q/48953259
score: 0
upvote count: 1

http://stackoverflow.com/q/48893403
has comment: http://stackoverflow.com/comment/84985205
score: -1
has body: When reading in data, Python gives me the following error: TypeError: list indices must be integers or slices, not tuple with sys import in python I use the following data.txt inputfile: 1.0 2.0 3.0 4.0 5.0 6.0 With the command !python file_name data.txt import sys fp = open(sys.argv[1],"r+") coordinates = fp.readlines() fp.close() import numpy a = numpy.array(coordinates[0, 1, 2]) b = numpy.array(coordinates[3, 4, 5]) dist_unround=numpy.linalg.norm(a-b) dist_round=round(dist_unround, 2) energy_unround=0.5*2*((dist_unround-3.0)**2) energy_round=round(energy_unround,2) print("dist \t energy") print(dist_round,"\t" ,energy_round) I try to calculate a vector from a random input textfile. Is there something wrong with my numpy.array code?
answer count: 2
has comment: http://stackoverflow.com/comment/84792474
upvote count: 0
has comment: http://stackoverflow.com/comment/85031124
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84987294
has comment: http://stackoverflow.com/comment/85031325
tagged with: python
has answer: http://stackoverflow.com/a/48893630
downvote count: 1
has answer: http://stackoverflow.com/a/48893543
type: Question
has comment: http://stackoverflow.com/comment/84886318
tagged with: arrays
has title: TypeError: list indices must be integers or slices, not tuple with sys import in python

http://stackoverflow.com/q/48939455
tagged with: numpy
has body: I have a pandas dataframe with the columns holding opening and closing hours of restaurants. This dataset came from scraping a chinese restaurant guide, a little like tripAdvisor. Please see the image attached for illustration As you see, columns like 'Mon', and 'Fri', contain values, but some rows do not and thus the opening and closing hours are found in the 'Daily' column for the same restaurant. Where the columns 'Mon' and 'Fri' have NaN values, I would like to populate them with the values from the the 'Daily' column. The code that I have tested in the next line returns: 'function' object has no attribute 'apply'.
has answer: http://stackoverflow.com/a/48939531
favorite count: 0
type: Question
tagged with: pandas
tagged with: python
score: -1
downvote count: 2
has title: How to populate rows of a column with values from a different column
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84885990
tagged with: database
type: UnansweredQuestion

http://stackoverflow.com/comment/84872614
type: Comment
score: 0
type: AnswerComment
has text: I actually achieved more a less what I wanted, by using 4 contours as @ImportanceOfBeingErnest suggested, then putting the "bottom" contours with a low alpha and the top ones with a high alpha value.
comment on: http://stackoverflow.com/a/48931750

http://stackoverflow.com/q/48897935
duplicate of: http://stackoverflow.com/q/36250353
tagged with: opencv
tagged with: anaconda
answer count: 0
linked to: http://stackoverflow.com/q/36250353
type: Question
score: 0
has comment: http://stackoverflow.com/comment/84802256
has comment: http://stackoverflow.com/comment/84869161
has comment: http://stackoverflow.com/comment/84805146
tagged with: python-3.x
has body: I'm a beginner in coding and want to learn machine learning. So I've installed Anaconda 4.4.1 and python 3.6 and Open CV 3. I've done everything as told in this website https://chrisconlan.com/installing-python-opencv-3-windows/. After installing, I tried running a short line of code which goes like this: import numpy as np import cv2 img = cv2.imread('dog.jpg', 0) print(img) The output was this: runfile('C:/Users/Russell/Desktop/Python_Test/cv2 test.py', wdir='C:/Users/Russell/Desktop/Python_Test') Traceback (most recent call last): File "&lt;ipython-input-1-8ac86397d1f0&gt;", line 1, in &lt;module&gt; runfile('C:/Users/Russell/Desktop/Python_Test/cv2 test.py', wdir='C:/Users/Russell/Desktop/Python_Test') File "C:\Anaconda\envs\myWindowsCV\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile execfile(filename, namespace) File "C:\Anaconda\envs\myWindowsCV\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Russell/Desktop/Python_Test/cv2 test.py", line 2, in &lt;module&gt; import cv2 File "C:\Users\Russell\Desktop\Python_Test\cv2.py", line 4, in &lt;module&gt; img = cv2.imread('dog.jpg') AttributeError: module 'cv2' has no attribute 'imread' Can anyone help me with this? Would really appreciate it.
type: UnansweredQuestion
has title: Cannot run cv2 in Anaconda
tagged with: python

http://stackoverflow.com/q/48939609
tagged with: iterable
favorite count: 0
has comment: http://stackoverflow.com/comment/84886287
type: Question
has title: To which iterator are my iterators binding to?
tagged with: python
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48939681
has answer: http://stackoverflow.com/a/48939694
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84886382
tagged with: iterator
has body: Here is my python code for this question. class iterator(): def __init__(self, data): self.__data__ = data self.__base__ = -1 self.__sentinel__ = len(data) def __iter__(self): return self def __next__(self): self.__base__ = self.__base__ + 1 if self.__base__ == self.__sentinel__: raise StopIteration else: return self.__data__[self.__base__] class iterable(): def __init__(self, data): self.__iterator__ = iterator(data) def __iter__(self): return self.__iterator__ From above definitions, I wrote the following code to understand the concept iterator binding love = 'Welcome to my house!' house = iterable(love) ice = iter(house) joy = iter(house) if ice is joy: print("ice and joy are the same iterators") king = iter(love) mouse = iter(love) if king is not mouse: print("king and mouse are not the same iterators") When I run the above code, I will get the above messages, which indicates that iterators obtained from iter function invoking on data are not the same, but iterators obtained from iter function invoking on my iterable are the same. Can anyone explain to me what is going on? I would appreciate any help on this. Thank you.
downvote count: 0
score: 1

http://stackoverflow.com/comment/84877457
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48935422
score: 1
has text: Try some googling before asking

http://stackoverflow.com/comment/84688831
comment on: http://stackoverflow.com/q/48842293
has text: @AryaMcCarthy yes, I agree line plot would be better but I am trying to have the bar graphs and a line showing the trend of the data on the same graph. I hope it makes it clear what I'm trying to achieve. I have edited the data above a bit. I just randomly got these numbers. The numbers are not necessarily representative of my data. However, the variables are
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84869810
type: AnswerComment
has text: I managed to get it working by doing: self.canonicalAddressesButton.clicked.connect(self.select_canonical_data) def select_canonical_data(self): os.system('CanonicalAddressesParser.py')
type: Comment
comment on: http://stackoverflow.com/a/48928012
score: 0

http://stackoverflow.com/a/48912577
has body: I guess this is what you wanted. Ran this. It works. Check and tell. import numpy as np int2binary = {} largest_number = pow(2,16) a=(np.array([range(largest_number)],dtype=np.uint8)) b = np.unpackbits(a, axis=1) for row in b: x=row for i in range(len(x)): int2binary[(i)] = x[i] print(int2binary)
type: Answer
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48912471
has comment: http://stackoverflow.com/comment/84831893
answers question: http://stackoverflow.com/q/48912471
has comment: http://stackoverflow.com/comment/84831668
has comment: http://stackoverflow.com/comment/84832010
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84831921
has comment: http://stackoverflow.com/comment/84831812

http://stackoverflow.com/q/48911108
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/35139711
has body: I have a list of commands to be sent to a Juniper router. How can I sort my list by the ip address at the end of the command? From this, generated with set_fact and with_items "command_list": [ "show bgp neighbor 1.1.1.1", "show bgp neighbor 2.2.2.2", "show bgp neighbor 3.3.3.3", "show route receive-protocol bgp 1.1.1.1", "show route receive-protocol bgp 2.2.2.2", "show route receive-protocol bgp 3.3.3.3", "show route advertising-protocol bgp 1.1.1.1", "show route advertising-protocol bgp 2.2.2.2" "show route advertising-protocol bgp 3.3.3.3" ] To this, ordered by the target IP. "command_list": [ "show bgp neighbor 1.1.1.1", "show route receive-protocol bgp 1.1.1.1", "show route advertising-protocol bgp 1.1.1.1", "show bgp neighbor 2.2.2.2", "show route receive-protocol bgp 2.2.2.2", "show route advertising-protocol bgp 2.2.2.2" "show bgp neighbor 3.3.3.3", "show route receive-protocol bgp 3.3.3.3", "show route advertising-protocol bgp 3.3.3.3" ]
has title: Ansible - Sort a list of commands by the last argument, an IP address
type: Question
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48911361
tagged with: ansible
favorite count: 0
upvote count: 2
accepted answer: http://stackoverflow.com/a/48911361
tagged with: python
tagged with: jinja2
score: 2

http://stackoverflow.com/a/55164251
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/48876387
has body: You might also use the spark udf. The solution might be applied whenever you need to modify a data frame entry with a value from another column: from pyspark.sql.functions import udf from pyspark.sql.types import StringType pd_input = pd.DataFrame({'address': ['2.PA1234.la','10.PA125.la','2.PA156.ln'], 'st':['1234','125','156']}) spark_df = sparkSession.createDataFrame(pd_input) replace_udf = udf(lambda address, st: address.replace(st,'9999'), StringType()) spark_df.withColumn('adress_new',replace_udf(col('address'),col('st'))).show() Output: +-----------+----+------------+ | adress| st| adress_new| +-----------+----+------------+ |2.PA1234.la|1234| 2.PA9999.la| |10.PA125.la| 125|10.PA9999.la| | 2.PA156.ln| 156| 2.PA9999.ln| +-----------+----+------------+
type: Answer
score: 2

http://stackoverflow.com/q/48869196
has body: I've tried to install pandas using pip but several warnings and an one error appears. Here is the command that I used pip install pandas I've received several warning messages like this: x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -D_FORTIFY_SOURCE=2 -g -fstack-protector --param=ssp-buffer-size=4 -Wformat -Werror=format-security build/temp.linux-x86_64-2.7/pandas/_libs/join.o -o build/lib.linux-x86_64-2.7/pandas/_libs/join.so building 'pandas._libs.tslibs.frequencies' extension creating build/temp.linux-x86_64-2.7/pandas/_libs/tslibs x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Ipandas/_libs/src/klib -Ipandas/_libs/src -I/usr/local/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -c pandas/_libs/tslibs/frequencies.c -o build/temp.linux-x86_64-2.7/pandas/_libs/tslibs/frequencies.o -Wno-unused-function In file included from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarraytypes.h:1816:0, from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/ndarrayobject.h:18, from /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/arrayobject.h:4, from pandas/_libs/tslibs/frequencies.c:526: /usr/local/lib/python2.7/dist-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp] #warning "Using deprecated NumPy API, disable it by " \ When, finally, the error message appears Cleaning up... Command /usr/bin/python -c "import setuptools, tokenize;__file__='/tmp/pip_build_flaviomb-lasse/pandas/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-O3U0h8-record/install-record.txt --single-version-externally-m…
favorite count: 0
downvote count: 0
type: UnansweredQuestion
tagged with: pip
tagged with: python
score: 3
has title: Pandas: Error when I tried to install it using pip
has answer: http://stackoverflow.com/a/48871069
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/26473681
has comment: http://stackoverflow.com/comment/84748671
upvote count: 3
has comment: http://stackoverflow.com/comment/84745966
tagged with: pandas

http://stackoverflow.com/comment/84755835
type: Comment
comment on: http://stackoverflow.com/a/48859067
type: AnswerComment
score: 0
has text: @David glad to help! Please see my recent edit. I incorporated your original `funct2` function with the loop.

http://stackoverflow.com/comment/84879465
type: QuestionComment
comment on: http://stackoverflow.com/q/48936132
has text: @Wen this doesn't do the trick. I was forcing to have at least two `True` per group. Plus I was looking for something where I can plug my custom (eventually more complex) function.
score: 0
type: Comment

http://stackoverflow.com/q/48911830
has body: I have a series that starts with a state name and then list certain cities in that state, like so... locations = ['Alabama', 'Auburn', 'Tuscaloosa', 'Alaska', 'Fairbanks', 'Arizona', 'Flagstaff', 'Tempe', 'Tuscon'] and a dict which takes state names and turns them into postal codes, like so... state_codes = {'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ'} what I want is a dataframe x with each postal code applied properly to each location, whether the location is a city or a state... State RegionName 'Alabama' AL 'Auburn' AL 'Tuscaloosa' AL 'Alaska' AK 'Fairbanks' AK 'Arizona' AZ 'Flagstaff' AZ 'Tempe' AZ 'Tuscon' AZ ...but I can't quite seem to find the right code to get me there. I had been trying to use a temporary value that changes whenever a new state name is detected: temp = 'fail' newAreas = [] for k in range(0, len(locations)): if (locations[k] in state_codes.items()): temp = state_codes[locations[k]] newAreas.append(temp) ...but that returns a column of entirely the word 'fail.' What am I doing wrong?
has answer: http://stackoverflow.com/a/48912239
tagged with: python
answer count: 4
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48912023
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/48912023
has comment: http://stackoverflow.com/comment/84830477
type: Question
has title: How to iterate through a dict in pandas when some outputs will repeat
has answer: http://stackoverflow.com/a/48911914
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48912115
favorite count: 0
accepted answer: http://stackoverflow.com/a/48911914

http://stackoverflow.com/comment/84902297
has text: @jazrael I've changed my question. Thanks
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48946537
type: Comment

http://stackoverflow.com/q/48938264
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/48938413
has title: Subtracting columns from a numpy array
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48938298
has body: This question is a follow-up of a previous post of mine: Multiply each column of a numpy array with each value of another array. Suppose i have the following arrays: In [252]: k Out[252]: array([[200, 800, 400, 1600], [400, 1000, 800, 2000], [600, 1200, 1200,2400]]) In [271]: f = np.array([[100,50],[200,100],[300,200]]) In [272]: f Out[272]: array([[100, 50], [200, 100], [300, 200]]) How can i subtract f from k to obtain the following? In [252]: g Out[252]: array([[100, 750, 300, 1550], [200, 900, 600, 1900], [300, 1000, 900,2200]]) Ideally, i would like to make the subtraction in as fewer steps as possible and in concert with the solution provided in my other post, but any solution welcome.
accepted answer: http://stackoverflow.com/a/48938298
tagged with: python
linked to: http://stackoverflow.com/q/48937018
score: 2
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/48938413
type: Question
tagged with: numpy

http://stackoverflow.com/q/48884480
has comment: http://stackoverflow.com/comment/84773951
downvote count: 1
has comment: http://stackoverflow.com/comment/84776593
type: Question
has answer: http://stackoverflow.com/a/48887189
has comment: http://stackoverflow.com/comment/84773927
has body: I am using dateutils.parser.parse to parse date strings which might contain partial information. If some information is not present, parse can take a default keyword argument from which it will fill any missing fields. This default defaults to datetime.datetime.today(). For a case like dateutil.parser.parse("Thursday"), this means it will return the date of the next Thursday. However, I need it to return the date of the last Thursday (including today, if today happens to be a Thursday). So, assuming today == datetime.datetime(2018, 2, 20) (a Tuesday), I would like to get all of these asserts to be true: from dateutil import parser from datetime import datetime def parse(date_str, default=None): # this needs to be modified return parser.parse(date_str, default=default) today = datetime(2018, 2, 20) assert parse("Tuesday", default=today) == today # True assert parse("Thursday", default=today) == datetime(2018, 2, 15) # False assert parse("Jan 31", default=today) == datetime(2018, 1, 31) # True assert parse("December 10", default=today) == datetime(2017, 12, 10) # False Is there an easy way to achieve this? With the current parse function only the first and third assert would pass.
score: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48887189
has comment: http://stackoverflow.com/comment/84775571
tagged with: datetime
has comment: http://stackoverflow.com/comment/84774027
tagged with: python
has comment: http://stackoverflow.com/comment/84774957
tagged with: date-parsing
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84774434
has comment: http://stackoverflow.com/comment/84773902
tagged with: python-dateutil
has title: dateutils default to the last occurence of recognized part, not next
upvote count: 1

http://stackoverflow.com/comment/84807872
comment on: http://stackoverflow.com/q/48900923
score: 0
type: Comment
type: QuestionComment
has text: Tip: https://github.com/Clever/postgres-to-redshift

http://stackoverflow.com/q/48918270
type: AnsweredQuestion
type: Question
score: 0
has body: I am trying to append every second row from a dataset into a separate list. But I get a TypeError: float() argument must be a string or a number, not 'list'when trying to convert each row into a float so I can do this. x_data = [random.sample(range(80), 20)]*1000 y_data = [random.sample(range(80), 20)]*1000 data = [x_data,y_data] n = 0 for row in data : if n == 0 : n+=1 continue x_data = [] y_data = [] for (x,y) in [(0,1),(2,3), (4,5), (6,7), (8,9), (10,11), (12,13), (14,15), (16,17), (18,19), (20,21), (22,23), (24,25), (26,27), (28,29), (30,31), (32,33), (34,35), (36,37), (38,39)] : xcoord = float(row[x]) #Error occurs in this line ycoord = float(row[y]) if xcoord &gt;= 5 : x_data.append(xcoord) y_data.append(ycoord) I tried to change float(row[x]) to list(map(float(row[x])) but get the same result?
has answer: http://stackoverflow.com/a/48918363
has title: TypeError when trying to convert a row to a float as to append into a list
answer count: 1
accepted answer: http://stackoverflow.com/a/48918363
tagged with: python

drf-queryset
type: Tag
tag name: drf-queryset
tags question: http://stackoverflow.com/q/48885254

http://stackoverflow.com/comment/84815639
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48904950
has text: Thanks for your help. It worked after re-assignment. result_array=np.append(result_array, arr_1d, axis=0)

http://stackoverflow.com/comment/84755156
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48875255
has text: @eric Trackback has been added. It is the exact error.
type: QuestionComment

http://stackoverflow.com/q/48919673
tagged with: numpy
possible better answer: http://stackoverflow.com/a/48919754
accepted answer: http://stackoverflow.com/a/48921397
score: 0
answer count: 2
tagged with: array-broadcasting
has body: I have a bunch of 5-dimensional vectors of shape (5,) in a 2-dimensional array of shape (1000, 5), each of which which I want to multiply by a matrix of shape (6, 5). I would have assumed that broadcasting would allow me to do A = np.random.rand(1000, 5) B = np.random.rand(1, 6, 5) # empty axis for broadcasting np.matmul(B, A) but this doesn't work properly. Is there a way to do this kind of multiplication so that np.matmul(B, A) produces an output of shape (1000, 6)?
tagged with: python
has title: Numpy Matmul while ignoring first axis
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48921397
has answer: http://stackoverflow.com/a/48919754
type: Question

http://stackoverflow.com/q/48815486
downvote count: 2
tagged with: function
tagged with: program-entry-point
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84635096
has body: After I pick an option my program is supposed to give me the area of a rectangle, circle, or triangle after I input the unit of whatever shape. But instead of stopping after one area formula, it continues to do all of them. How do I stop this? import math def main(): menu() if choice ==1: circle() if choice == 2: rectangle() if choice ==3: triangle() def menu(): global choice choice = int(input('choose option 1-3:')) while choice &lt; 1 or choice &gt; 3: print('error. must choose option 1-3') choice = int(input('try again:')) circle() rectangle() triangle() def circle (): radCir = float(input('enter radius of circle:')) areaCir = math.pi*radCir**2 print('area of circle:',format(areaCir,'.2f')) def rectangle(): global choice length = float(input('enter length of rectangle:')) width = float(input('enter width of rectangle:')) areaRec = length * width print('area of rectangle:',format(areaRec, '.2f')) def triangle(): base = float(input('enter base of triangle:')) height = float(input('enter height of triangle:')) areaTri = base * height * .5 print('area of triangle:',format(areaTri,'.2f')) main()
tagged with: python
has comment: http://stackoverflow.com/comment/84634931
tagged with: menu
has answer: http://stackoverflow.com/a/48815765
accepted answer: http://stackoverflow.com/a/48815765
has title: confused with def main() and def menu() order
type: AnsweredQuestion
upvote count: 0
tagged with: loops
type: Question
score: -2

http://stackoverflow.com/q/48805590
tagged with: qspinbox
has answer: http://stackoverflow.com/a/48814691
type: Question
upvote count: 2
tagged with: pyqt
answer count: 1
has title: How to use superscripts in QDoubleSpinBox suffix
downvote count: 0
has body: I am trying to format part of a suffix in a QDoubleSpinBox as a superscript. Thus far I have tried the following: self.myDblSinBox.setSuffix("Nsm-4") and: self.myDblSinBox.setSuffix(r"Nsm$^{-4}$") but without succes. Is there anyone who knows if this is possible? I am using Python 3.6, IPython 6.1, Spyder 3.2.3, and PyQt5.
tagged with: superscript
tagged with: python
favorite count: 0
score: 2
accepted answer: http://stackoverflow.com/a/48814691
tagged with: pyqt5
type: AnsweredQuestion

http://stackoverflow.com/comment/84764459
has text: If nothing better pops up today, I feel this answer deserves to be accepted since it gave me a very useful suggestion on how to proceed with the implementation of the algorithm I am looking for.
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48870891

http://stackoverflow.com/q/48905888
has comment: http://stackoverflow.com/comment/84821384
upvote count: 1
tagged with: analysis
type: Question
has comment: http://stackoverflow.com/comment/84818258
downvote count: 0
has comment: http://stackoverflow.com/comment/84818699
has title: How to traverse an Abstract Syntax Tree object in python using javalang module?
has comment: http://stackoverflow.com/comment/84819144
favorite count: 0
tagged with: static
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84817597
has body: I'm using javalang module (https://github.com/c2nes/javalang) to analyze a java code. I have no knowledge about parsing or static code analysis. Example: tree = javalang.parse.parse("-javacodelocation-") for path,node in tree: print path,node This traverses through the tree and displays the path and the node name. node.children() gives all children of the iterator node. I really can't figure how to traverse through this tree object properly and what all more information I can gather from the given Java code using this tree object. Basically I just want to know more attributes,methods etc of the iterator node. I tried using the dir(), still couldn't figure out anything useful This is what I've implemented till now. https://github.com/MokshTalreja/JavaCodeAnalyzer
answer count: 0
score: 1
tagged with: java

http://stackoverflow.com/a/48841832
downvote count: 0
has comment: http://stackoverflow.com/comment/84689006
score: 1
has body: I guess the reason is results['posts'] value is overwritten per every for loop.. How about changing code like queries = querystring.split() tmp = [] for query in queries: tmp.append(Post.objects.filter(text__icontains=query)) results['posts'] = tmp
upvote count: 1
answers question: http://stackoverflow.com/q/48841782
type: Answer
has comment: http://stackoverflow.com/comment/84688797

http://stackoverflow.com/comment/94684743
type: Comment
score: 1
has text: Welcome to Stack Overflow! Thank you for the code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its [long-term value](https://meta.stackexchange.com/q/114762/206345) by describing why this is a good solution to the problem, and would make it more useful to future readers with other similar questions. Please edit your answer to add some explanation, including the assumptions you've made.
comment on: http://stackoverflow.com/a/53915121
type: AnswerComment

http://stackoverflow.com/a/49251424
type: Answer
has body: Quite often "type mismatch" or "conversion" errors can come from the way you get your naoqi module. Here you get it the "old" (naoqi v.1) way : self.ALAudioDevice = ALProxy("ALAudioDevice") Which can generate conversion errors. Can you try to get it the new way, via the session : self.ALAudioDevice = self.session().service("ALAudioDevice")
upvote count: 1
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48950804

http://stackoverflow.com/comment/84770663
has text: Im pretty sure of my_list and its type print (type(my_list)) #<class 'list'> print(my_list['status']) #TypeError: list indices must be integers or slices, not str
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48882938
type: Comment

gtk3
tags question: http://stackoverflow.com/q/48853226
type: Tag
tags question: http://stackoverflow.com/q/48831728
tag name: gtk3

http://stackoverflow.com/a/74378304
answers question: http://stackoverflow.com/q/48927271
type: Answer
has body: Using Spark SQL SELECT word, count(*) FROM (SELECT explode(split(Description, ' ')) AS word FROM mytable) GROUP BY 1 ORDER BY 2 DESC Full example data = [ ("2015-05-14 03:53:00", "WARRANT ARREST"), ("2015-05-14 03:53:00", "TRAFFIC VIOLATION"), ("2015-05-14 03:33:00", "TRAFFIC VIOLATION") ] df = spark.createDataFrame(data, ["Dates", "Description"]) df.createOrReplaceTempView("mytable") spark.sql(""" SELECT word, count(*) FROM (SELECT explode(split(Description, ' ')) AS word FROM mytable) GROUP BY 1 ORDER BY 2 DESC """).show()
score: 0

http://stackoverflow.com/q/48836589
type: Question
answer count: 2
score: -1
has comment: http://stackoverflow.com/comment/84678189
has body: I am following an online django course and one of the exercises includes creating a blog. One of the elements of the blog includes a "Publish" button but when I click it nothing happens. This is the code: HTML: Publish views.py: @login_required def post_publish(request,pk): post = get_object_or_404(Post,pk=pk) post.publish() return redirect('post_detail',pk=pk) urls.py: url(r'^post/(?P<pk>\d+)/publish/$',views.post_publish,name='post_publish'),
downvote count: 1
has answer: http://stackoverflow.com/a/48838583
has comment: http://stackoverflow.com/comment/84679051
has comment: http://stackoverflow.com/comment/84680548
favorite count: 0
upvote count: 0
has answer: http://stackoverflow.com/a/48840471
type: UnansweredQuestion
tagged with: django
tagged with: python
has title: Publish button doesn't do anything (django forms)

http://stackoverflow.com/q/48910820
tagged with: cmd
has body: I have the code that you can see below. I'm trying to go first to the directory and then,with the pipe "|" make a backup of the MongoDB´s database.The problem is that when I launch the script the console returns me mongodump is not an internal or external command. On the other hand,if I launch the same line cd C:\\...\\MongoDB\\Server\\3.6\\bin | mongodump -h ip -d database name -o C:\\Users\\...\\Desktop\\BackUpMongo in my system cmd it works without problems. Any idea? import sys import os if __name__ == '__main__': try: os.system('cd C:\\...\\MongoDB\\Server\\3.6\\bin | mongodump -h ip -d database name -o C:\\Users\\...\\Desktop\\BackUpMongo') print("Copia de seguridad finalizada") except: print("Error during data base backup") sys.exit(0)
type: Question
has answer: http://stackoverflow.com/a/48911183
tagged with: python
linked to: http://stackoverflow.com/q/8055371
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48911183
has title: Launch a script from Python
has comment: http://stackoverflow.com/comment/84828444
type: AnsweredQuestion

http://stackoverflow.com/comment/84835015
has text: @anupamb No problem. Happy to help. :-)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48914264
type: Comment

http://stackoverflow.com/q/48942256
has title: Nestable Blueprint not working
type: Question
tagged with: flask
has body: I would like to use Blueprint nesting so that similar blueprints can have similar @similar.before_request, etc (along with nice url name spacing). I am aware that flask doesnt native support this feature. However, this issue mentions a way to do it: class NestableBlueprint(Blueprint): """ Hacking in support for nesting blueprints, until hopefully https://github.com/mitsuhiko/flask/issues/593 will be resolved """ def register_blueprint(self, blueprint, **options): def deferred(state): url_prefix = (state.url_prefix or u"") + (options.get('url_prefix', blueprint.url_prefix) or u"") if 'url_prefix' in options: del options['url_prefix'] state.app.register_blueprint(blueprint, url_prefix=url_prefix, **options) self.record(deferred) Trying the above fails to work, and gives me 404. I have a file, which defines a blueprint like : base_blueprint = Blueprint("BASE", __name__, url_prefix='/v0.1') At the bottom, I have : from .Admin import admin_base_blueprint admin_base_blueprint.register_blueprint(base_blueprint, url_prefix='/admin') And Admin.py is defined as: admin_base_blueprint = NestableBlueprint('admin', __name__) @admin_base_blueprint.route('/', methods=['GET']) def admin_echo_time(): """ Just a function to echo current time. May be useful for testing if servers are up. :return: current date """ return datetime.now() When I try to visit GET /v0.1/admin, it give me a 404. I also tried https://stackoverflow.com/a/36326234/2670775. In this case, I am able to get url name spacing to work , but blueprint functions like before_request dont get called. my flask version is 0.12.2
linked to: http://stackoverflow.com/q/33003178
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: design-patterns
answer count: 0
score: 1
upvote count: 1

http://stackoverflow.com/comment/84832150
has text: https://stackoverflow.com/q/38878741/6445069
comment on: http://stackoverflow.com/q/48912898
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/67888693
has body: This should now be fixed in Tweepy v3.7.0 and newer. See: https://github.com/tweepy/tweepy/issues/576 https://github.com/tweepy/tweepy/issues/698 https://github.com/tweepy/tweepy/commit/c1eddf1a5788ec4947d3a363dfe165ea599c31fc https://github.com/tweepy/tweepy/issues/1026 https://github.com/tweepy/tweepy/pull/1027
answers question: http://stackoverflow.com/q/48890261
score: 0
type: Answer

http://stackoverflow.com/a/48934291
score: 1
has body: Just for fun here's a way of padding with both the 0 and 1 with just np.pad: Write a little padding function. def pad_with(vector, pad_width, iaxis, kwargs): # print(vector, pad_width,iaxis) if iaxis==0: vector[-1] = 1 return vector This is just enough of a change from the example in the docs to work here. The print line was helpful in understanding what pad is passing it. So the action is determined by that 2nd pad width number: In [31]: np.pad(x, [[0,1],[0,0]],pad_with) Out[31]: array([[0, 1, 2, 3], [4, 5, 6, 7], [1, 1, 1, 1]]) In [32]: np.pad(x, [[0,2],[0,0]],pad_with) Out[32]: array([[0, 1, 2, 3], [4, 5, 6, 7], [0, 0, 0, 0], [1, 1, 1, 1]]) In [33]: np.pad(x, [[0,4],[0,0]],pad_with) Out[33]: array([[0, 1, 2, 3], [4, 5, 6, 7], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [1, 1, 1, 1]]) With the print on: In [27]: np.pad(x, [[0,1],[0,0]],pad_with) [0 4 0] (0, 1) 0 [1 5 0] (0, 1) 0 [2 6 0] (0, 1) 0 [3 7 0] (0, 1) 0 [0 1 2 3] (0, 0) 1 [4 5 6 7] (0, 0) 1 [1 1 1 1] (0, 0) 1 Out[27]: array([[0, 1, 2, 3], [4, 5, 6, 7], [1, 1, 1, 1]]) So pad is iterating over each row and column, and passing to this function the 0 padded vector. The function can then modify that, even changing the interior values. Lots of generality here, but over kill for this simple problem.
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48929508
upvote count: 1

http://stackoverflow.com/comment/84715252
has text: @PeterWood The issue was when I import it I alias it. So import example_name as en. So when I ran print(en._file_) I got "/home/user_name/other-library/example_name.py". The problem I have now is when I run "cd ~" in my terminal I don't see a "other-library" in the directory even when I show the hidden files. Could it be that the "other-library" folder got deleted and since I haven't restarted the kernel it's still working when I run the cell with the import example_name as en line in it?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48855519
type: QuestionComment

http://stackoverflow.com/q/48941388
has answer: http://stackoverflow.com/a/48945957
type: AnsweredQuestion
upvote count: 5
type: Question
has title: Python lru_cache implementation
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48945957
favorite count: 0
score: 5
tagged with: python-3.x
has body: I am trying to understand the implementation of lru_cache decorator in python (3) specifically how it creates the key from function args for its internal dict. I have been reading this https://github.com/python/cpython/blob/master/Lib/functools.py#L414 I am unable to understand why there is this kwd_mark = (object(),) in the function. I see that it is making a tuple with only an instance of object() and what it seems like is that it is like a delimiter between all of the args and kwargs/kwds for the key for a function call. I am trying to understand if it is doing anything special here https://repl.it/repls/ExpensiveFinishedSandboxes but I can not think of anything.
tagged with: python

http://stackoverflow.com/comment/85505433
comment on: http://stackoverflow.com/a/49215234
type: AnswerComment
has text: Sorry, I do not follow your answer. Yes this question is more conceptual (but if you know how to implement it feel free to link a git repo demonstrating). If an app is dependent on a model, how do I write it to take in this model (if I use it in another project)? So for Q1, why would I not place both independent functions under a user app? For Q3, it doesn't make sense to copy-paste the same file everywhere, especially if it is custom static files like css as that would scale poorly. To be honest I do not find your answer at the moment sufficient in answering the question
type: Comment
score: 0

http://stackoverflow.com/q/48810947
has comment: http://stackoverflow.com/comment/84626234
has comment: http://stackoverflow.com/comment/84625375
has comment: http://stackoverflow.com/comment/84625533
type: AnsweredQuestion
tagged with: loops
type: Question
has comment: http://stackoverflow.com/comment/84626652
score: 0
has answer: http://stackoverflow.com/a/48812126
accepted answer: http://stackoverflow.com/a/48812126
answer count: 1
has body: I am currently going through one of online beginner courses for Python3 where a guy makes an RPG games in order to show its functionalities. So in general the game works in main.py and uses 3 classes, each in separate file. Classes are Person, Spell and Item Basically it works in a loop for whole game, and inside of it, it loops through each player in party (3 players, one enemy). Person class looks lihe this: class Person: def __init__(self, name, hp, mp, atk, df, magic, items): self.maxhp = hp self.hp = hp self.maxmp = mp self.mp = mp self.atkl = atk - 15 self.atkh = atk + 15 self.df = df self.magic = magic self.items = items self.actions = ["Attack", "Magic", "Items"] self.name = name Now straight to the problem: When i pass dictionary/array with items using one variable this way: player_items = [{"item": potion, "quantity": 4}, {"item": superPotion, "quantity": 5}, {"item": elixer, "quantity": 5}, {"item": grenade, "quantity": 2}] player1 = Person("Nasteroth", 460, 130, 65, 34, player_spells, player_items) player2 = Person("Vidala ", 380, 200, 55, 34, player_spells, player_items) player3 = Person("Xerogas ", 540, 100, 80, 34, player_spells, player_items) and then, during player1 turn when it should reduce the quantity of used item by 1 for player1 only, it reduces the quantity for ALL players which we are looping through? Part of loop here: players = [player1, player2, player3] for player in players: item_choice = int(input(BColors.OKGREEN + "Choose item to use: " + BColors.ENDC)) - 1 item = player.items[item_choice] if item["item"].type == "potion": player.heal(item["item"].prop) print(BColors.OKGREEN, "\n", item["item"].name, "heals for", str(item["item"].prop), "HP", BColors.ENDC) item["quantity"] -= 1 But when i pass items the manual way: player1 = Person("Nasteroth", 460, 130, 65, 34, player_spells, [{"item": potion, "quantity": 4}, {"item": superPotion, "quantity": 5}, {"item": elixer, "quantity": 5}, {"item": grenade, "quantity": 2}]) player2 = Person("Vi…
has title: Looping through instances and changing value of specific instance parameter goes wrong
tagged with: python

http://stackoverflow.com/comment/84684981
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48831544
type: Comment
has text: I'm going the reinstall pycharm

http://stackoverflow.com/comment/84634672
comment on: http://stackoverflow.com/q/48815365
score: 0
type: QuestionComment
type: Comment
has text: @AntonvBR No, I'd like to make a function that interprets something like `myDict["main", "foo", "xyz"]` as `myDict["main"]["foo"]["xyz"]`

http://stackoverflow.com/q/48865825
tagged with: tweepy
has title: Image resolution decreases when uploading image to twitter using python tweepy
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48868981
type: Question
has body: I am using python tweepy library to update status on twitter. It is working fine but quality of image uploaded is not original. I am using following statement to upload api.update_with_media(filename=image, status=tags_str) Original Image Uploaded Image
tagged with: twitter
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84739432
has comment: http://stackoverflow.com/comment/84740739
tagged with: python

http://stackoverflow.com/q/48893528
tagged with: tensorflow
type: Question
has body: Which one is the recommended (or more future-proof) way to use Keras? What are the advantages/disadvantages of each? I guess there are more differences than simply saving one pip install step and writing tensorflow.python.keras instead of keras.
answer count: 2
score: 36
has answer: http://stackoverflow.com/a/49073626
upvote count: 39
tagged with: deep-learning
tagged with: keras
favorite count: 0
tagged with: pip
tagged with: python
accepted answer: http://stackoverflow.com/a/49073626
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/58602751
has answer: http://stackoverflow.com/a/58602751
has title: keras vs. tensorflow.python.keras - which one to use?
downvote count: 3

http://stackoverflow.com/comment/84738892
comment on: http://stackoverflow.com/a/48867654
type: AnswerComment
type: Comment
has text: It helped! Also added `self.fileNameSave+".xlsx"` for xlsxwritter to save properly, thanks
score: 0

http://stackoverflow.com/q/48835809
linked to: http://stackoverflow.com/q/1207406
answer count: 4
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48836001
type: Question
has answer: http://stackoverflow.com/a/48835896
has comment: http://stackoverflow.com/comment/84676522
has title: Attempting to filter through itemset
score: 0
has answer: http://stackoverflow.com/a/48835887
accepted answer: http://stackoverflow.com/a/48835887
has body: I have an itemset called data, where in every itemset is the first element of a tuple. An example of one instance looks like this: (('5', 'Generous', '&lt;=X'), 0.33333333333333) I am trying to filter through the itemset in two parts: Part 1 - I'm trying to filter out the itemset so that the only instances remaining are ones which contain '&lt;=X' within the actual itemset (Within the first part of the tuple for each instance). Code for Part 1: for i in data: if "&lt;=X" not in i[0]: del i Part 2 - I'm now trying to take the remaining items and filter it in such a way that the only sets remaining are ones where there are three or more items in the itemset. Code for Part 2: for i in data: if len(i[0]) &lt; 3: del i Despite this, when I try to run the above code I end up with an empty list, but I have looked through the list with a variable inspector and I have seen that there are occurrences of this, but they don't show up after filtering. What's wrong?
tagged with: parsing
tagged with: tuples
has answer: http://stackoverflow.com/a/48837299
tagged with: python
possible better answer: http://stackoverflow.com/a/48835896

http://stackoverflow.com/comment/84784553
score: 1
has text: I also don't understand, explain clearly the logic, is each list independent or not? Does the order matter when you filter out the duplicates?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48889647

http://stackoverflow.com/q/48895323
has comment: http://stackoverflow.com/comment/84796448
has comment: http://stackoverflow.com/comment/84796599
has comment: http://stackoverflow.com/comment/84796490
answer count: 1
score: -1
favorite count: 0
type: UnansweredQuestion
tagged with: python
downvote count: 1
has body: import subprocess command = r'C:\Windows\system32\windowspowershell\v1.0\powershell.exe -noe -c ". \"C:\Program Files\VMware\VMware View\Server\extras\PowerShell\add-snapin.ps1\""' subprocess.call(command,shell=True) I use to this code but i recived error on powershell add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 5. At C:\Program Files\VMware\VMware View\Server\extras\PowerShell\add-snapin.ps1:25 char:2
has title: Python Execute Error
has answer: http://stackoverflow.com/a/48895453
type: Question
linked to: http://stackoverflow.com/q/14894993
upvote count: 0
tagged with: powershell

http://stackoverflow.com/comment/84799128
type: Comment
comment on: http://stackoverflow.com/a/48896663
type: AnswerComment
has text: The issue with that is that it also groups by the other values, which I don't want to do. I just want to take the value from the last one for VALUE B and VALUE C.
score: 0

http://stackoverflow.com/a/67960348
answers question: http://stackoverflow.com/q/48915456
has body: letters = [chr(i) for i in range(97, 123)] alph_index = dict(zip(letters, range(26))) print(&quot;&gt;&gt; letters=&quot;, letters) print(&quot;&gt;&gt; alph_index=&quot;, alph_index) ord('a') = 97 chr(97) = 'a' 97 is a, 65 is A, 122 is z Output: &gt;&gt; letters= ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] &gt;&gt; alph_index= {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25}
score: 0
type: Answer

http://stackoverflow.com/q/48896633
has answer: http://stackoverflow.com/a/48896739
favorite count: 0
tagged with: python-3.x
downvote count: 2
has comment: http://stackoverflow.com/comment/84799011
tagged with: python
possible better answer: http://stackoverflow.com/a/48896739
tagged with: append
has comment: http://stackoverflow.com/comment/84799077
accepted answer: http://stackoverflow.com/a/48896809
type: AnsweredQuestion
tagged with: syntax
upvote count: 1
has answer: http://stackoverflow.com/a/48896773
type: Question
tagged with: if-statement
has body: I am trying to create a way to add input values to my lists through a user interface that asks you what the category and what word you would like to add it to. It all works just fine, and as you can see I was trying it out with my test category (the reason for the seemingly unnecessary print statements) except for one thing: the append statement. I want to find a way to put the inputted category in the spot before the append so that the phrase that i want to add will be added to that category. I am not sure what to put so I tried a number of things: list, (list), userCategory (which is in there now), and (userCategory). I think it is probably a syntax error but it just tells me that those names can't be appended to. This is the error message: AttributeError: 'str' object has no attribute 'append This is my code: testcategory = ['chicken',] greetingInput = ['hi','HI','Hi','Hello','wazzup','hello','sup','Sup','howdy','Howdy','hey','Hey','What\'s hanging my dude?',] greetingOutput = ['Hello, how are you?','How\'s it going?','Wazzup','What\'s hanging my dude?',] greetingResponseP = ['good','great','ok','fine','okay','amazing','splendid','Good','Great','Ok','Fine','Okay','OK','Amazing','Splendid','allright','Allright',] greetingResponseB = ['bad','sucky','lame','not good','horrible','cruddy','bloody horrible','terrible','Bad','Sucky','Lame','Not good','Horrible','Cruddy','Bloody horrible','Not Good','Bloody Horrible','Terrible'] statusInputandResponseP = ['Good, how are you?','I\'m great, how are you?','i\'m good, how are you?','Good how are you?','I\'m great how are you?','i\'m good how are you?','Im great, how are you?','im good, how are you','Good, how are you','I\'m great, how are you','i\'m good, how are you','Im great, how are you','im good, how are you','Good, hbu?','I\'m great, hbu?','i\'m good, hbu?','Good hbu?','I\'m great hbu?','i\'m good hbu?','Im great, hbu?','im good, hbu','Good, hbu','I\'m great, hbu','i\'m good, hbu','Im great, hbu','im good, hbu','Good h…
score: -1
has answer: http://stackoverflow.com/a/48896809
answer count: 3
has title: Using append with a Variable in an if Statement Python

http://stackoverflow.com/a/48931850
type: Answer
has comment: http://stackoverflow.com/comment/84870519
has body: This code will work if all you filenames follow the pattern you described. filename = 'data_file_10572_2018-02-15-12-57-29.file' parts = filename.split('_') new_filename = '_'.join(parts[:2]) If alphabetical part fo file name has variable number of underscores it's better to use Regex. import re pattern = re.compile('_[0-9_-]{3,}.file$') re.sub(pattern, '', filename) Output: data_file Essentially, first, it creates a pattern that starts with _, followed by 3 or more numbers, _ or - and ends with .file. Then you replace the largest substring of you string that follows this pattern with an empty string.
score: 0
answers question: http://stackoverflow.com/q/48931681

http://stackoverflow.com/comment/84877376
type: AnswerComment
score: 0
type: Comment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165674/discussion-between-raw-dawg-and-dominik).
comment on: http://stackoverflow.com/a/48932552

http://stackoverflow.com/comment/84722998
comment on: http://stackoverflow.com/a/48859661
has text: Well...when you load the view you are making a GET request; however, your variable is passed in the path as a URL parameter not the extra data that comes along with other possible GET requests (i.e. a search bar's parameter). I'm sorry if that confused you more...
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/a/49683211
has comment: http://stackoverflow.com/comment/86379945
type: Answer
has comment: http://stackoverflow.com/comment/86463888
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/86415752
answers question: http://stackoverflow.com/q/48960514
downvote count: 0
has body: Did you compile your CSS? If it looks funnyou may need lessc CSS compiling (from https://www.odoo.com/documentation/8.0/setup/install.html ) We symlink node because some versions of debian/ubuntu don't agree on the bin name Install Node sudo apt install -y nodejs npm sudo ln -s /usr/bin/nodejs /usr/bin/node Compiling CSS If you install less, odoo will automatically compile the CSS sudo npm install -g less less-plugin-clean-css Consider blowing away the file cache: If the compilation had failed, sometimes you need to blow away the postgres cache, (thanks to sebalix for this tip): You can run this SQL query in postgres to let Odoo rebuild its CSS+JS assets + reload icons via dbeaver: DELETE FROM ir_attachment WHERE datas_fname SIMILAR TO '%.(js|css)'; DELETE FROM ir_attachment WHERE name='web_icon_data'; Then restart the server (assuming it was installed via ansible) sudo service odoo restart There's also files in ~/.local/share/Odoo/filestore you may want to temporarily move/rename Check postgres version Some versions of postgres are not supported, check psql --version and that you can download a backup of your database Check odoo version I've seen installs where odoo-bin --version returns 10 but the logs show odoo11 before every log line

http://stackoverflow.com/comment/84835734
type: Comment
comment on: http://stackoverflow.com/a/48914646
score: 0
type: AnswerComment
has text: You need the use the functions to write and read. Also don't use the shell for this

http://stackoverflow.com/q/48817828
has comment: http://stackoverflow.com/comment/84647666
type: Question
type: AnsweredQuestion
score: 1
tagged with: numpy
linked to: http://stackoverflow.com/q/37486502
has answer: http://stackoverflow.com/a/48821858
upvote count: 1
accepted answer: http://stackoverflow.com/a/48821858
answer count: 1
has title: .apply() a bivariate numpy() lambda function to an .expanding() window of a pandas DataFrame
tagged with: pandas
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84646956
downvote count: 0
has body: Consider this simple code (numpy.sum in loc_fun is a stand in for a more complicated bivariate function using numpy): import pandas import numpy def loc_fun(A, B): return numpy.sum(A[:-1] &gt; B[-1]) df = pandas.DataFrame(numpy.random.normal(0, 1, [100000, 2]), columns=['size_A', 'size_B']).cumsum(axis=0) df.expanding(2).apply(lambda x: loc_fun(x.size_A.values, x.size_B.values)) The last line in the code above results in an error I cannot make sense of. Basically, I would like to apply loc_fun to an expanding() window of the values in the columns.

http://stackoverflow.com/comment/84834276
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48913149
has text: Maybe you can use locality-sensitive hashing as discussed in [this SO question](https://stackoverflow.com/questions/25114338/approximate-string-matching-using-lsh)

http://stackoverflow.com/q/48887817
tagged with: iteration
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am trying to implement Algorithm 6 (and eventually Algorithm 7) of the following paper - https://arxiv.org/pdf/1610.03045.pdf Most of this seems fine but I don't understand why I am not achieving convergence in the $z$ variables. My code seems to fit with what is written in the pseudocode for Alg 6 so I am really not sure what is happening here but my belief is that it is a problem with the variables [z_{new}] or $z_{hat}$ as these should be achieving an increasingly better approximation yet the errors are actually increasing. def iterative_primal_dual_sketch_new(data, targets, left_sketch, right_sketch, offset, tolerance, max_iterations=10): '''Perform the vanilla iterative_primal_dual_sketching.''' X = data y = targets y = y[:,None] # change to (row, column) index not flat array _lambda = offset n, d = X.shape # initialise sketches nb. I have switched notation from the R in paper feature_sketch = right_sketch p = feature_sketch.shape[1] # same as in paper for Pi but needs to be transposed for right multiplication sample_sketch = left_sketch m = left_sketch.shape[1] # sketch products and parameters for iteration X_R = np.dot(X,feature_sketch) # just renaming to avoid unnecessary compute double_sketch = (0.5*n)*np.dot(sample_sketch, X_R) w_hat = np.zeros(shape=(d,1)) has_z_converged = False for t in range(max_iterations): k = 0 z = np.zeros(shape=(p,1)) while not has_z_converged: z0 = z print("iteration on (t,k) ({},{})".format(t,k)) print("start of loop: norm(z) = {}".format(norm(z0,2))) temp1 = (1/n)*(np.dot(X_R.T, y) -\ np.dot(X_R.T, np.dot(X,w_hat)) -\ np.dot(X_R.T, np.dot(X_R,z0))) temp2 = _lambda*np.dot(feature_sketch.T, w_hat) + _lambda*z0 temp3 = temp1 - temp2 print("temp1 shape {}".format(temp1.shape)) print("temp2 shape {}".format(temp2.shape)) print("temp3 shape {}".format(temp3.shape)) assert temp3.shape[0] == p # solve the linear system for z z_hat = np.linalg.solve(2*np.dot(double_sketch.T,double_sketch) \ +_lambda*np.eye(p),temp3) print("z_hat shape…
answer count: 0
tagged with: sketching
score: 1
upvote count: 1
type: Question
tagged with: algorithm
tagged with: matrix
downvote count: 0
has title: Not achieving convergence in iterative algorithm from paper

http://stackoverflow.com/q/48836940
type: Question
has comment: http://stackoverflow.com/comment/84678967
answer count: 1
has comment: http://stackoverflow.com/comment/84678944
has body: Say I have a packet that contains fields that are all hex values. How can I define a function that returns a packet where all of the hex values for the fields in the packet are inverted? Here is what I have so far: def complementPacket(pkt): ''' Function: complementPacket Purpose: Takes a packet as an input and inverts all bits in the packet. Return: Inverted packet of same structure as the input packet ''' retPkt = pkt while(pkt): # iterate through the packets for field in pkt.fields_desc: print(fmtToLen(field.fmt)) # converts scapy field.fmt to the number of bits for that field type # invert bits, assign to retPkt pkt = pkt.payload return retPkt The only solution I can think of would be to iterate through the packet and construct a new packet by taking the complement of all the fields. Is there a better way to do this? Given a packet, P, with hex (binary) values, I want to return ~P. Example: def customPacket(Packet): name = "myPacket" fields_desc = [XByteField("data", 1)] pkt = customPacket() pkt.show() will output that the value of 'data' is 0x1 complementedPkt = complementPacket(pkt) complementedPkt.show() will output that the value of 'data' is 0xE (0x1 = 0001, ~0001 = 1110, 1110 = 0xE)
tagged with: packet
tagged with: python
has title: How to invert the bits of a Scapy packet (complement of a packet)
has answer: http://stackoverflow.com/a/48837790
type: UnansweredQuestion
score: 0
tagged with: scapy
has comment: http://stackoverflow.com/comment/84746665
has comment: http://stackoverflow.com/comment/84679009
has comment: http://stackoverflow.com/comment/84746638

http://stackoverflow.com/comment/84666393
score: 0
type: Comment
has text: https://docs.python.org/3/ . You want to raise your own `Exception` with `call_main(y)`?
type: AnswerComment
comment on: http://stackoverflow.com/a/48830953

http://stackoverflow.com/a/48907758
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/118549611
type: Answer
accepted answer of: http://stackoverflow.com/q/48906173
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/118557190
answers question: http://stackoverflow.com/q/48906173
has body: Few things: I don't think you need __name__ == "__main__" bit DispatcherMiddleware does not have a run() method You don't really need to run it, gunicorn will do it for you DispatcherMiddleware expects an app as the first argument and optionally a dict of mounts. I believe you can set root app to None if you so desire. So I would try doing something like this: # hello_world_app.py @app.route("/") def hello(): return "Hello World!" # bye_world_app.py @app.route("/") def hello(): return "Bye World!" # wsgi.py from hello_world_app import app as hello_app from bye_world_app import app as bye_app from werkzeug.wsgi import DispatcherMiddleware application = DispatcherMiddleware(None, { '/hello': hello_app, '/bye': bye_app, }) Not sure if it's the absolute best way to do it, but it worked for me.

http://stackoverflow.com/q/48837777
has comment: http://stackoverflow.com/comment/84680732
type: Question
has comment: http://stackoverflow.com/comment/84680566
has answer: http://stackoverflow.com/a/48849993
score: 0
has comment: http://stackoverflow.com/comment/84680671
tagged with: pandas
answer count: 1
tagged with: pandas-to-sql
has title: pandas to_sql only writing first row to db
accepted answer: http://stackoverflow.com/a/48849993
has body: I am using the below code to read a tab delimited file into a postgres database enginestring = cfg.dbuser+":"+cfg.dbpwd+"@"+server.local_bind_host+":"+str(server.local_bind_port)+"/"+cfg.dbname engine = create_engine('postgresql://' + enginestring) rows = [] for line in smart_open.smart_open(key): ln = str(line.decode('utf-8')) fields = ln.split('\t') rows.append(fields) df = pd.DataFrame(rows, columns=cfg.df_colheaders) print(df.head) df.to_sql(name=table_name, con=engine, if_exists='append') The call to print returns the dataframe that I expect (i.e. [798624 rows x 133 columns]) and the call to to_sql doesn't fail, yet in the DB I see only one row of data with the correct columns...(same results if the table has been created before or not)
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48842320
has answer: http://stackoverflow.com/a/48843802
tagged with: python
upvote count: 4
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/49181149
has body: I have a square image, for example this one: and I would like to calculate the 1D average of the image for each radius from the position (0,0). I have written some code to do so, but first of all it very slow even for small images, secondly I see that there are also some problems with the idea behind it. Code is here: import matplotlib.pyplot as plt import numpy as np import collections from skimage import data image = data.coins() image = image[:,0:303] print(image.shape) projection = {} total_count = {} for x_i,x in enumerate(image): for y_i,y in enumerate(x): if round(np.sqrt(x_i**2+y_i**2),1) not in projection: projection[round(np.sqrt(x_i**2+y_i**2),1)] = y total_count[round(np.sqrt(x_i**2+y_i**2),1)] = 1 elif np.sqrt(round(np.sqrt(x_i**2+y_i**2),1)) in projection: projection[round(np.sqrt(x_i**2+y_i**2),1)] += y total_count[round(np.sqrt(x_i ** 2 + y_i ** 2), 1)] += 1 od = collections.OrderedDict(sorted(projection.items())) x, y = [],[] for k, v in od.items(): x.append(k) y.append(v/total_count[k]) plt.plot(x,y) plt.xlabel('Radius from (0,0)') plt.ylabel('Averaged pixel value') plt.show() The result of the code looks like this: Has anyone have some clue how to improve my the script? I also don't know why in some cases there are some spikes which have very small average value. I would really appreciate some hints. Thanks!
tagged with: average
has comment: http://stackoverflow.com/comment/84689112
type: Question
has comment: http://stackoverflow.com/comment/84689511
has answer: http://stackoverflow.com/a/48843835
has title: What is the best way to calculate radial average of the image with python?
accepted answer: http://stackoverflow.com/a/48843835
tagged with: algorithm
tagged with: matplotlib
score: 4
tagged with: image
answer count: 3
possible better answer: http://stackoverflow.com/a/49181149
linked to: http://stackoverflow.com/q/21242011
favorite count: 0

http://stackoverflow.com/comment/84810642
comment on: http://stackoverflow.com/a/48901107
score: 0
type: AnswerComment
has text: You are welcome. To find the name maybe you can use `recast.columns.get_level_values(level=0).unique()` ? (It will show you all the unique first level columns values)
type: Comment

http://stackoverflow.com/comment/84670033
type: Comment
has text: You didn't get the syntx exactly right for the dictionary comprehension. It should read like a `for` loop `{k: k+v for k, v in d.items()}`. Also, don't use the name `dict`, there's already a built-in function with that name.
score: 1
comment on: http://stackoverflow.com/q/48832823
type: QuestionComment

http://stackoverflow.com/comment/84747860
has text: What is `'CmSelectionCriteria'(...)` supposed to do?
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48872025

http://stackoverflow.com/comment/84837710
has text: or as a hidden variable in a form, and your "more info" button submits that form with target=_blank. The form target page script renders the more detailed results
comment on: http://stackoverflow.com/q/48897369
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48915751
has body: I'm trying to do this problem that I saw in a YouTube video and I get this error every time I try to import scikit-learn. I'm using Jupyter Notebook and I installed scikit-learn through Anaconda. This is the error message I get. I've already uninstalled and installed sckit-learn and scipy using conda isn't all multiple times but I always get the same result. Please, help.
tagged with: jupyter-notebook
favorite count: 0
upvote count: 2
has title: ImportError cannot import name '_ccallback_c'
tagged with: python
has comment: http://stackoverflow.com/comment/84837989
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49255870
tagged with: anaconda
tagged with: scipy
type: Question
has comment: http://stackoverflow.com/comment/84839580
answer count: 1
downvote count: 0
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/49255870

http://stackoverflow.com/q/48811196
accepted answer: http://stackoverflow.com/a/48811549
has body: I have two matrix: mx1 = np.matrix([[2,9,9],[2,5,8],[7,2,9]]) [[2 9 9] [2 5 8] [7 2 9]] mx2 = np.matrix([[7,1,3],[5,8,2],[6,9,5]]) [[7 1 3] [5 8 2] [6 9 5]] I would like to do something like the matrix product row by column but with sum. i.e., the resulting matrix element[1,1] should be calculated as: (2+7)+(9+5)+(9+6) = 38 element[1,2]: (2+1)+(9+8)+(9+9) = 38 and so on. Some smart way to do so?
has answer: http://stackoverflow.com/a/48812152
has comment: http://stackoverflow.com/comment/84626038
tagged with: python
has answer: http://stackoverflow.com/a/48811549
type: AnsweredQuestion
has title: sum of two matrix row by column
has answer: http://stackoverflow.com/a/48811554
type: Question
tagged with: numpy
tagged with: sum
has comment: http://stackoverflow.com/comment/84626216
score: 0
answer count: 3
possible better answer: http://stackoverflow.com/a/48811554

http://stackoverflow.com/q/48809682
has comment: http://stackoverflow.com/comment/84622835
has comment: http://stackoverflow.com/comment/84622920
type: AnsweredQuestion
tagged with: oop
has comment: http://stackoverflow.com/comment/84622749
downvote count: 3
has comment: http://stackoverflow.com/comment/84622718
accepted answer: http://stackoverflow.com/a/48809906
type: Question
tagged with: python-2.7
answer count: 2
tagged with: syntax-error
upvote count: 0
has comment: http://stackoverflow.com/comment/84622804
has comment: http://stackoverflow.com/comment/84622968
has title: Syntax error: cant assign to operator
has body: def addOp(self): i = math.sqrt(-1) addAnswer = (a + b*i) + (c + d*i) = (a + c) + (b + d)*i return addAnswer When I run my code it gives me an error on the 'addAnswer' line... I have tried inputting * when needed and adjusting the parentheses, but no help. Same goes for the code below as well def mutliplicationOp(self): multiAnswer = (a + b*i) * (c + d*i) = (a*c - b*d) + (b*c + a*d)*i return multiAnswer
tagged with: python
has comment: http://stackoverflow.com/comment/84622631
possible better answer: http://stackoverflow.com/a/48810262
favorite count: 0
has answer: http://stackoverflow.com/a/48809906
has answer: http://stackoverflow.com/a/48810262
has comment: http://stackoverflow.com/comment/84623108
score: -3

http://stackoverflow.com/q/48817876
has body: I've managed to query and get results for values from a list. But say i have the genres ["Action", "Comedy", "Romance"] in the list I am using to query. My code below returns all the records which are action, romance and comedy whereas I want it to return only the records that meet all three genres. How can I do this? The database has a field called genre in which there are multiple genres for each record. Code: with sqlite3.connect("animeData.db") as db: #anime database c = db.cursor() c.execute("select * from t where genre in %s" % repr(self.genreResults).replace('[','(').replace(']',')') ) #self.genreResults is the list containing the genres i want to query results = c.fetchall() print(results) db.commit() db.close() Output: Database: It's returning all animes which have genres of action and adventure whereas I only want it to return animes which have both. Any suggestions?
type: AnsweredQuestion
tagged with: sql
tagged with: sqlite
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84641080
type: Question
accepted answer: http://stackoverflow.com/a/48831557
tagged with: python
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84639821
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84662855
has title: SQL database query - return records which have all values from a list (Python)
has answer: http://stackoverflow.com/a/48831557

http://stackoverflow.com/q/48805501
upvote count: 2
has body: They use identical examples to illustrate both charts and I can not seem to spot any difference. Is there one?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48811398
score: 2
tagged with: plotly
type: Question
downvote count: 0
has title: Is there a difference between Plotly OHLC and Plotly Candlestick chart?
answer count: 1
favorite count: 0

http://stackoverflow.com/comment/84617504
type: QuestionComment
type: Comment
score: 2
has text: Did you try regenerating the .qm files since updating?
comment on: http://stackoverflow.com/q/48806568

http://stackoverflow.com/comment/84682951
type: QuestionComment
comment on: http://stackoverflow.com/q/48839120
has text: I am not getting any error message.
score: 0
type: Comment

http://stackoverflow.com/comment/84774061
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48884755
score: 0
has text: Possible duplicate of [html to .doc converter in Python?](https://stackoverflow.com/questions/4226095/html-to-doc-converter-in-python)

http://stackoverflow.com/a/48967962
has body: Try installing with --skip-keys python-wxtools --skip-keys google-mock. It worked for me.
answers question: http://stackoverflow.com/q/48960039
score: 4
upvote count: 4
downvote count: 0
type: Answer

http://stackoverflow.com/a/48874348
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
has body: You can set an ordering metadata in the Values model: class Value(models.Model): name = models.TextField() class Meta: ordering = ['name']
accepted answer of: http://stackoverflow.com/q/48845167
score: 1
answers question: http://stackoverflow.com/q/48845167

http://stackoverflow.com/comment/84726954
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48861545
has text: The reason why it's black is because it isn't read as a 16 bit array. I use ´gray = misc.imread('test.png')´ but my image is a 8 bit image. So maybe this is the Problem why your example doesn't work. So how can I read in a 16bit .png image?

http://stackoverflow.com/q/48856837
tagged with: python
has body: First of all I'll say that, as my code comments are in Spanish, I'll try to explain them in English even though the code is pretty obvious and easy to understand. Don't feel insulted if I'm explaining things that are too obvious :) So I'm trying to get all img from a website but it seems it just doesn't want to. I've read some similar articles but none seem to work. import requests from bs4 import BeautifulSoup as bs import os You can visit the web and see the html yourself. # url de las imgs url = 'https://dbz.space/cards/' Here request the web page for it to be parsed # descargamos la pagina para scrapear page = requests.get(url) soup = bs(page.text, 'html.parser') Here I search for all the images with that class # localizamos todas las imgs con esa clase image_tags = soup.findAll("img", {"class": "thumb on"}) Here i just look if the folder imgs exist and if it doesn't then create one to then go inside it # si no existe imgs lo creamos if not os.path.exists('imgs'): os.makedirs('imgs') # cambiamos de directorio os.chdir('imgs') A variable for then naming all images # para el nombre de la imagen x = 0 And finally the saving process # guardando imagenes for image in image_tags: try: url = image['src'] response = requests.get(url) if response.status_code == 200: with open('img-' + str(x) + '.jpg', 'wb') as f: f.write(requests.get(url).content) f.close() x += 1 print('Nueva imagen en carpeta') except: pass So, the imgs on the web are inside a div tag and they have the class "thumb on" and they also contain the src (obviously) link which is the one I want to get to my folder called "imgs"
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84717424
upvote count: 1
has comment: http://stackoverflow.com/comment/84717449
type: Question
has answer: http://stackoverflow.com/a/48870630
has title: trying to get all imgs from web python + bs4
score: -1
has comment: http://stackoverflow.com/comment/84717405
has answer: http://stackoverflow.com/a/48857251
answer count: 3
has answer: http://stackoverflow.com/a/48860023
favorite count: 0
tagged with: beautifulsoup
type: UnansweredQuestion
downvote count: 2

gmail
type: Tag
tags question: http://stackoverflow.com/q/48946616
tag name: gmail

http://stackoverflow.com/comment/84786855
type: QuestionComment
has text: Yes. Monthly sales vs Product price and Geographic Region vs No of customers
comment on: http://stackoverflow.com/q/48885074
score: 0
type: Comment

http://stackoverflow.com/comment/84805188
comment on: http://stackoverflow.com/a/48897620
type: Comment
has text: Thanks for clarifying things up. I already browsed that link several times, and I am still unsure what functions replace the 5 lines in my `input_parser` function. Could you give some hint as to which functions should replace it so it conforms to the TF declarative model?
score: 0
type: AnswerComment

http://stackoverflow.com/a/48827395
has comment: http://stackoverflow.com/comment/84659414
answers question: http://stackoverflow.com/q/48827361
upvote count: 4
score: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/91931721
has comment: http://stackoverflow.com/comment/91931679
has comment: http://stackoverflow.com/comment/91931929
has body: Use helper Series: df = pd.concat({k:pd.Series(v) for k, v in d.items()}).unstack().astype(float).sort_index() df.columns = 'col1 col2 col3'.split() Another solution is convert not list values to one element list and then DataFrame.from_dict: d = {k:v if isinstance(v, list) else [v] for k, v in d.items()} df = pd.DataFrame.from_dict(d, orient='index').astype(float).sort_index() df.columns = 'col1 col2 col3'.split() print (df) col1 col2 col3 a 1.2 1.0 1.1 b 5.8 1.0 2.0 c 9.5 0.9 NaN h 1.9 6.1 NaN l 1.0 8.0 NaN o 5.0 NaN NaN p 3.0 1.1 NaN v 1.8 0.0 NaN
type: Answer
has comment: http://stackoverflow.com/comment/91931992
accepted answer of: http://stackoverflow.com/q/48827361

http://stackoverflow.com/comment/84762792
has text: Thanks for the explanation!
type: Comment
comment on: http://stackoverflow.com/a/48876319
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84943113
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48942027
has text: also, setting event to none runs the program not when the canvas is clicked but when the program begins

http://stackoverflow.com/q/48806737
upvote count: 0
has answer: http://stackoverflow.com/a/48807100
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84616336
has answer: http://stackoverflow.com/a/48806773
score: -4
has title: TypeError: argument of type 'int' is not iterable - python 3.5
type: Question
has comment: http://stackoverflow.com/comment/84616455
tagged with: data-transform
has comment: http://stackoverflow.com/comment/84616131
has comment: http://stackoverflow.com/comment/84616140
has comment: http://stackoverflow.com/comment/84616551
answer count: 2
downvote count: 4
has body: While doing data transformation, I am getting "TypeError: argument of type 'int' is not iterable", I am using python 3.5 This is the code snippet, for idx, val in enumerate(aircrashdf.Destination): if ',' in val: destination = val.split(",") original = destination[0].strip() aircrashdf.iloc[idx,10] = original This is the output Traceback (most recent call last): File "/home/drogon/PycharmProjects/aircrashes.py", line 151, in &lt;module&gt; if ',' in val: TypeError: argument of type 'int' is not iterable What could be the problem?

http://stackoverflow.com/q/48813922
tagged with: python
type: AnsweredQuestion
has body: I can't figure out how to convert x and y into an integer coming from a string import turtle t = turtle.Turtle() s = turtle.Screen() t.penup() t.speed(0) def draw_grid(): count = 0 distance = 0 while count &lt; 5: t.goto(0, distance) for i in range(5): t.dot() t.fd(100) count += 1 distance += 100 draw_grid() def get_mouse_click_coor(x, y): Something is happening here?? Im not sure, and keep giving me this error: TypeError: '&lt;' not supported between instances of 'int' and 'str' X = int(x) Y = int(y) if -20 &lt; X &lt; 20 and 380 &gt; Y &gt; 20: t.penup() if 80 &gt; Y &gt; 20: t.goto(0,0) t.pendown() t.goto(0,100) if 180 &gt; Y &gt; 120: t.goto(0, 100) t.pendown() t.goto(0, 200) if 280 &gt; Y &gt; 220: t.goto(0, 200) t.pendown() t.goto(0, 300) if 380 &gt; Y &gt; 320: t.goto(0, 300) t.pendown() t.goto(0, 400) turtle.onscreenclick(get_mouse_click_coor) s.mainloop() s.done()
has comment: http://stackoverflow.com/comment/84631477
downvote count: 0
accepted answer: http://stackoverflow.com/a/48815357
score: 1
type: Question
has answer: http://stackoverflow.com/a/48815357
tagged with: int
upvote count: 1
has comment: http://stackoverflow.com/comment/84631570
answer count: 1
tagged with: string
favorite count: 0
has title: Getting TypeError comparing coordinates in Python turtle event handler
tagged with: turtle-graphics

http://stackoverflow.com/comment/84711288
type: Comment
type: QuestionComment
has text: Is that what you are looking for? https://github.com/karulis/pybluez/tree/master/bluetooth
score: 0
comment on: http://stackoverflow.com/q/48853919

http://stackoverflow.com/a/48911498
type: Answer
downvote count: 0
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48911071
has body: Another way df[df.eq(20)].stack() Out[1220]: 1 C 20.0 dtype: float64

http://stackoverflow.com/comment/84786018
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48890152
has text: This is the error : ValueError: invalid literal for int() with base 10: ''

http://stackoverflow.com/q/48834156
answer count: 1
has comment: http://stackoverflow.com/comment/84672916
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84672825
linked to: http://stackoverflow.com/q/11194110
type: Question
has comment: http://stackoverflow.com/comment/84672780
has title: AI Python - TypeError: 'int' object has no attribute '__getitem__'
tagged with: python
has answer: http://stackoverflow.com/a/48834244
score: 0
has body: In the AI code I am working on, the program has to check if a square on a chessboard is empty. This is represented by a nxn matrix of zeros, and in this part of the code the program checks if the current square (coordinate in the array) is empty: # Check if a square is empty def square_is_empty(i,j, state): if state[i][j] == 0: return True return False However, I get an output error saying: in square_is_empty if state[i][j] == 0: TypeError: 'int' object has no attribute '__getitem__' Despite having read multiple answers about the same issue, I still haven't managed to fix mine! Thank you

http://stackoverflow.com/comment/84763021
comment on: http://stackoverflow.com/q/48879482
score: 1
has text: @DeliriousLettuce Loving the username...
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48831227
favorite count: 0
has answer: http://stackoverflow.com/a/48831295
tagged with: return
has comment: http://stackoverflow.com/comment/84666589
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I want to print and return a value, but cant seem to find my way around it. I have this as of now: def collatz_number(n): # If n is not a positive integer if n&lt;=0: return "Only positive integers please" # Even numbers elif n % 2 == 0: return n // 2 # If n is 1 elif n == 1: return 1 # Odd number elif n % 2 == 1: return 3*n+1 I want it to function like this: &gt;&gt;&gt;a = collatz_number(5) 16 &gt;&gt;&gt; print(a) 16 My problem is that I either print 16 two times, if I use print under each if statement (the code would then print the same number the if statement returns), or as it is with this code that you see - I only get 16 after print(a), but not after a = collatz_number(n). How can I make this code function as I stated above: have it print and return the collatz number of n such that it works like this(as stated above): &gt;&gt;&gt; a = collatz_number(n) 16 &gt;&gt;&gt; print(a) 16 Im sorry for the bad formulation
has answer: http://stackoverflow.com/a/48831460
score: 1
has answer: http://stackoverflow.com/a/48831329
type: Question
has title: print and return python
answer count: 3
downvote count: 0

http://stackoverflow.com/comment/84920266
type: QuestionComment
comment on: http://stackoverflow.com/q/48954831
has text: @SoZettaSho as far as I know it doesn't. It loads some parameters from a file. I know it is able to access and read the file.
score: 0
type: Comment

http://stackoverflow.com/q/48955150
tagged with: python
has body: I'm trying to use the API of a media ID registry, the EIDR, to download tv show information. I'd like to be able to query many shows automatically. I'm not experienced in how to use APIs, and the documentation for this specific one is very opaque. I'm using python 3 (requests library) in Ubuntu 16.04. I tried sending a request for a specific tv show. I took the headers and parameters information from the browser, as in, I did the query from the browser (I looked up 'anderson cooper 360' from this page) and then looked at the information in the "network" tab of the browser's page inspector. I used the following code: import requests url = 'https://resolve.eidr.org/EIDR/query/' headers = {'Host': 'ui.eidr.org', 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:58.0) \ Gecko/20100101 Firefox/58.0', \ 'Accept': '*/*', \ 'Accept-Language': 'en-US,en;q=0.5', 'Accept-Encoding': 'gzip, deflate, br', \ 'Referer': 'https://ui.eidr.org/search/results/19c70c63d73790b86f3fb385f2a9b3f4', \ 'Cookie': 'ci_session=f4tnbi8qm7oaq30agjtn8p69j91s4li4; \ _ga=GA1.2.1738620664.1519337357; _gid=GA1.2.1368695940.1519337357; _gat=1', \ 'Connection': 'keep-alive'} params = {'search_page_size':25, 'CustomAsciiSearch[_v]':1, \ 'search_type':'content', 'ResourceName[_v]':'anderson cooper 360', \ 'AlternateResourceNameAddition[_v]':1, \ 'AssociatedOrgAlternateNameAddition[_v]':1, 'Status[_v]':'valid'} r = requests.post(url, data=params, headers=headers) print(r.text) I get this response that basically says it's an invalid request: <?xml version="1.0" encoding="UTF-8"?> \ <Code>3 invalid request Now, I read in an answer to this Stackoverflow question that I should somehow use a session object. The code suggested in the answer by Padraic Cunningham was this: headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:46.0) \ Gecko/20100101 Firefox/46.0','X-Requested-With': 'XMLHttpRequest', \ "referer": "https://www.hackerearth.com/challenges/"} with requests.Session() as s: s.get("ht…
has answer: http://stackoverflow.com/a/48959322
score: 1
upvote count: 1
tagged with: python-requests
tagged with: post
type: Question
tagged with: session
tagged with: api
linked to: http://stackoverflow.com/q/37532409
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
has title: POST request (python) - invalid request

http://stackoverflow.com/comment/84914295
type: AnswerComment
type: Comment
has text: @JackHudgins, please note the change in the `data = ...` line, I've changed it from a list to a dictionary.
comment on: http://stackoverflow.com/a/48953747
score: 0

http://stackoverflow.com/q/48818373
downvote count: 0
linked to: http://stackoverflow.com/q/18084698
has answer: http://stackoverflow.com/a/54669768
tagged with: scipy
linked to: http://stackoverflow.com/q/39332053
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48819533
has answer: http://stackoverflow.com/a/48848654
tagged with: image
score: 12
has title: Interpolate between two images
answer count: 3
favorite count: 0
has body: I'm trying to interpolate between two images in Python. Images are of shapes (188, 188) I wish to interpolate the image 'in-between' these two images. Say Image_1 is at location z=0 and Image_2 is at location z=2. I want the interpolated image at location z=1. I believe this answer (MATLAB) contains a similar problem and solution. Creating intermediate slices in a 3D MRI volume with MATLAB I've tried to convert this code to Python as follows: from scipy.interpolate import interpn from scipy.interpolate import griddata # Construct 3D volume from images # arr.shape = (2, 182, 182) arr = np.r_['0,3', image_1, image_2] slices,rows,cols = arr.shape # Construct meshgrids [X,Y,Z] = np.meshgrid(np.arange(cols), np.arange(rows), np.arange(slices)); [X2,Y2,Z2] = np.meshgrid(np.arange(cols), np.arange(rows), np.arange(slices*2)); # Run n-dim interpolation Vi = interpn([X,Y,Z], arr, np.array([X1,Y1,Z1]).T) However, this produces an error: ValueError: The points in dimension 0 must be strictly ascending I suspect I am not constructing my meshgrid(s) properly but am kind of lost on whether or not this approach is correct. Any ideas? ---------- Edit ----------- Found some MATLAB code that appears to solve this problem: Interpolating Between Two Planes in 3d space I attempted to convert this to Python: from scipy.ndimage.morphology import distance_transform_edt from scipy.interpolate import interpn def ndgrid(*args,**kwargs): """ Same as calling ``meshgrid`` with *indexing* = ``'ij'`` (see ``meshgrid`` for documentation). """ kwargs['indexing'] = 'ij' return np.meshgrid(*args,**kwargs) def bwperim(bw, n=4): """ perim = bwperim(bw, n=4) Find the perimeter of objects in binary images. A pixel is part of an object perimeter if its value is one and there is at least one zero-valued pixel in its neighborhood. By default the neighborhood of a pixel is 4 nearest pixels, but if `n` is set to 8 the 8 nearest pixels will be considered. Parameters ---------- bw : A black-and-white image n : C…
upvote count: 12
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/27286537
linked to: http://stackoverflow.com/q/28667286

http://stackoverflow.com/comment/84751450
has text: check the values you are trying to compare, mostly, check their type
comment on: http://stackoverflow.com/q/48873781
type: QuestionComment
type: Comment
score: 0

http://stackoverflow.com/comment/84628995
type: AnswerComment
comment on: http://stackoverflow.com/a/48811715
type: Comment
has text: You're right, it works on the subsample as provided. Must be something wrong when I try to scale it up. I'll figure it out.
score: 0

http://stackoverflow.com/a/48842667
score: 1
answers question: http://stackoverflow.com/q/48842535
has body: The problem is that pygame.event.get() clears all events from the event queue, so when your player calls it, all events are already gone. From the docs This will get all the messages and remove them from the queue. If a type or sequence of types is given only those messages will be removed from the queue. You can solve this by specifying which events should be removed from the event queue e.g. for event in pygame.event.get(QUIT): GameQuit = True The other events should still be in the queue for your player to use
upvote count: 1
type: Answer
downvote count: 0

http://stackoverflow.com/q/48935920
has comment: http://stackoverflow.com/comment/84881471
tagged with: discord.py
has comment: http://stackoverflow.com/comment/84878819
has comment: http://stackoverflow.com/comment/84878658
has comment: http://stackoverflow.com/comment/85003495
score: -1
has body: i'm trying to make it so when ever you do the invite command it will make a brand new invite to the server with unlimited uses and never expires, this is the current code i've made but doesn't work and i'm struggling to work-out why, I've looked online and found nothing I hope you guys can all help :) @bot.command(pass_context=True) async def invite(ctx): invitelinknew = await bot.create_invite(destination = ctx.message.channel, xkcd = True, max_uses = 100) embed=discord.Embed(title="Discord Invite Link", description=invitelinknew, color=0xf41af4) embed.set_footer(text="Discord server invited link.") await bot.say(embed=embed)
type: Question
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84878825
tagged with: python
has title: discord.py new invite link
has answer: http://stackoverflow.com/a/49162177
type: UnansweredQuestion
downvote count: 2
upvote count: 1

http://stackoverflow.com/q/48934539
has body: Currently, when 500 errors occur I show the user my custom 500.html error page. The app is used by both administrators and clients, which users are respectively in groups "operator" and "client". The information shown depends on that group. I would like to apply that concept to the error page. I would like to show the same Traceback error shown when DEBUG = True (not necessary the same style) when logged user is from group "operator". I guess there will be an attribute in the request that I can pass through the template and print the errors, but I can't find out which attribute is that. This is the function I use to render the 500.html page: def error_500(request): data = {} if request.user.groups.filter(name='operator').exists(): # fill the data dict with the traceback/errors return render(request,'app/errors/500.html', data) Thanks in advance.
has comment: http://stackoverflow.com/comment/84882199
type: Question
has title: How display request error in custom django admin error page
score: 0
has comment: http://stackoverflow.com/comment/84877118
tagged with: python
tagged with: django-templates
answer count: 0
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/84748460
type: Comment
comment on: http://stackoverflow.com/a/48872089
score: 0
type: AnswerComment
has text: You would need to define it somewhere with ``` def CmSelectionCriteria(): <insert function logic here> ```

http://stackoverflow.com/q/48900647
has comment: http://stackoverflow.com/comment/84806762
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84806644
has comment: http://stackoverflow.com/comment/84806701
has answer: http://stackoverflow.com/a/48901463
tagged with: python
tagged with: tweepy
score: 0
type: UnansweredQuestion
upvote count: 1
has title: JSON load twitter API error
downvote count: 1
tagged with: http://stackoverflow.com/tag/json
tagged with: twitter
has body: I have used tweepy user timeline API to extract information for some users. Here is the link to the file. The content of the file is in string format. I tried to load the same using JSON.loads(&lt;string&gt;) but it is showing the error ValueError: Expecting property name: line 1 column 2 (char 1) I need to make the string to work as a dict/json so that I can iterate on the keys.
type: Question

http://stackoverflow.com/q/48917141
downvote count: 0
has answer: http://stackoverflow.com/a/48919516
favorite count: 0
tagged with: python
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48919516
score: 1
has title: Create Pandas DataFrame from dictionary with list, tuple or dict as a single entry value
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48917241
possible better answer: http://stackoverflow.com/a/48917241
tagged with: pandas
has answer: http://stackoverflow.com/a/48917732
has body: I have a dictionary data = { 'x' : 1, 'y' : [1,2,3], 'z' : (4,5,6), 'w' : {1:2, 3:4} } I'd like to construct a Pandas DataFrame such that the list and tuple do not get broadcasted: df = pd.DataFrame(some_transformation(data), index=['a']) to get df = x y z w a 1 (1,2,3) (4,5,6) (1,2,3,4) Or some sort of flattening and/or string-fy of the list/tuple/dict. What is the easiest / most efficient way of doing so, without having to go down the exact data structure of each dictionary entry?
has answer: http://stackoverflow.com/a/48917274

http://stackoverflow.com/a/48962422
score: 0
answers question: http://stackoverflow.com/q/48962292
type: Answer
has body: If your file is like this abcd:1234 abcd:abc40 pizd:1234 adcd:abc40 Then with open('p.txt', 'r+') as f: mylist = f.read().splitlines() print (mylist) data = [x.rstrip().split(':') for x in mylist] print (data) Output ['abcd:1234', 'abcd:abc40', 'pizd:1234', 'adcd:abc40'] [['abcd', '1234'], ['abcd', 'abc40'], ['pizd', '1234'], ['adcd', 'abc40']]

http://stackoverflow.com/q/48841804
type: AnsweredQuestion
score: 0
has body: I've been searching for it but could not find anything on the net on this topic. When I'm working on a programm in python 3.5 which imports tkinter or pyglet I'm perfectly able to start it from the command line on my Linux Mint installation. As soon as I try to start it from pycharm or Visual Studio Code I get an error. It is for tkinter: Traceback (most recent call last): File "/home/b...", line 3, in &lt;module&gt; import tkinter as tk File "/usr/lib/python3.5/tkinter/__init__.py", line 35, in &lt;module&gt; import _tkinter # If this fails your Python may not be configured for Tk ImportError: No module named '_tkinter' Both, the tkinter and the pyglet script, are working when they are started from idle3 (with F5). Can anyone help me out? Best B.
linked to: http://stackoverflow.com/q/76105218
accepted answer: http://stackoverflow.com/a/49231335
type: Question
has title: python 3 no module named _tkinter
linked to: http://stackoverflow.com/q/5459444
has comment: http://stackoverflow.com/comment/84688476
has comment: http://stackoverflow.com/comment/84687619
has comment: http://stackoverflow.com/comment/134266778
answer count: 1
has answer: http://stackoverflow.com/a/49231335
tagged with: linux
tagged with: python

django
tags question: http://stackoverflow.com/q/48918452
tags question: http://stackoverflow.com/q/48835267
tags question: http://stackoverflow.com/q/48847905
tags question: http://stackoverflow.com/q/48835946
tags question: http://stackoverflow.com/q/48884821
tags question: http://stackoverflow.com/q/48886381
tags question: http://stackoverflow.com/q/48832773
tags question: http://stackoverflow.com/q/48944520
tags question: http://stackoverflow.com/q/48943862
tags question: http://stackoverflow.com/q/48870489
tags question: http://stackoverflow.com/q/48834945
tags question: http://stackoverflow.com/q/48826287
tags question: http://stackoverflow.com/q/48859515
tags question: http://stackoverflow.com/q/48845167
tags question: http://stackoverflow.com/q/48873139
tags question: http://stackoverflow.com/q/48897947
tags question: http://stackoverflow.com/q/48849928
tags question: http://stackoverflow.com/q/48959852
tags question: http://stackoverflow.com/q/48839376
tags question: http://stackoverflow.com/q/48862256
tags question: http://stackoverflow.com/q/48896653
tags question: http://stackoverflow.com/q/48949974
tags question: http://stackoverflow.com/q/48888351
tags question: http://stackoverflow.com/q/48959112
tags question: http://stackoverflow.com/q/48923219
tags question: http://stackoverflow.com/q/48817433
tags question: http://stackoverflow.com/q/48833259
tags question: http://stackoverflow.com/q/48841239
tags question: http://stackoverflow.com/q/48919241
tags question: http://stackoverflow.com/q/48805477
tags question: http://stackoverflow.com/q/48929153
tags question: http://stackoverflow.com/q/48961622
tags question: http://stackoverflow.com/q/48842253
tags question: http://stackoverflow.com/q/48841407
tags question: http://stackoverflow.com/q/48942725
tags question: http://stackoverflow.com/q/48934539
tags question: http://stackoverflow.com/q/48872885
tags question: http://stackoverflow.com/q/48935764
tags question: http://stackoverflow.com/q/48840076
tags question: http://stackoverflow.com/q/48825929
tags question: http://stackoverflow.com/q/48913388
tags question: http://stackoverflow.com/q/48842558
tags question: http://stackoverflow.com/q/48845873
tags question: http://stackoverflow.com/q/48928813
tags question: http://stackoverflow.com/q/48874556
tags question: http://stackoverflow.com/q/48875849
tags question: http://stackoverflow.com/q/48959563
tags question: http://stackoverflow.com/q/48926288
tags question: http://stackoverflow.com/q/48835978
tags question: http://stackoverflow.com/q/48869667
type: Tag
tags question: http://stackoverflow.com/q/48810468
tags question: http://stackoverflow.com/q/48894535
tags question: http://stackoverflow.com/q/48810094
tags question: http://stackoverflow.com/q/48895374
tags question: http://stackoverflow.com/q/48852092
tags question: http://stackoverflow.com/q/48862106
tags question: http://stackoverflow.com/q/48844877
tags question: http://stackoverflow.com/q/48901934
tags question: http://stackoverflow.com/q/48887001
tags question: http://stackoverflow.com/q/48804687
tags question: http://stackoverflow.com/q/48895833
tags question: http://stackoverflow.com/q/48920949
tags question: http://stackoverflow.com/q/48961857
tags question: http://stackoverflow.com/q/48834534
tags question: http://stackoverflow.com/q/48841782
tags question: http://stackoverflow.com/q/48960764
tags question: http://stackoverflow.com/q/48842064
tags question: http://stackoverflow.com/q/48843780
tags question: http://stackoverflow.com/q/48882313
tags question: http://stackoverflow.com/q/48910214
tags question: http://stackoverflow.com/q/48947777
tags question: http://stackoverflow.com/q/48907467
tags question: http://stackoverflow.com/q/48958007
tags question: http://stackoverflow.com/q/48846365
tags question: http://stackoverflow.com/q/48876511
tags question: http://stackoverflow.com/q/48890780
tags question: http://stackoverflow.com/q/48958400
tags question: http://stackoverflow.com/q/48947270
tags question: http://stackoverflow.com/q/48867604

http://stackoverflow.com/comment/84619226
comment on: http://stackoverflow.com/a/48807996
type: AnswerComment
score: 0
type: Comment
has text: i got the answer it should be d= d.reshape(28,28)@Cezary.Sz

http://stackoverflow.com/comment/84875572
has text: `object has no attribute 'text'"`
comment on: http://stackoverflow.com/a/48934206
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48824396
has answer: http://stackoverflow.com/a/48824462
has answer: http://stackoverflow.com/a/48824525
has answer: http://stackoverflow.com/a/48824646
downvote count: 0
answer count: 7
has body: I want to overwrite the 'magicians' list by putting 'the Great' after each item. It works if I assign the new items to a new list with pop(), making the old one empty, and by appending back to it the new names. code: for great in greatlist: mages.append(great) But why doesnt simply copying it over work? The results is an empty 'mages' list. mages=greatlist[:] Here the whole code: magicians=['feka','kuka','szuka'] #puts 'the Great' after every list element name def make_great(mages): greatlist=[] while mages: uj=mages.pop() greatlist.append(uj + ", the Great") # for great in greatlist: # mages.append(great) mages=greatlist[:]
possible better answer: http://stackoverflow.com/a/48824646
favorite count: 0
has title: Python copying list in a function
has comment: http://stackoverflow.com/comment/84652375
accepted answer: http://stackoverflow.com/a/48824525
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84661406
has answer: http://stackoverflow.com/a/48824603
has answer: http://stackoverflow.com/a/48824709
has answer: http://stackoverflow.com/a/48824547
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48824596
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84652315

http://stackoverflow.com/comment/84713019
type: Comment
type: QuestionComment
has text: don't put a solution into the question. Post it as an answer instead. https://stackoverflow.com/help/self-answer
comment on: http://stackoverflow.com/q/48848628
score: 0

http://stackoverflow.com/comment/84819669
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48906833
type: QuestionComment
has text: What is the code that you mentioned have you written?

http://stackoverflow.com/comment/84884101
type: Comment
has text: How can an RGB pixel have the value [136, 136, 0, 255]? The imported picture has a shape (h, w, 3), at least in my IDE.
score: 0
comment on: http://stackoverflow.com/q/48938086
type: QuestionComment

http://stackoverflow.com/q/48869529
has body: I hope this is not a redundant question, but I was not able to find a proper answer and tutorial. I am currently learning Data Science and therefore use kaggle competition for practice and jupyter notebook to tackle them (as it is visually more appealing to me). Now I stumbled upon an example kernel (see: http://nbviewer.jupyter.org/github/agconti/kaggle-titanic/blob/master/Titanic.ipynb#Data-Handling) is using comments, links and illustrations between his codes to give more context. Is anybody aware of how to write such comments and remarks within jupyter? If so, do you have an online resource where I could learn this? Thanks a bunch!
tagged with: jupyter-notebook
favorite count: 0
upvote count: 12
has answer: http://stackoverflow.com/a/48869658
answer count: 5
linked to: http://stackoverflow.com/q/4823468
type: UnansweredQuestion
tagged with: kaggle
tagged with: python
has comment: http://stackoverflow.com/comment/84743343
downvote count: 0
has comment: http://stackoverflow.com/comment/84742935
type: Question
has answer: http://stackoverflow.com/a/68901387
has answer: http://stackoverflow.com/a/64693584
linked to: http://stackoverflow.com/q/36288670
has comment: http://stackoverflow.com/comment/84743055
score: 12
has answer: http://stackoverflow.com/a/59646511
has answer: http://stackoverflow.com/a/74753817
has title: Inserting comments into jupyter notebook

http://stackoverflow.com/comment/84729283
type: AnswerComment
has text: It's coming in blank "[ ]" from the form to the views
type: Comment
comment on: http://stackoverflow.com/a/48861475
score: 0

http://stackoverflow.com/a/48864134
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48857015
type: Answer
answers question: http://stackoverflow.com/q/48857015
score: 2
upvote count: 2
has body: You can pass the API key using "key" parameter. Example: search_list_by_keyword(client, part='snippet', maxResults=25, q='surfing', key="YOUR_API_KEY", type='') Examples using CURL: # curl URL: curl -i -G -d "part=snippet&amp;maxResults=25&amp;q=surfing&amp;key={YOUR_API_KEY}" https://www.googleapis.com/youtube/v3/search # HTTP URL: GET https://www.googleapis.com/youtube/v3/search?part=snippet &amp;maxResults=25 &amp;q=surfing &amp;key={YOUR_API_KEY}

http://stackoverflow.com/a/48849682
answers question: http://stackoverflow.com/q/48849577
type: Answer
upvote count: 1
score: 1
has body: If I understand your question correctly, the module schedule might be what you are looking for. How do I get a Cron like scheduler in Python? import schedule import time def job(): print("I'm working...") schedule.every(10).minutes.do(job) schedule.every().hour.do(job) schedule.every().day.at("10:30").do(job) while 1: schedule.run_pending() time.sleep(1)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48849577

http://stackoverflow.com/q/48833908
has answer: http://stackoverflow.com/a/48834239
favorite count: 0
has comment: http://stackoverflow.com/comment/84673571
tagged with: python-3.x
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84672285
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84672665
has answer: http://stackoverflow.com/a/70562256
upvote count: 1
tagged with: python
downvote count: 1
has body: I am making a tkinter code that uses button widget but when I press the button, it stays pushed until the function which is executed on button press is not completed. I want the button to be released immediately and execute the function. Here is a code that shows a good example of the happening: from tkinter import * import time root = Tk() root.geometry('100x100+100+100') # size/position of root def callback(): # this function will run on button press print('Firing in 3') time.sleep(3) # wait for 3 seconds def main(): #function 'main' b = Button(root, text="ᖴIᖇE", width=10,height=2, command=callback)# setting the button b["background"] = 'red' #button color will be red b["activebackground"] = 'yellow' #button color will be yellow for the time when the button will not be released b.place(x=25,y=25) #placing the button main() # using function 'main' mainloop()
has comment: http://stackoverflow.com/comment/84673595
has comment: http://stackoverflow.com/comment/84673153
has answer: http://stackoverflow.com/a/62247120
has comment: http://stackoverflow.com/comment/108140130
type: Question
has comment: http://stackoverflow.com/comment/84674376
tagged with: button
has comment: http://stackoverflow.com/comment/84672920
has comment: http://stackoverflow.com/comment/84673005
has comment: http://stackoverflow.com/comment/84672703
score: 0
answer count: 3
has title: Tkinter button stays pressed
has comment: http://stackoverflow.com/comment/84674360

http://stackoverflow.com/comment/84681099
type: Comment
has text: you might need to parse it in another constructor
comment on: http://stackoverflow.com/q/48838289
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84803745
score: 0
type: Comment
type: QuestionComment
has text: Bryan, thanks. I shortened the code and explained that answer only to the first question is enough. Other questions are optional, though I would appreciate answers to them too. )
comment on: http://stackoverflow.com/q/48862213

http://stackoverflow.com/comment/84803337
type: Comment
type: QuestionComment
has text: can explain bit more about your random_method()
score: 1
comment on: http://stackoverflow.com/q/48898959

http://stackoverflow.com/comment/84760135
comment on: http://stackoverflow.com/q/48878059
type: Comment
type: QuestionComment
has text: Possible duplicate of [How to download image using requests](https://stackoverflow.com/questions/13137817/how-to-download-image-using-requests)
score: 1

http://stackoverflow.com/comment/84876975
comment on: http://stackoverflow.com/q/48934807
has text: Although, I would just totally rethink whatever is going on with `address_fields_dest`... that looks like a `str` representation fo a `dict`, how did that get in there in the first place?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48827728
has comment: http://stackoverflow.com/comment/84659754
accepted answer of: http://stackoverflow.com/q/48827148
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48827148
has comment: http://stackoverflow.com/comment/84659575
has body: write self.msg.buttonClicked.connect(self.Okpressed) before self.myfunc.run() If you call run function before subscribing click event, curse will stuck into infinite while loop. so your click event never subscribed. First subscribe click event and then call "run" function of "myfunc" And yes never do this - from PyQt4.QtGui import * from PyQt4.QtCore import * Its vbad programming practice. You can write like from PyQt4 import QtGui And use into code like QtGui.QMessagebox
score: 2
upvote count: 2

http://stackoverflow.com/comment/84801273
score: 0
type: Comment
type: QuestionComment
has text: I can see one missing bracket, with properly formatted code syntax errors are much easier to spot
comment on: http://stackoverflow.com/q/48897876

http://stackoverflow.com/q/48885401
accepted answer: http://stackoverflow.com/a/48885571
tagged with: python
downvote count: 6
type: AnsweredQuestion
has title: How to find and replace in 2 txt files with Python
type: Question
has comment: http://stackoverflow.com/comment/84777330
has answer: http://stackoverflow.com/a/48885571
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84777477
has body: i would like to search and replace Ids in two different txt files. So i have those .txt files. OLDIDS.txt which seems like: 12F 130 132 106 100 ... and the other file MASTERIDS.txt where the old and new Ids where splittet in columns like: (LEFT old ids, RIGHT new ids) 100 132 12F 1FF 106 256 ... ... What I want to do is to open OLDIDS.txt like f2 = open('OLDIDS.txt', 'w') and search for the first id in the first line (which is 12F) find this in the second line of MASTERIDS.txt and write the new ID 1FF to the second line of newFile.txt.
has comment: http://stackoverflow.com/comment/84775412
score: -6
favorite count: 0

http://stackoverflow.com/q/48859452
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/61969504
tagged with: cython
type: Question
tagged with: mypy
upvote count: 9
score: 9
answer count: 1
downvote count: 0
favorite count: 0
has title: How to enable PyCharm Type Checker feature for cython(.pyx) file?
has body: It seems python type checker in PyCharm automatically works for .py files.. but not for .pyx files. Is there any way to enable type checker for .pyx files in PyCharm? Also, is there any way to use mypy with cython files (.pyx files)?
tagged with: python
tagged with: pycharm

http://stackoverflow.com/comment/84864547
type: QuestionComment
has text: Might be of interest: https://erikbern.com/2018/02/15/new-benchmarks-for-approximate-nearest-neighbors.html
score: 1
comment on: http://stackoverflow.com/q/48887912
type: Comment

http://stackoverflow.com/comment/84850093
type: AnswerComment
type: Comment
has text: @Chris_Rands you're right, it does. What does str.split use for default? \t and \n?
score: 0
comment on: http://stackoverflow.com/a/48910838

http://stackoverflow.com/comment/84886278
has text: I'll go ahead and say that you were not on the right track. Abandon the old method. Don't throw good time after bad. I answered with one problem, but honestly, I can't even figure out what you're going for. You have something that works, move on.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48939473
score: 1

http://stackoverflow.com/comment/106276421
type: AnswerComment
comment on: http://stackoverflow.com/a/49073626
type: Comment
has text: Not everything is in `tf.keras`, some functions are still in `tf.python.keras.` LIke all the `vis_utils` and `load_weights_from_hdf5_group_by_name`.
score: 1

http://stackoverflow.com/q/48813291
has comment: http://stackoverflow.com/comment/85394011
has answer: http://stackoverflow.com/a/59973052
linked to: http://stackoverflow.com/q/2151084
has title: Read multi-dimensional array from caffe in opencv (C++)
has comment: http://stackoverflow.com/comment/106056144
has comment: http://stackoverflow.com/comment/106061751
has answer: http://stackoverflow.com/a/48814942
tagged with: opencv
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
upvote count: 1
tagged with: arrays
has answer: http://stackoverflow.com/a/48813677
answer count: 3
has body: I have a model in caffe that produce a multi-dimensional array. Size of this array is [1x10x8x8] so in python I haven't problem with this size because python automatically manage this array and I know order of elements in that. but when I switch to opencv with c++ the whole array is a vector and I haven't any idea how to regenerate something like python array, I use cv::NAryMatIterator to access multi-dimensional array such below const cv::Mat* arrays[]={&amp;prob,0}; //my multi-dimensional array is prob cv::Mat my_planes[1]; cv::NAryMatIterator it(arrays,my_planes); cv::Mat Multi_Array ; //temporary Mat for (int p = 0; p &lt; it.nplanes; ++p,++it) { Multi_Array = it.planes[0]; } after doing that I see Multi_Array size is [640x1] which seems that it is equal to 8x8x10 that python produced. is there anyway to access 8x8 planes one by one? EDIT: my multi-dimensional array size is [1x10x8x8]
accepted answer: http://stackoverflow.com/a/59973052
tagged with: python
possible better answer: http://stackoverflow.com/a/48813677
favorite count: 0
tagged with: c++

http://stackoverflow.com/q/48911692
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48912587
answer count: 1
tagged with: phishing
has body: Thanks in advance, I am trying to automate the process of getting if a URL is phishing or not using this page (which is a must) phishcheck.me. This is my python code: import requests from time import time import warnings warnings.simplefilter("ignore") def main(): badurl = "google.com" user_agent = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36" user_agent +=" (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36" url = "https://phishcheck.me/submit" referer = 'https://phishcheck.me' header = { 'Referer': referer + "/", 'User-Agent': user_agent, "Origin": referer, "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Accept": "application/json, text/javascript, */*; q=0.01", "Accept-Encoding": "gzip, deflate, br", "Accept-Language": "en-US,en;q=0.9,es;q=0.8", "Connection": "keep-alive", "Host": "phishcheck.me", "X-Requested-With": "XMLHttpRequest" } client = requests.session() client.get(referer, verify=False) csrftoken = client.cookies['csrftoken'] session_id = client.cookies['sessionid'] cookies = { 'csrftoken': csrftoken, '_ga': 'GA1.2.{0}.1517235473'.format(int(time())), '_gid': 'GA1.2.{0}.1519059714'.format(int(time())), '_gat': '1', "sessionid": session_id } # Try 1 payload = { 'csrfmiddlewaretoken': csrftoken, 'url': badurl, 'useragent': '0' } # Try 2 payload = "csrfmiddlewaretoken={0}&amp;url={1}&amp;useragent=0".format( csrftoken, badurl ) r = client.post(url, headers=header, data=payload, cookies=cookies, verify=False) return r print(main().text) # {"is_success": false} print(main().cookies) # &lt;RequestsCookieJar[&lt;Cookie messages="c0fa3b2c4d55aea15b28a734768e681a2680ff7d$__json_message\0540\05440\054Malformed URL. Please check your entry and try again." for phishcheck.me/&gt;]&gt; The cookies is telling me that I have a Malformed URL, I am not sure about how to fix it. Here is a screenshot about how the request is created from the phishcheck.me web page. Any detail I am missing, please ask!
has title: Can not automate a script to check url at phishcheck.me with Python requests
tagged with: python-requests
accepted answer: http://stackoverflow.com/a/48912587
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question

http://stackoverflow.com/comment/84805622
has text: I'll look into the NLTK stuff thanks. Nonetheless, I cannot use `grammar_check` because it's just a fork of `language_check`. Therefore, also uses the Java LanguageTool which is too slow for my purposes. Still could be that I can configure the LanguageTool server better that it internally uses multiprocessing, but I haven't found a way to do that, yet.
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48894856

http://stackoverflow.com/a/48862230
type: Answer
downvote count: 0
has body: I just found the issue. I also installed django-tinymce-4 via pip which downgraded my django installation to 1.9.2 during installation. I had to uninstall and reinstall django. I advice people to stay clear of that for now unless your django --version &lt;= 1.9.2
score: 1
answers question: http://stackoverflow.com/q/48862205
accepted answer of: http://stackoverflow.com/q/48862205
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48816296
score: 4
type: Question
upvote count: 4
tagged with: egg
tagged with: debugging
answer count: 1
downvote count: 0
favorite count: 0
has body: I am trying to debug an error in a python script that uses code in a module which is bundled as a .egg file. Using the IDLE 3.6.3 debugger (NB: the title of the debugger window is "Debug Control"), it is able to trace the commands that were executed in the various modules as well as the local and global variables available at the time those lines of code were executed. This is regardless of whether the source script is in a .egg file or not. For lines of code from a script that is not in a .egg file (but in a folder on the PC), I am able to access the source file from IDLE by right-clicking on the line of code in the Debug Control window and then choosing "Go to source line" from the context menu. The source file opens in an IDLE Editor window and the associated line number is highlighted. Within this Editor window, I can right-click on any line and set/clear a breakpoint. The problem arises when I try to "Go to source line" of a script which is located within an egg file. The debugger is also unable to step into the code in these scripts. I have however been able to extract the script from the egg file and can view it in the IDLE Editor window (or any other text editor). Is there a way to debug scripts in .egg files which I have been unable to figure out or is there a way to link the source script I have extracted to the debugger so that it does not have to depend on the one in the .egg file? (I am using python version 3.6.3)
tagged with: python
linked to: http://stackoverflow.com/q/2051192
has answer: http://stackoverflow.com/a/48817688
tagged with: python-idle
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48817688
has title: How to debug a python source file within a .egg file

http://stackoverflow.com/q/48872887
downvote count: 2
tagged with: count
tagged with: python
tagged with: recursion
score: 0
has title: I am trying to implement a count function in Python, without using len()
tagged with: methods
linked to: http://stackoverflow.com/q/19215141
answer count: 0
type: UnansweredQuestion
tagged with: iteration
has comment: http://stackoverflow.com/comment/84749665
duplicate of: http://stackoverflow.com/q/17778372
has body: def compute(arr, size): if not arr: return size else: compute(arr[1:], size+1) def count(sequence): result = compute(sequence, 0) return result array = [i for i in range(1, 101)] print(count(array)) I am trying to build my own custom method of count My intention is not to reinvent the wheel but to understand better about recursion and iteration I have a compute a compute method that slices the array in every call and increments the size variable. When the array becomes empty , it returns the size. but I am getting the result as None. Please let me know if I am doing something wrong here
has comment: http://stackoverflow.com/comment/84749628
favorite count: 0
type: Question
upvote count: 2

http://stackoverflow.com/comment/84667569
score: 0
has text: @JonClements Good point!
comment on: http://stackoverflow.com/q/48822177
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48961857
has answer: http://stackoverflow.com/a/48962105
tagged with: django
upvote count: 1
tagged with: python
has title: Reverse for 'add_comment' with keyword arguments '{u'slug': None}' not found. 1 pattern(s) tried: [u'blog/(?P<pk>\\d+)/comment/$']
type: AnsweredQuestion
score: 1
type: Question
has body: I am getting an error - Reverse for 'add_comment' with keyword arguments '{u'slug': None}' not found. 1 pattern(s) tried: [u'blog/(?P\d+)/comment/$'] I added - app_name= 'blog' - to urls to solve the earlier error of namespace but now I am stuck with a new error my urls.py url(r'^(?P<pk>\d+)/comment/$', views.add_comment, name='add_comment') my views.py def add_comment(request, slug): post = get_object_or_404(Post, slug=slug) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('blog:post', slug=post.slug) else: form = CommentForm() template = 'blog/add_comment.html' context = {'form': form} return render(request, template, context) my models.py class Post(models.Model): title = models.CharField(max_length=200) body = models.TextField() date = models.DateTimeField() slug = models.SlugField(max_length=250, blank=True, null=True) def __unicode__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) def get_absoulte_url(self): return reverse('blog:post.html', args=[self.slug]) class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments', blank=True, null=True) user = models.CharField(max_length=250) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) def approved(self): self.approved = True self.save() def __str__(self): return self.user my template add_comment.html {% extends "personal/header.html" %} {% block content %} Add new comment {% csrf_token %} {{ from.as_p }} Submit {% endblock %}
accepted answer: http://stackoverflow.com/a/48962105
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84929818
favorite count: 0

http://stackoverflow.com/q/48885254
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/84792171
downvote count: 0
tagged with: django-rest-framework
favorite count: 0
type: UnansweredQuestion
tagged with: django
tagged with: python
has body: How can you merge querysets in Django? I use the Django Rest Framework. I work with the following model: class City(models.Model): ... class House(models.Model): city = models.ForeignKey(City, ...) ... class Resident(models.Model): house = models.Foreignkey(House, ...) ... I now want to have a view that lists all the residents of a given city (slug is the slug of the city). Here is how I wrote it: class ResidentList(generics.ListAPIView): lookup_field = 'slug' serializer_class = ResidentSerializer permission_classes = (IsAuthenticated, IsMayor) def get_queryset(self): residents = Resident.objects.filter(house__city__slug=self.kwargs['slug']) return residents As you can see I create the list of residents for a city by iterating through all the citizens and filter those who life in a home that lifes in the right city. I just feel like this is pretty bad and inefficient, since the database has to loop through ALL the citizens. It would be better to have something like City.objects.get(slug=&lt;cityslug&gt;).houses.residents Then I would only have to loop through the smaller amount of cities. The problem with this obviously is that the above query returns a queryset. Therefore I can't chain houses and residents like that. PS: If you have other suggestions how I can improve my view let me know! PPS: I found this question here on stackoverflow, but it only shows how to get a list, which wouldn't work with get_queryset and the django rest structure, would it? Edit (More specification to get the question better): So the goal is to hit the api route: localhost:8000/api/house/&lt;city_slug&gt;/residents/ And get a list of all the residents in the city. Like this: { [ { resdidentid = "&lt;some_resident_id&gt;", residentname = "&lt;some_resident_name&gt;", ... }, { resdidentid = "&lt;some_resident_id&gt;", residentname = "&lt;some_resident_name&gt;", ... }, { resdidentid = "&lt;some_resident_id&gt;", residentname = "&lt;some_resident_name&gt;", ... }, ... ] }
answer count: 0
score: 1
linked to: http://stackoverflow.com/q/431628
upvote count: 1
has title: Merging multiple querysets in Django Rest Framework
has comment: http://stackoverflow.com/comment/84786920
has comment: http://stackoverflow.com/comment/84786435
type: Question
has comment: http://stackoverflow.com/comment/84786967
has comment: http://stackoverflow.com/comment/84785447
tagged with: drf-queryset
has comment: http://stackoverflow.com/comment/84786845

http://stackoverflow.com/q/48909748
has answer: http://stackoverflow.com/a/48909793
has title: Regular Expression in python doesn't work
tagged with: regex
favorite count: 0
has body: I'm working on the exercise in the book Python for Informatics which asks me to write a program to simulate the operation of the grep command on UNIX. However, my code doesn't work. Here I simplified my code and only intend to calculate how many lines start with the word 'Find'. I'm quite confused and wish you could cast light on it. from urllib.request import urlopen import re fhand = urlopen('http://www.py4inf.com/code/mbox-short.txt') sumFind = 0 for line in fhand: line = str(line) #convert from byte to string for re operation if re.search('^From',line) is not None: sumFind+=1 print(f'There are {sumFind} lines that match.') The output of the script is There are 0 lines that match. And here is the link of the input text: text Thanks a lot for your time.
accepted answer: http://stackoverflow.com/a/48909793
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48910436
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48910436

http://stackoverflow.com/a/52279615
has body: Delete the mentioned packages by editing the .yml file and run the command for environment creation. It works fine. Hope this helps.
upvote count: 1
downvote count: 1
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48848755

http://stackoverflow.com/q/48873936
accepted answer: http://stackoverflow.com/a/48874204
answer count: 2
possible better answer: http://stackoverflow.com/a/48874126
downvote count: 0
favorite count: 0
upvote count: 2
tagged with: python
tagged with: regex
type: AnsweredQuestion
score: 2
has answer: http://stackoverflow.com/a/48874204
has body: I am porting a parsing tool from Perl to Python: my $lineno = 1; my @data; for my $line (split /\R/, $source) { $line =~ s/^([ ]*)//; my $indent = length $1; push @data, [$lineno++, $indent, $line]; } This splits the input into lines, using Unicode line separators, strips leading space (only U+0020 space characters), determines the indendation level from the stripped space. I am finding it difficult to translate this to idiomatic Python because re.sub() only returns the string after replacement, but not the match object (which I need to count the removed spaces). In this particular example, I could simply compare the length of the string before and after the substitution. But I'm interested in a general solution to this kind of problem: How can I perform a single substitution while also accessing the regex captures? Attempt 1 – exfiltrate the match object through a substitution function: lineno = 1 data = [] re_leading_space = re.compile(r'^([ ]*)') for line in source.splitlines(): # TODO handle Unicode line seps m = None def exfiltrate(the_match): nonlocal m m = the_match return '' line = re_leading_space.sub(exfiltrate, line, count=1) indent = len(m.group(1)) if m is not None else 0 data.append((lineno, indent, line)) lineno += 1 Disadvantage: weird nonlocal data flow. Attempt 2 – perform the substitution manually: lineno = 1 data = [] re_leading_space = re.compile(r'^([ ]*)') for line in source.splitlines(): # TODO handle Unicode line seps m = re_leading_space.match(line) indent = 0 if m is not None: line = line[m.end():] # remove matched prefix indent = len(m.group(1)) data.append((lineno, indent, line)) lineno += 1 Disadvantage: while otherwise fairly clear, it just ends up being a bad reimplementation of the standard library. Attempt 3 – perform a match, then match the regex again as a substitution: lineno = 1 data = [] re_leading_space = re.compile(r'^([ ]*)') for line in source.splitlines(): # TODO handle Unicode line seps m = re_leading_space.match(line) li…
has title: How can I perform a single substitution, and use the regex captures afterwards?
type: Question
has answer: http://stackoverflow.com/a/48874126

http://stackoverflow.com/comment/85125656
has text: What you want is not done with the api but with account management on the web. https://www.interactivebrokers.com/en/software/etmug/employeetrackmgmt.htm#cshid=employeetrack/etreports/ib_activity_flex.htm
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48942917

http://stackoverflow.com/a/48849979
downvote count: 0
has body: user = models.OneToOneField(User, on_delete=models.CASCADE) Instead of foriegn key use one to one relation
answers question: http://stackoverflow.com/q/48849928
type: Answer
upvote count: 1
score: 1

permissions
tag name: permissions
type: Tag
tags question: http://stackoverflow.com/q/48945756

http://stackoverflow.com/comment/84622920
type: QuestionComment
has text: We still have no idea why the assignment line contains two equals signs or what you hope the semantics of that to be. Really, explain what you want to happen there.
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48809682

http://stackoverflow.com/q/48939988
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84887173
has title: Python: Read in a random sample of a json file
type: Question
linked to: http://stackoverflow.com/q/9690009
has body: I have a very large JSON file containing last month's reddit comments (~30 GBs), which is too large to store in RAM and analyze. I'm hoping there is a method to sample a random subset of the data for analytical purposes, before resorting to cloud compute. I'm reading in a certain amount of comments using the following code: import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import json from IPython.display import display %matplotlib inline r_data = [] with open('reddit_1_28_2018.txt') as f: counter = 0 for line in f: r_data.append(json.loads(line)) counter += 1 if counter % 500000 == 0: print ("Processed %d comments\n" % (counter)) if counter &gt;= 2000000: break print ("Data downloaded!") A sample of the dataset can be found here: https://files.pushshift.io/reddit/comments/sample_data.json h/t @deliriouslettuce
has comment: http://stackoverflow.com/comment/84887209
has comment: http://stackoverflow.com/comment/84887052
score: 0
has comment: http://stackoverflow.com/comment/84887025
has comment: http://stackoverflow.com/comment/84887215
answer count: 0

http://stackoverflow.com/comment/84812042
type: Comment
has text: `parentList[elements[j][0]].clear()` there is no method `clear()`
comment on: http://stackoverflow.com/a/48903172
type: AnswerComment
score: 0

sensors
type: Tag
tags question: http://stackoverflow.com/q/48813621
tag name: sensors
tags question: http://stackoverflow.com/q/48830551

http://stackoverflow.com/comment/84668874
type: QuestionComment
comment on: http://stackoverflow.com/q/48831595
has text: @PauloScardine I think I have a user with `id == 1` but it is deleted when the test tearDown but kept in the "Track" table for a reason I don't understand
score: 0
type: Comment

http://stackoverflow.com/comment/84683891
type: Comment
comment on: http://stackoverflow.com/q/48839873
type: QuestionComment
has text: What do you mean by "stores all the quantity from the BriefDescription"? And why do you think you have tuples? What is a `Quantity`?
score: 0

http://stackoverflow.com/comment/84709438
type: AnswerComment
comment on: http://stackoverflow.com/a/48852862
type: Comment
has text: @MrT, I you suggested edited question. Hope it fine. Please let me know if not correct format
score: 0

http://stackoverflow.com/comment/84972459
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48922079
has text: I can't see in your examples where do you upload a file. Eventually you should open another question specifically for that issue. If you have solved your problem, please post your own answer and explain what helped and how the issue was solved, then accept your own answer. In that way you'll help other people having a similar problem and the quality of SO will increase. It is ugly when we have too many unanswered and open questions, which in fact have been solved.

pivot-table
tag name: pivot-table
tags question: http://stackoverflow.com/q/48927232
tags question: http://stackoverflow.com/q/48871983
tags question: http://stackoverflow.com/q/48905336
tags question: http://stackoverflow.com/q/48896660
tags question: http://stackoverflow.com/q/48823986
tags question: http://stackoverflow.com/q/48859588
tags question: http://stackoverflow.com/q/48913757
tags question: http://stackoverflow.com/q/48943425
tags question: http://stackoverflow.com/q/48960528
tags question: http://stackoverflow.com/q/48835129
tags question: http://stackoverflow.com/q/48866730
type: Tag

http://stackoverflow.com/comment/84758994
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48876945
has text: Okay. Do you know what about the final result is wrong specifically?

http://stackoverflow.com/q/48826045
has title: Read input as nested list in python
favorite count: 0
has body: I am new to python. I want to read the input from stdin as nested list. Stdin: student1 90 student2 85 student3 98 My list should be as follows: student = [['student1',90],['student2',85],['student3',98]] Is there any way I can read the input using list comprehension without needing any extra space.
accepted answer: http://stackoverflow.com/a/48826115
possible better answer: http://stackoverflow.com/a/48826136
tagged with: python
has answer: http://stackoverflow.com/a/48826136
type: AnsweredQuestion
tagged with: nested-lists
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48826115
score: 0
answer count: 2

http://stackoverflow.com/comment/97205582
type: Comment
comment on: http://stackoverflow.com/a/49046025
score: 0
type: AnswerComment
has text: as @Artemis Fowl mentioned - "Your normal google search will be based on a lot of info that google picks up about you. If you sign out of google and use an incognito window, it should be unaffected."

http://stackoverflow.com/comment/84710687
score: 1
comment on: http://stackoverflow.com/q/48853156
type: Comment
type: QuestionComment
has text: I second @JonClements, at least with the data above, pandas date time is able to convert all the dates in correct format.

http://stackoverflow.com/q/48856162
has title: Python Discord bot won't say something when handed to function
accepted answer: http://stackoverflow.com/a/48856334
type: AnsweredQuestion
tagged with: discord.py
type: Question
answer count: 1
tagged with: python-3.6
has answer: http://stackoverflow.com/a/48856334
score: 0
tagged with: python
has body: I just started modifying a Python Program that responds to queries in Discord. Running the Program starts a Discord bot that listens to commands and executes tasks accordingly. Now I wanted to give a reference to the bot object into the method it started to give some information back to the discord channel on what is happening right now. For some reason that's not working and I can't figure out why. Here's the min example. If something is missing please tell me. Full code can be reviewed here. discord.py from communitybot.playgame import Game from discord.ext.commands import Bot from communitybot.utils import ( start_game ) bot = Bot( description=description, command_prefix="$", pm_help=False) bot.remove_command('help') @bot.group(pass_context=True) async def game(ctx): if ctx.invoked_subcommand is None: await bot.say('Usage: $game start') @game.command() async def start(): start_game(bot) await bot.say("**Game started**") utils.py from communitybot.playgame import Game from communitybot.settings import BOT_ACCOUNT from steem import Steem def start_game(discordbot=None): c = Game( get_steem_conn(), BOT_ACCOUNT, discordbot = discordbot ) c.start_game() playgame.py class Game: def __init__(self, steemd_instance, bot_account, discordbot=None): self.s = steemd_instance self.bot_account = bot_account self.discord = discordbot def start_game(self): #do something if self.discord is not None: self.discord.say('**did something**') The bot from discord.py and self.discordbot from playgame.py seem to be referenced to the same object. After running this discord says Game started but he won't say did something Any suggestion on what is wrong so I can look into it? Thanks in advance.

http://stackoverflow.com/q/48855333
answer count: 1
type: UnansweredQuestion
has title: python compare a list to a list in a file,without overwriting the file
has comment: http://stackoverflow.com/comment/84714117
favorite count: 0
has answer: http://stackoverflow.com/a/48855688
type: Question
has comment: http://stackoverflow.com/comment/84714203
tagged with: python
has body: i am trying to find away how to check using the python script if there is new vcenter farm let say i have currently 5 farms Farm01 Farm02 Farm03 Farm04 Farm05 if new vmware farm let say Farm6 i want the script to detect it so i thought to write the exiting farms to file and compare it to the exiting farm list but the file is getting ovewriten ,here is what i did so far f=open('farms_file',"w+") for farms_items in all_farms_list: f.write("%s\n" % farms_items) f.close() file = open('farms_file','r') f_content = file.read() for i in f_content.split(): #print i will print all farms in the file if i not in all_farms_list: print(i) but i am not getting any results as the file is overwritten can you please provide away so the file will not be overriten so i will get the new farm for example farm6
score: -1
downvote count: 2
upvote count: 1

http://stackoverflow.com/q/48959112
upvote count: 1
tagged with: python
tagged with: node.js
answer count: 0
has comment: http://stackoverflow.com/comment/84932128
has comment: http://stackoverflow.com/comment/84926602
downvote count: 1
type: Question
has title: Can a Django project backend server run in two environments?
score: 0
has body: Can a Django project backend server run in two environments? I have a Django-Rest-Framework project( using Python write the project ) as the backend to provide APIs, and now I want to add a application to as a app in my backend. The application is written using node.js. Can I use two environments to run the backend project?
has comment: http://stackoverflow.com/comment/84967274
favorite count: 0
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/q/48881691
tagged with: python
has comment: http://stackoverflow.com/comment/84810058
linked to: http://stackoverflow.com/q/10335561
downvote count: 1
tagged with: sqlalchemy
type: Question
has comment: http://stackoverflow.com/comment/84769101
score: -1
has title: How would I use database in sqlalchemy using create_engine?
has body: Right now; I'm getting the following error: ProgrammingError: (psycopg2.ProgrammingError) relation "tableName" does not exist LINE 2: FROM tableName I assumed it's because I'm not using that database for the session; so i went and procceded to use session.execute and use the sql statement USE to use the database but it is throwing me syntax error engine = create_engine('postgresql://postgres:passwordhere@localhost:5432/test1') sa.orm.configure_mappers() # IMPORTANT! Base.metadata.create_all(engine) session = sessionmaker(bind=engine)() session.connection().connection.set_isolation_level(0) session.execute('USE DATABASE test1;') session.connection().connection.set_isolation_level(1) ERROR I GET FROM ABOVE SCRIPT: cursor.execute(statement, parameters) sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) syntax error at or near "USE" LINE 1: USE DATABASE test1; ^ [SQL: 'USE DATABASE test1;'] (Background on this error at: http://sqlalche.me/e/f405) As suggested by people; here is my code that saves and checks the database before saving it. check_if_exists = session.query(latest_movies_scraper).filter_by(name=dictionary['title']).first() if check_if_exists: print check_if_exists.name print 'skipping this...' pass else: insert_to_db = latest_movies_scraper(name=dictionary['title'], url=dictionary['href'], image_url=dictionary['featured_image']) session.add(insert_to_db) session.commit() class latest_movies_scraper(Base): __tablename__ = 'latest_movies_scraper' id = sa.Column(sa.Integer, primary_key=True) name = sa.Column(sa.Unicode(255)) url = sa.Column(sa.Unicode(255)) image_url = sa.Column(sa.Unicode(255)) create = sa.Column(sa.DateTime, default=datetime.datetime.utcnow) search_vector = sa.Column(TSVectorType('name'))
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84799017
has answer: http://stackoverflow.com/a/53072674
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84768154

http://stackoverflow.com/comment/84782914
comment on: http://stackoverflow.com/a/48885694
has text: @gangabass thanks for your simple answer. Now I understand how regex works with item loaders.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84637367
score: 0
has text: how are you viewing the csv once you write it- excel?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48816717

tree-traversal
tags question: http://stackoverflow.com/q/48850446
tag name: tree-traversal
type: Tag

http://stackoverflow.com/a/49424269
score: 0
has body: I found this: https://github.com/aldryn/aldryn-bootstrap3/issues/157. Guess it is not compatible with the current Django version. I hope they will fix it soon.
type: Answer
answers question: http://stackoverflow.com/q/48897947

http://stackoverflow.com/q/48884153
has answer: http://stackoverflow.com/a/48884395
type: Question
has comment: http://stackoverflow.com/comment/84774188
accepted answer: http://stackoverflow.com/a/48885062
has body: I'm trying to combine rasters model field with non-model config_version field into my serializer which looks like: class RasterPostSerializer(serializers.ModelSerializer): class Meta: model = Raster fields = ( 'name', 'description', 'filepath' ) class ConfigurationSerializer(serializers.Serializer): config_version = serializers.CharField() rasters = RasterPostSerializer(many=True) def create(self, validated_data): data_field = validated_data['rasters'] for raster in data_field['rasters']: return Raster(name=raster['name'], description=raster['description'], filepath=raster['filepath']) Before utilize serializer.save() method I would like to check config_version in my view.py, but after that the .save() gives me: The serializer field might be named incorrectly and not match any attribute or key on the `Raster` instance. Original exception text was: 'Raster' object has no attribute 'config_version'. What is going on, and is there a solution for that? EDIT: my example JSON POST payload looks like: { "config_version":"v2", "rasters":[ { "name":"XYZ.jpg", "description":"some description", "filepath":"path in filesystem" } } The config_version it is not constant. It can be set dynamically, due the controller utilizing ConfigurationSerializer will be the configuration endpoint - there need to be possibility to add rasters, and some other information in the future. configuration endpoint in views.py looks like @api_view(['POST']) def configuration(request): if request.method == 'POST': serializer = ConfigurationSerializer(data=request.data) if serializer.is_valid(): if serializer.validated_data['config_version'] is 'v2': raster_name_list = [raster.name for raster in Raster.objects.all()] for instance in serializer.validated_data['rasters']: if instance['name'] in raster_name_list: return Response({"Fail": "Raster name '{}' already exists".format(instance['name'])}, status=status.HTTP_304_NOT_MODIFIED) serializer.save() return Response(serializer.data, status=status.HTTP_201…
tagged with: django-rest-framework
score: 4
has title: Add non-model field in Serializer DRF
upvote count: 4
answer count: 2
has comment: http://stackoverflow.com/comment/84773576
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84776681
has answer: http://stackoverflow.com/a/48885062
tagged with: django
has comment: http://stackoverflow.com/comment/84774349
tagged with: python
has comment: http://stackoverflow.com/comment/84773719
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48884395
has comment: http://stackoverflow.com/comment/84774390

http://stackoverflow.com/comment/84773440
type: Comment
has text: If the problem was with indentation none (or almost none) of the `manage.py` command would work, and specially not `makemigrations`.
comment on: http://stackoverflow.com/a/48884163
score: 0
type: AnswerComment

http://stackoverflow.com/comment/116586419
score: 1
type: AnswerComment
has text: Interesting, but perhaps not as relevant to a pyspark question?
type: Comment
comment on: http://stackoverflow.com/a/65939280

http://stackoverflow.com/a/48928135
type: Answer
upvote count: 2
has comment: http://stackoverflow.com/comment/84862505
answers question: http://stackoverflow.com/q/48927800
score: 2
accepted answer of: http://stackoverflow.com/q/48927800
type: AcceptedAnswer
has body: A decorator is a function that takes a function (a view in this case), and returns another function (a view in this case). At the moment your rights_needed looks like a regular view - it’s returning a response not a function. Django comes with a user_passes_test method that makes it easy to create decorators like this. Since you are using class based views, it would be even easier to use the UserPassesTest mixin. Your test function for the mixin would be: def test_func(self): return self.request.user.groups.filter(Q(name='Admin')).exists()
downvote count: 0

http://stackoverflow.com/q/48886029
upvote count: 1
tagged with: python
score: 1
has comment: http://stackoverflow.com/comment/84776845
tagged with: django-models
has body: I'm trying to implement a method that duplicate Django model instances and its related objects. The solution is in this stackoverflow post. But _collect_sub_objects method seems to be deprecated in recent versions of Django. Somebody could tell me if its an equivalent in recent versions of Django?
has comment: http://stackoverflow.com/comment/84777106
type: Question
linked to: http://stackoverflow.com/q/437166
downvote count: 0
has title: Is there an equivalent for _collect_sub_objects method in Python 3?
favorite count: 0
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/comment/84657629
type: Comment
comment on: http://stackoverflow.com/a/48826517
has text: Ok, I''ll check it, thanks for your answer and time!
score: 0
type: AnswerComment

http://stackoverflow.com/q/48890261
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
has title: Tweepy 3.5 - error in streaming.py: line = buf.read_line().strip()
tagged with: python
tagged with: tweepy
type: UnansweredQuestion
score: 1
type: Question
has body: This error occurs intermittently when parsing Twitter data using streaming.py in Tweepy 3.5. I have seen discussions about this in past postings, but have yet to see a solution. One person suggested installing Tweepy 3.2, but we are on 3.5 now, so this does not seem reasonable. The trace and my software versions are listed below: Traceback (most recent call last): File "newt5.py", line 223, in <module> sapi.filter(track=['BTC', 'Bitcoin'], languages = ['en']) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tweepy/streaming.py", line 445, in filter self._start(async) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tweepy/streaming.py", line 361, in _start self._run() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tweepy/streaming.py", line 294, in _run raise exception File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tweepy/streaming.py", line 263, in _run self._read_loop(resp) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/tweepy/streaming.py", line 313, in _read_loop line = buf.read_line().strip() AttributeError: 'NoneType' object has no attribute 'strip' pip3 shows tweepy Name: tweepy Version: 3.5.0 Summary: Twitter library for python Home-page: http://github.com/tweepy/tweepy Author: Joshua Roesslein Author-email: tweepy@googlegroups.com License: MIT Location: /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages
has answer: http://stackoverflow.com/a/67888693
has comment: http://stackoverflow.com/comment/85350018

http://stackoverflow.com/comment/84743905
type: AnswerComment
comment on: http://stackoverflow.com/a/48863926
type: Comment
has text: Thank you!! That was extremely helpful. Going forward it'll be useful to know that the * operand doesn't work for matrix multiplication!
score: 0

http://stackoverflow.com/q/48842926
has body: I have a df that has multiple columns that end in the same value. I want to consolidate columns into one final column. For example, any columns that end in '_1' should go into a new column labeled 'final_1'. The value in final_1 would be 1 if all values in '_1' are '1' and final_1 would be 0 if otherwise e.g., if there's at least one value that isn't '1' within the '_1' columns. The original and final result dataframes are more clear if my explanation is not. df = pd.DataFrame({'KEY': ['100000003', '100000009', '100000009', '100000009'], 'RO_1': [1, 1, 4,1], 'RO_2': [1, 0, 0,0], 'RO_3': [1, 1, 1,1], 'en_1': [1, 4, 1,1], 'en_2': [1, 4, 1,0], 'en_3': [1, 4, 4,0], 'ao_1': [1, 4, 1,1], 'ao_2': [1, 4, 1,0], 'ao_3': [1, 4, 4,0] }) KEY RO_1 RO_2 RO_3 ao_1 ao_2 ao_3 en_1 en_2 en_3 0 100000003 1 1 1 1 1 1 1 1 1 2 100000009 4 0 1 1 1 4 1 1 4 3 100000009 1 0 1 1 0 0 1 0 0 Final result: KEY RO_1 RO_2 RO_3 ao_1 ao_2 ao_3 en_1 en_2 en_3 Final1 Final2 Final3 0 100000003 1 1 1 1 1 1 1 1 1 1 1 1 2 100000009 4 0 1 1 1 4 1 1 4 0 0 0 3 100000009 1 0 1 1 0 0 1 0 0 1 0 0 My current attempt. SInce there are 3 different columns I'm using a loop. then I'm combining the original df with the new frame (mc). But I am not getting anything different.. for i in range(1,4): mc = df.filter(regex='^_' + str(i)).isin([1]).astype(int).rename(columns=lambda x: x.replace('_', 'Final')) df= pd.concat([df, mc], axis=1)
has answer: http://stackoverflow.com/a/48843158
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: consolidating multiple columns into one column pandas
score: 1
possible better answer: http://stackoverflow.com/a/48843158
upvote count: 1
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/48842969
accepted answer: http://stackoverflow.com/a/48842969
answer count: 2
tagged with: pandas-groupby
tagged with: pandas

ipython-parallel
type: Tag
tag name: ipython-parallel
tags question: http://stackoverflow.com/q/48939457

http://stackoverflow.com/comment/84904187
score: 0
type: Comment
has text: `my_nested_dictionary.items()`, not `iteritems()` (at least for Python 3)
comment on: http://stackoverflow.com/a/48949024
type: AnswerComment

http://stackoverflow.com/q/48946552
tagged with: validation
answer count: 1
has answer: http://stackoverflow.com/a/48966811
favorite count: 0
has body: I have a Class with a quite complex set of business rules. Imagine something like "If field A has value 4 and field B has value True, than field C must be an array with at least 2 elements" and so on. I'm trying to prevent the users to add instances of this class that don't respect these rules. So the validation should happen both on creation and on update. I saw that SqlAlchemy offers the validate method but it looks a little bit too complicated to setup when the validation includes multiple fields. The alternative appears to be the before_insert and before_update events. Is this the proper solution in this case or I have another alternatives that I've not considered?
upvote count: 2
has comment: http://stackoverflow.com/comment/84899613
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: orm
tagged with: sqlalchemy
type: Question
downvote count: 0
tagged with: flask-sqlalchemy
has title: What is the proper way to validate an object with SqlAlchemy when the validation involves several fields?

http://stackoverflow.com/comment/84625304
score: 1
type: AnswerComment
has text: This might not be a feasible solution. Even though the python program sleeps for the time specified, its just you are asking the python to not perform any operations, which means Python compiler is still utilizing your processor. What if the program execution lasts only for 10 secs ? You are sacrificing the processor for 29 mins 50 secs.
type: Comment
comment on: http://stackoverflow.com/a/48810684

http://stackoverflow.com/comment/84898670
score: 0
type: Comment
type: QuestionComment
has text: I tried to write this : `def save(self) : return {'Utilisateur' : self.request.user}` but it doesn't seems to work. I'm searching yet
comment on: http://stackoverflow.com/q/48944619

http://stackoverflow.com/a/48870033
has comment: http://stackoverflow.com/comment/84780529
answers question: http://stackoverflow.com/q/48811690
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85234797
accepted answer of: http://stackoverflow.com/q/48811690
type: Answer
has body: The problem wasn't bulk. csv.DictReader always reads the first line from the file to get the headers for subsequent rows. So if you're going to use DictReader, the file needs a header.
has comment: http://stackoverflow.com/comment/85286174
score: 1
upvote count: 1

http://stackoverflow.com/comment/86174477
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48848755
has text: can you show the content of your tfdl_env.yml file?

http://stackoverflow.com/q/48938111
possible better answer: http://stackoverflow.com/a/48938163
has body: I have two data frames df and dfusers df: ID Count A1 5 B1 12 C1 7 dfusers: ID FullName A1 Mike Frost B1 Jack James C1 Mickey Rose I would like ID Count FullName A1 5 Mike Frost B1 12 Jack James C1 7 Mickey Rose In my research, I ended up trying df['Fullname']=df['ID'].map(dfusers['FullName']) But the resulting dataframe returns NaN for all IDs. I was able to successfully create the desired dataframe using Excel Vlookup though. How come this is not working in pandas?
type: Question
has answer: http://stackoverflow.com/a/48938163
has comment: http://stackoverflow.com/comment/84883217
has comment: http://stackoverflow.com/comment/84883219
accepted answer: http://stackoverflow.com/a/48938167
tagged with: dataframe
score: 4
upvote count: 4
answer count: 3
tagged with: pandas
tagged with: vlookup
downvote count: 0
favorite count: 0
has title: pandas map returning all NaNs
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48938187
has answer: http://stackoverflow.com/a/48938167

http://stackoverflow.com/comment/84765058
score: 0
comment on: http://stackoverflow.com/a/48879870
has text: Hmph! It's upto the OP to decide how he wants these boundary-value conditions to behave I guess! But both are just fine given the question...
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84766955
type: QuestionComment
has text: Tried using `agg`?
score: 0
comment on: http://stackoverflow.com/q/48881437
type: Comment

http://stackoverflow.com/comment/84987563
type: QuestionComment
comment on: http://stackoverflow.com/q/48944574
has text: Actually, I cannot reproduce this since my test account does not have an archive folder structure. I tried `recoverable_items_root` but it works without issues. What's the error or output you get from `account.archive_msg_folder_root.tree()` and what did you expect?
score: 0
type: Comment

http://stackoverflow.com/comment/84705996
score: 0
has text: Hope that helps
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48850764

http://stackoverflow.com/q/48954438
linked to: http://stackoverflow.com/q/6260089
has comment: http://stackoverflow.com/comment/84915527
score: 0
tagged with: key-value
answer count: 3
has comment: http://stackoverflow.com/comment/84916489
accepted answer: http://stackoverflow.com/a/48963253
tagged with: python
has answer: http://stackoverflow.com/a/48954515
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/48954515
has body: I have a list of key-value pair in python. A sample of this list is: list_pairs = [{'text': 'Zen', 'value': 'Zen'}, {'text': 'Global', 'value': 'Global'}, {'text': 'Corporation', 'value': 'Corporation'}] Now I have a string str1 and what I want to do is to match it with text field of each key-value pair and delete the one which matches. So if my string is Zen then delete {'text': 'Zen', 'value': 'Zen'} from the list. I tried to do del list_pairs[str1] but it throws error as list indices can only be integers and not str. How can I delete the items from my list of key-value pair?
type: Question
has answer: http://stackoverflow.com/a/48954534
has answer: http://stackoverflow.com/a/48963253
has title: how to delete item from a list of key-value pairs in python

image-processing
tags question: http://stackoverflow.com/q/48811203
tags question: http://stackoverflow.com/q/48809433
tags question: http://stackoverflow.com/q/48917381
tags question: http://stackoverflow.com/q/48962001
tags question: http://stackoverflow.com/q/48916237
tags question: http://stackoverflow.com/q/48812552
tags question: http://stackoverflow.com/q/48866756
tags question: http://stackoverflow.com/q/48814216
tags question: http://stackoverflow.com/q/48877967
tags question: http://stackoverflow.com/q/48815453
tags question: http://stackoverflow.com/q/48931944
tags question: http://stackoverflow.com/q/48818032
tags question: http://stackoverflow.com/q/48911162
tags question: http://stackoverflow.com/q/48868348
tags question: http://stackoverflow.com/q/48877925
tags question: http://stackoverflow.com/q/48912988
tags question: http://stackoverflow.com/q/48896088
tags question: http://stackoverflow.com/q/48903091
tags question: http://stackoverflow.com/q/48888239
type: Tag
tags question: http://stackoverflow.com/q/48945249
tags question: http://stackoverflow.com/q/48886637
tags question: http://stackoverflow.com/q/48886830
tags question: http://stackoverflow.com/q/48822796
tags question: http://stackoverflow.com/q/48806504
tags question: http://stackoverflow.com/q/48898155
tags question: http://stackoverflow.com/q/48915449
tags question: http://stackoverflow.com/q/48922718
tags question: http://stackoverflow.com/q/48954246
tags question: http://stackoverflow.com/q/48804553
tags question: http://stackoverflow.com/q/48856444
tags question: http://stackoverflow.com/q/48956585
tag name: image-processing
tags question: http://stackoverflow.com/q/48895902
tags question: http://stackoverflow.com/q/48928592
tags question: http://stackoverflow.com/q/48905676
tags question: http://stackoverflow.com/q/48914995
tags question: http://stackoverflow.com/q/48948769
tags question: http://stackoverflow.com/q/48941504
tags question: http://stackoverflow.com/q/48871470

http://stackoverflow.com/comment/84836493
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48914590
has text: my question is oriented to ask where you use file.load()?
score: 0

http://stackoverflow.com/q/48818274
tagged with: blender
has body: I'm trying to add tens of thousands of mesh primitives to a scene in blender using its Python interface. I've been using something to the effect of: for i in range(10000): bpy.ops.mesh.primitive_cube_add(radius=1, location=(i, i, i)) This approach takes many minutes, though. Is there a more efficient way of doing this?
accepted answer: http://stackoverflow.com/a/48819995
has comment: http://stackoverflow.com/comment/84698590
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion
has title: quickly adding large numbers of mesh primitives in blender
has answer: http://stackoverflow.com/a/48819995
upvote count: 3
type: Question
score: 3

http://stackoverflow.com/q/48911850
favorite count: 0
tagged with: unicode-escapes
has body: I have created a custom corpus using nltk's CategorizedPlaintextCorpusReader. There are unicode characters within the .txt files of my corpus which I'm unable to decode. I assume it's the fact this is a "plaintext" reader but need to decode this nonetheless. Code: import nltk from nltk.corpus import CategorizedPlaintextCorpusReader import os mr = CategorizedPlaintextCorpusReader('C:\mycorpus', r'(?!\.).*\.txt', cat_pattern=os.path.join(r'(neg|pos)', '.*',)) for w in mr.words(): print(w) This will print the words of files that do not contain unicode in tokenized format, and then throws the following error: for w in mr.words(): File "C:\Python\Python36-32\lib\site-packages\nltk\corpus\reader\util.py", line 402, in iterate_from for tok in piece.iterate_from(max(0, start_tok-offset)): File "C:\Python\Python36-32\lib\site-packages\nltk\corpus\reader\util.py", line 296, in iterate_from tokens = self.read_block(self._stream) File "C:\Python\Python36-32\lib\site-packages\nltk\corpus\reader\plaintext.py", line 122, in _read_word_block words.extend(self._word_tokenizer.tokenize(stream.readline())) File "C:\Python\Python36-32\lib\site-packages\nltk\data.py", line 1168, in readline new_chars = self._read(readsize) File "C:\Python\Python36-32\lib\site-packages\nltk\data.py", line 1400, in _read chars, bytes_decoded = self._incr_decode(bytes) File "C:\Python\Python36-32\lib\site-packages\nltk\data.py", line 1431, in _incr_decode return self.decode(bytes, 'strict') File "C:\Python\Python36-32\lib\encodings\utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 30: invalid start byte I have attempted to decode with: mr.decode('unicode-escape') which throws this error: AttributeError: 'CategorizedPlaintextCorpusReader' object has no attribute 'decode' I am using Python 3.6.4.
tagged with: python
has answer: http://stackoverflow.com/a/48916497
upvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84831241
tagged with: nltk
score: 1
tagged with: python-unicode
accepted answer: http://stackoverflow.com/a/48916497
has comment: http://stackoverflow.com/comment/84831983
has title: NLTK - Decoding Unicode in custom corpus
has comment: http://stackoverflow.com/comment/84831423
answer count: 1
downvote count: 0
tagged with: unicode
has comment: http://stackoverflow.com/comment/84830753

http://stackoverflow.com/a/48919954
downvote count: 1
has comment: http://stackoverflow.com/comment/84846336
type: Answer
answers question: http://stackoverflow.com/q/48919882
score: 0
has body: Try this single liner and use in to check element exitance: - A = [(2, 'two', '2nd', 'second')] B = ['two'] print [i[0] for i in A if B[0] in i] #[2] B = ['two1'] print [i[0] for i in A if B[0] in i] #[]
upvote count: 1

http://stackoverflow.com/q/48830324
tagged with: append
answer count: 0
duplicate of: http://stackoverflow.com/q/29314424
has title: Pandas average columns with same value in other columns
has comment: http://stackoverflow.com/comment/84664628
upvote count: 1
type: Question
score: 1
tagged with: dataframe
tagged with: pandas
has comment: http://stackoverflow.com/comment/84664619
downvote count: 0
has comment: http://stackoverflow.com/comment/84688307
has comment: http://stackoverflow.com/comment/84664621
favorite count: 0
duplicate of: http://stackoverflow.com/q/46938572
has body: I have a df that looks like this: headings = ['foo','bar','qui','gon','jin'] table = [[1,1,3,4,5], [1,1,4,5,6], [2,2,3,4,5], [2,2,4,5,6], ] df = DataFrame(columns=headings,data=table) foo bar qui gon jin 0 1 1 3 4 5 1 1 1 4 5 6 2 2 2 3 4 5 3 2 2 4 5 6 What I want to do is average the values of all columns whenever a certain column has a similar value e.g. I want to average all the columns with similar 'bar' values and then create a dataframe with the answer. I tried the following: newDf = DataFrame([]) for i in df['bar'].loc[1:2]: newDf = newDf.append(df[df['foo'] == i].mean(axis=0),ignore_index=True) And it outputs what I want: bar foo gon jin qui 0 1.00E+00 1.00E+00 4.50E+00 5.50E+00 3.50E+00 1 2.00E+00 2.00E+00 4.50E+00 5.50E+00 3.50E+00 But when I try that with another column with value, it does not output what I want: for i in df['qui'].loc[1:2]: newDf = newDf.append(df[df['foo'] == i].mean(axis=0),ignore_index=True) Produces bar foo gon jin qui 0 NAN NAN NAN NAN NAN 1 NAN NAN NAN NAN NAN Can you give me a hand? Side question: how do I prevent the columns of the new dataframe to be ordered alphabetically? Is it possible to maintain the order of the original dataframe?
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/29314424

nodes
tags question: http://stackoverflow.com/q/48846735
tags question: http://stackoverflow.com/q/48953515
tag name: nodes
tags question: http://stackoverflow.com/q/48941381
type: Tag

http://stackoverflow.com/comment/84751437
comment on: http://stackoverflow.com/q/48873457
type: Comment
has text: Or assuming you've overwritten column A - then `df[df.ColA.isna()]` will retrieve all the rows/columns from the DF where ColA is NaN - so you've got more information available to find...
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84887190
comment on: http://stackoverflow.com/q/48940047
has text: Look again at `for i in len(sequence)`. `len(sequence)` is a number. You probably mean `range(len(sequence))`.
score: 4
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84777757
type: QuestionComment
has text: Thanks @sshashank124, I will attach it .
type: Comment
comment on: http://stackoverflow.com/q/48886423
score: 0

http://stackoverflow.com/comment/84625640
type: Comment
type: QuestionComment
has text: `C:` isn't a path. It's a drive letter *without* a path
comment on: http://stackoverflow.com/q/48810950
score: 0

http://stackoverflow.com/comment/84882686
has text: it will print something like `', How are Tim doing'` with an extra space between `Tim` and `doing`.
comment on: http://stackoverflow.com/a/48937834
score: 0
type: AnswerComment
type: Comment

pygame
tags question: http://stackoverflow.com/q/48876935
tags question: http://stackoverflow.com/q/48838842
tags question: http://stackoverflow.com/q/48887664
tags question: http://stackoverflow.com/q/48835136
tags question: http://stackoverflow.com/q/48898263
tags question: http://stackoverflow.com/q/48952459
tags question: http://stackoverflow.com/q/48885785
tags question: http://stackoverflow.com/q/48876373
tags question: http://stackoverflow.com/q/48948861
tags question: http://stackoverflow.com/q/48919961
tags question: http://stackoverflow.com/q/48848397
tags question: http://stackoverflow.com/q/48848185
tags question: http://stackoverflow.com/q/48847871
tags question: http://stackoverflow.com/q/48912400
tags question: http://stackoverflow.com/q/48819658
tags question: http://stackoverflow.com/q/48908625
tags question: http://stackoverflow.com/q/48812436
tags question: http://stackoverflow.com/q/48819905
tags question: http://stackoverflow.com/q/48861661
tags question: http://stackoverflow.com/q/48920570
tags question: http://stackoverflow.com/q/48907925
tags question: http://stackoverflow.com/q/48960034
tags question: http://stackoverflow.com/q/48950962
tag name: pygame
tags question: http://stackoverflow.com/q/48948745
tags question: http://stackoverflow.com/q/48895582
tags question: http://stackoverflow.com/q/48836823
tags question: http://stackoverflow.com/q/48872304
tags question: http://stackoverflow.com/q/48856922
tags question: http://stackoverflow.com/q/48807879
tags question: http://stackoverflow.com/q/48851883
tags question: http://stackoverflow.com/q/48837220
tags question: http://stackoverflow.com/q/48911463
tags question: http://stackoverflow.com/q/48911436
tags question: http://stackoverflow.com/q/48841539
tags question: http://stackoverflow.com/q/48871840
tags question: http://stackoverflow.com/q/48873768
tags question: http://stackoverflow.com/q/48875255
tags question: http://stackoverflow.com/q/48842535
type: Tag

http://stackoverflow.com/q/48819561
tagged with: keras
has body: So I am trying to implement a reinforcement learning algorithm using Evolution Strategy. The principle is to clone your original model N times (let's say 100 times), apply some noise on those 100 clones, run them, check which ones are giving the best results and use that to update the original model. Now I am trying to put each of these clones in a different thread and run them all in parallel. Here is my Worker class : class WorkerThread(Thread): def __init__(self, action_dim, img_dim, sigma, sess): Thread.__init__(self) #sess = tf.Session() self.actor = ActorNetwork(sess, action_dim, img_dim) self.env = Environment() self.reward = 0 self.N = {} self.original_model = None self.sigma = sigma def setActorModel(self, model): self.original_model = model def run(self): k = 0 for l in self.actor.model.layers: if len(np.array(l.get_weights())) &gt; 0: # First generate some noise shape = (np.array(l.get_weights()[0])).shape if len(shape) == 2: self.N[k] = np.random.randn(shape[0], shape[1]) else: self.N[k] = np.random.randn(shape[0], shape[1], shape[2], shape[3]) # 2nd set weights using original model's weights and noise la = self.original_model.layers[k] self.actor.model.layers[k].set_weights((la.get_weights()[0] + self.sigma * self.N[k], la.get_weights()[1])) k += 1 ob = self.env.reset() while True: action = self.actor.predict(np.reshape(ob['image'], (1, 480, 480, 3))) ob = self.env.step(action[0]) if ob['done']: self.reward = ob['reward'] break So each worker thread has it's own model, and when running I set the weights using the original's model weights. At that point I get the following error File "/usr/local/lib/python3.6/site-packages/keras/engine/topology.py", line 1219, in set_weights K.batch_set_value(weight_value_tuples) File "/usr/local/lib/python3.6/site-packages/keras/backend/tensorflow_backend.py", line 2365, in batch_set_value assign_op = x.assign(assign_placeholder) File "/usr/local/lib/python3.6/site-packages/tensorflow/python/ops/variables.py", line 594,…
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48836869
tagged with: evolutionary-algorithm
has title: Run multiple clones of a model in parallel
tagged with: multithreading
tagged with: tensorflow
type: Question
score: 0
answer count: 1

http://stackoverflow.com/a/49000650
downvote count: 0
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48959547
answers question: http://stackoverflow.com/q/48959547
has body: So after long trial and error, and waiting on an answer that never came, I figured out how to do this myself so I thought I might help whoever was in need of this out I was able to send a request from my python cgi script using javascript like so: print "Content-Type: text/html" print "" print """ &lt;html&gt; &lt;head&gt; &lt;script&gt; function getTasks() { //put more processing in the function as needed var xmlhttp; var parameters = "This must be a string which will be the parameters you will receive in your python script"; var scriptName = "pythonScript To CommunicateWith.py"; //may be .cgi as well depending on how you are using it if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); } else { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("POST", scriptName, true); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 &amp;&amp; xmlhttp.status == 200) { //retrieve a json response and parse it into userTasks usersTasks = JSON.parse(xmlhttp.responseText); } } xmlhttp.send(parameters); } &lt;/script&gt; In my python script which the java script hits here is how I get the arguments and process them: #!usr/bin/python import sys import json args=sys.stdin.readlines() #args comes in as a list with one item in it which is the parameter that you sent in from javascript arguments=args[0] print "Content-Type: text/html" print "" def getTasks(userName): """This function will do some processing and get the required return value""" taskList=[] #read JSON file and get the info. with open("Somefile.json", 'r') as data_file: usersDictionary = json.load(data_file) data_file.close() """...do some process ing of data here, which will set some data into the list called taskList""" return taskList #Return a list of all the tasks for the user. print json.dumps(getTasks(arguments)) """convert the json to a string and print it out. what you print out here will be what you will get as a string in the .responseText of the XMLHttpRequest object"""…
type: Answer
score: 2

http://stackoverflow.com/a/48846615
has comment: http://stackoverflow.com/comment/108148673
type: Answer
has comment: http://stackoverflow.com/comment/108147444
accepted answer of: http://stackoverflow.com/q/48844600
upvote count: 9
has comment: http://stackoverflow.com/comment/108141217
has comment: http://stackoverflow.com/comment/108149909
has comment: http://stackoverflow.com/comment/108148521
answers question: http://stackoverflow.com/q/48844600
score: 9
has body: For the plot in question there is no advantage of using hexagonal binning since the hexagons have different sizes and hence would not allow a consistent binning throughout the plot. You may however use a constant binning and just shrink the cells, which do not have the maximal value. import matplotlib.pyplot as plt from matplotlib.collections import PatchCollection from matplotlib.path import Path from matplotlib.patches import PathPatch import numpy as np; np.random.seed(42) a = np.random.rand(200,2) b = np.random.rand(200) c = np.concatenate((a,np.c_[b,b]), axis=0) fig, ax = plt.subplots() hexbin = ax.hexbin(c[:,0],c[:,1],gridsize=20, linewidth=0 ) def sized_hexbin(ax,hc): offsets = hc.get_offsets() orgpath = hc.get_paths()[0] verts = orgpath.vertices values = hc.get_array() ma = values.max() patches = [] for offset,val in zip(offsets,values): v1 = verts*val/ma+offset path = Path(v1, orgpath.codes) patch = PathPatch(path) patches.append(patch) pc = PatchCollection(patches) pc.set_array(values) ax.add_collection(pc) hc.remove() sized_hexbin(ax,hexbin) plt.show() For comparisson, one may transmit the same information via a scatter plot. This code is potentially much more intuitive than the above. import matplotlib.pyplot as plt import numpy as np; np.random.seed(42) a = np.random.rand(200,2) b = np.random.rand(200) c = np.concatenate((a,np.c_[b,b]), axis=0) fig, ax = plt.subplots() h, ex, ey = np.histogram2d(c[:,0],c[:,1], bins=np.linspace(0,1,20)) X,Y = np.meshgrid(ex[:-1]+np.diff(ex)/2.,ey[:-1]+np.diff(ey)/2.) ax.scatter(X.flatten(),Y.flatten(), c=h.T.flatten(), s=h.T.flatten()**2, marker="h") plt.show()
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84655591
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48825940
score: 2
has text: use csv.reader (with StringIO) and set the delimiter with the dot.

http://stackoverflow.com/a/48945195
has comment: http://stackoverflow.com/comment/84898028
has body: Use list comprehension: df.B = df.B.apply(lambda x: [int(i) for i in x]) Or: df.B = [[int(i) for i in x] for x in df.B] print (df) A B 0 1 [1212, 2121, 323] 1 2 [2222, 2222, 323] 2 3 [3232, 2323, 323] For sets: df.B = df.B.apply(lambda x: set([int(i) for i in x])) df.B = [set([int(i) for i in x]) for x in df.B] print (df) A B 0 1 {2121, 323, 1212} 1 2 {323, 2222} 2 3 {3232, 323, 2323} But if need only convert to sets: df.B = df.B.apply(set) print (df) A B 0 1 {2121.0, 323.0, 1212.0} 1 2 {323.0, 2222.0} 2 3 {3232.0, 323.0, 2323.0} For another question use: uniq = df['cluster'].unique() df = df.dropna(subset=['songs']) df.songs = df.songs.astype(int) df = df.groupby('cluster')['songs'].apply(list).reindex(uniq, fill_value=[]) print (df) cluster 1 [11, 22] 2 [22] 3 [22, 11] 4 [] Name: songs, dtype: object
has comment: http://stackoverflow.com/comment/84897983
answers question: http://stackoverflow.com/q/48945163
has comment: http://stackoverflow.com/comment/84897488
downvote count: 0
has comment: http://stackoverflow.com/comment/84898016
has comment: http://stackoverflow.com/comment/84898097
type: Answer
has comment: http://stackoverflow.com/comment/84897021
score: 1
upvote count: 1

http://stackoverflow.com/comment/84634583
score: 0
type: Comment
type: QuestionComment
has text: You want all combinations or what?
comment on: http://stackoverflow.com/q/48815365

http://stackoverflow.com/comment/84875145
score: 0
has text: huh, doesnt allow me to split it on \n . It just splits on whatever char is in the exact half. I literally mentioned that in my post.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48934246

http://stackoverflow.com/q/48918639
tagged with: string
has body: Dataframe click to see the screenshot because I am new here, I need 10 reputation to embed pics Expected result Dataframe is imported from a csv file. 'types' and 'themes' are item's properties. 'Tags' is a long string column that contains mixed (randomly ordered) tags of each item(separated by ', '). Basically I need to do is to check if there is a correct theme tag (col_{theme}) in 'Tags' column, and if there is no, add it to 'Tags' column. For example： item 8: there is a 'col_t3' in 'Tags' column, and its theme is 't3'. so this is correct and we pass. item 1: there is a 'col_t1' in 'Tags' column, but its actual theme is 't2', so I need to replace 'col_t1' with 'col_t2' and keep other tags unchanged in the same column item 2 and item 5: there is no 'col_{theme}' tag in 'Tags' column, so I add add 'col_t1' and 'col_t5' to their 'Tags' column respectively. Please help !!
favorite count: 0
has comment: http://stackoverflow.com/comment/84844020
has comment: http://stackoverflow.com/comment/84844336
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84844160
score: 1
has comment: http://stackoverflow.com/comment/84844194
has title: python dataframe replace partial strings in a column based on other column's condition
type: Question
tagged with: conditional-statements
tagged with: dataframe
has answer: http://stackoverflow.com/a/48931044
has comment: http://stackoverflow.com/comment/84847496
accepted answer: http://stackoverflow.com/a/48931044
upvote count: 3
downvote count: 2
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/84844065

http://stackoverflow.com/q/48883493
type: Question
has comment: http://stackoverflow.com/comment/84771746
has comment: http://stackoverflow.com/comment/84772036
answer count: 2
has answer: http://stackoverflow.com/a/48884430
has comment: http://stackoverflow.com/comment/84772462
has comment: http://stackoverflow.com/comment/84771490
has body: I have a list like below: lst = [{'dt': u'Dec 22, 2017'}, {'dt': u'Dec 14, 2017'}, {'dt': u'Dec 12, 2017'}, {'dt': u'NA'}, {'dt': u'December 1st'}, {'dt': u'Feb 1, 2018'}, {'dt': u'January 31'}, {'dt': u'Oct 31, 2017'}, {'dt': u'July 11'}, {'dt': u'Jan 22, 2018'},{'dt': u'Thursday'}] lst.sort(key=lambda item:item['dt'], reverse=True) print lst [{'dt': u'Thursday'}, {'dt': u'Oct 31, 2017'}, {'dt': u'NA'}, {'dt': u'July 11'}, {'dt': u'January 31'}, {'dt': u'Jan 22, 2018'}, {'dt': u'Feb 1, 2018'}, {'dt': u'December 1st'}, {'dt': u'Dec 22, 2017'}, {'dt': u'Dec 14, 2017'}, {'dt': u'Dec 12, 2017'}] But my output should be like below. [{'dt': u'Feb 1, 2018'},{'dt': u'Jan 22, 2018'},{'dt': u'Dec 22, 2017'}, {'dt': u'Dec 14, 2017'}, {'dt': u'Dec 12, 2017'},{'dt': u'Oct 31, 2017'},{'dt': u'December 1st'},{'dt': u'July 11'}, {'dt': u'January 31'},{'dt': u'Thursday'},{'dt': u'NA'}] The elements should be sorted in the following order: First strings with month, day, and year (present to past) then those with only month and day (December to January) then with 'NA'
has comment: http://stackoverflow.com/comment/84771402
has comment: http://stackoverflow.com/comment/84771351
possible better answer: http://stackoverflow.com/a/48884252
has answer: http://stackoverflow.com/a/48884252
tagged with: python
has title: python list dict sorting based on date existence
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/48884430
type: AnsweredQuestion
score: 0

http://stackoverflow.com/q/48902085
favorite count: 0
accepted answer: http://stackoverflow.com/a/48902132
linked to: http://stackoverflow.com/q/1747817
downvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/84809487
has comment: http://stackoverflow.com/comment/84810662
has answer: http://stackoverflow.com/a/48902132
tagged with: python-3.x
upvote count: 0
linked to: http://stackoverflow.com/q/209840
has comment: http://stackoverflow.com/comment/84809659
score: -3
tagged with: dictionary
duplicate of: http://stackoverflow.com/q/209840
type: AnsweredQuestion
tagged with: list
type: Question
has title: Python3: How to make dictionary from list using 'dict' and 'zip'?
answer count: 1
has body: I'm learning Python3. I can't solve a problem... Please help me. I could input 2 different strings(One is consisted with string another is consisted with float). I'd like to make a dictionary from 2 different lists. I made first one for key, another is for value. input1 = list(map(str, input().split())) input2 = list(map(float, input().split())) # output = dict(zip(input1), (input2)) output = dict((input1, input2) for (input1[i], input2[i]) in range(0, len(input2))) print(output) Don't care too much that comment(#) I found a post may help my probelm from stack overflow. Create a dictionary with list comprehension in Python I did my best but I coudn't solve this...(New one below # comment, It is what I tried to reading that post) Thanks to read my question!

bazel
tags question: http://stackoverflow.com/q/48944682
type: Tag
tags question: http://stackoverflow.com/q/48810317
tag name: bazel

http://stackoverflow.com/a/48867816
type: Answer
upvote count: 5
downvote count: 0
has body: I suggest you to override the serializer and your list method. Serializer: class PersonSerializer(models.Serializer): personal_data = serializers.DictField() class Meta: model = Person make a function to add personal_data dictionary to persons object. Use this method before giving the list of person objects to the serializer. def prepare_persons(persons): person_ids = [p.uuid for p in persons] personal_data_list = Microservice.objects.custom_filter(uuid__in=person_ids) personal_data_dict = {pd['uuid']: pd for pd in personal_data_list} for p in persons: p.personal_data = personal_data_dict[p.id] return persons def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) page = self.paginate_queryset(queryset) if page is not None: page = prepare_persons(page) serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) else: persons = prepare_persons(queryset) serializer = self.get_serializer(persons, many=True) return Response(serializer.data)
score: 5
answers question: http://stackoverflow.com/q/48804687

http://stackoverflow.com/q/48829633
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has body: I have a two dimensional array of the form data = array([ [ 0.23 , 0.61070541], [ 1.12 , 0.94622007], [ 2.33 , 0.20868555], [ 3.23 , 0.26452314], [ 4.67 , 0.93988767], [ 5.17 , 0.05736691], [ 6.74 , 0.54063927], [ 7.58 , 0.3045981 ], [ 8.48 , 0.13873822], [ 9.47 , 0.27759926], [ 10.12 , 0.27030156]]) and i want to find the maximum in the second column limited to a interval given by the first column. I want to look in the rows 5 to 8 and find the maximum row index for the maximum in the second column. In the given data set that would be row 6, data[6] = 6. , 0.54063927. My goal is to get index 6 using numpy. So far i would have done data_interval = data[ np.where( (data[:,0] &gt; 5) &amp; data[:,0] &lt; 9 ) ] max_interval = data_interval.max(axis = 0)[1] index = np.where(data == [None, max_interval])[0] This works if the maximum value does not appear another time in the data outside the interval. Otherwise i would get in the last np.where call multiple indices. Overall this feels unwieldy and i was wondering if there was a faster way that yields only the index in the interval. I want the absolut index in respect to the total data array, not the index of the data_interval array. Generally i find it difficult to do sorting/searching data in numpy for data sets that comes pairwise like (x,y) based only on x or y once the data is together in an array. Hints/Advice for handling such problems are welcome.
accepted answer: http://stackoverflow.com/a/48829768
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48829768
tagged with: search
upvote count: 2
tagged with: max
tagged with: intervals
answer count: 1
favorite count: 0
has title: Numpy Find Index of Maximum Value inside small range of array

http://stackoverflow.com/q/48816457
has answer: http://stackoverflow.com/a/48816657
has title: pandas ffill based on condition in another column
type: AnsweredQuestion
tagged with: dataframe
score: 12
type: Question
accepted answer: http://stackoverflow.com/a/48816657
upvote count: 12
answer count: 1
downvote count: 0
favorite count: 0
has body: I have a pandas DataFrame as shown below. df = pd.DataFrame({ 'date': ['2011-01-01', '2011-01-01', '2011-02-01', '2011-02-01', '2011-03-01', '2011-03-01', '2011-04-01', '2011-04-01'], 'category': [1, 2, 1, 2, 1, 2, 1, 2], 'rate': [0.5, 0.75, np.nan, np.nan, 1, 1.25, np.nan, np.nan] }) I want to use ffill to forward fill the values of rate, except that I want each value to correspond also to the appropriate category. How can I get df to look like this?: df category date rate 1 2011-01-01 0.50 2 2011-01-01 0.75 1 2011-02-01 0.50 2 2011-02-01 0.75 1 2011-03-01 1.00 2 2011-03-01 1.25 1 2011-04-01 1.00 2 2011-04-01 1.25
tagged with: pandas
tagged with: python

http://stackoverflow.com/a/48884396
type: Answer
accepted answer of: http://stackoverflow.com/q/48883443
answers question: http://stackoverflow.com/q/48883443
has comment: http://stackoverflow.com/comment/84774818
has body: I think you should try, this might give your ans self.widget.geometry().height() - self.any_tab_name.geometry().height() Second portion will give height of tabs("Demo","tab_name"), subtract that from tabwidget height.
score: 0
has comment: http://stackoverflow.com/comment/84776154
type: AcceptedAnswer

http://stackoverflow.com/comment/84911905
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48952593
score: 3
has text: tried `re.compile(r'^(input|output|inout)\s+(\w+)',flags=re.M)` ?

http://stackoverflow.com/comment/85153950
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48942917
has text: You can write a small program to fetch the statements from the internet. You can also log the orders when you make them and when they are filled so you always have a record.

http://stackoverflow.com/comment/84739575
score: 0
comment on: http://stackoverflow.com/q/48867969
has text: A quick look at the [docs for `owm.weather_at_zip_code()`](http://pyowm.readthedocs.io/en/latest/pyowm.webapi25.html#pyowm.webapi25.owm25.OWM25.weather_at_zip_code) says it's _the **currently** observed weather_. To me that says the 2nd code is correct.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48945237
upvote count: 1
tagged with: python
has title: CRC CCITT (0xFFFF) Implementation in Python
score: 0
downvote count: 1
tagged with: crc16
has comment: http://stackoverflow.com/comment/84968166
answer count: 0
type: UnansweredQuestion
has body: I need to implement calculation of crc from string of zeroes and one-s like 10000000 etc I have found this code but its for CRC CCITT(XModem) POLYNOMIAL = 0x1021 PRESET = 0 def _initial(c): crc = 0 c = c &lt;&lt; 8 for j in range(8): if (crc ^ c) &amp; 0x8000: crc = (crc &lt;&lt; 1) ^ POLYNOMIAL else: crc = crc &lt;&lt; 1 c = c &lt;&lt; 1 return crc _tab = [ _initial(i) for i in range(256) ] def _update_crc(crc, c): cc = 0xff &amp; c tmp = (crc &gt;&gt; 8) ^ cc crc = (crc &lt;&lt; 8) ^ _tab[tmp &amp; 0xff] crc = crc &amp; 0xffff return crc def crc(str): crc = PRESET for c in str: crc = _update_crc(crc, ord(c)) return crc def crcb(*i): crc = PRESET for c in i: crc = _update_crc(crc, c) print crc return crc Changing PRESET to 0xFFFF as it is initial value for CRC CCITT (0xFFFF) doesnt help. Does anyone can help to rewrite or adapt this code? For reaching a result? For checking uses https://www.lammertbies.nl/comm/info/crc-calculation.html Downloading and installation crc16 library not allowed due security reasons Python2.7
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84949323
tagged with: crc

http://stackoverflow.com/q/48813490
has comment: http://stackoverflow.com/comment/84630707
tagged with: python
upvote count: 4
possible better answer: http://stackoverflow.com/a/54767372
has comment: http://stackoverflow.com/comment/84630614
has answer: http://stackoverflow.com/a/54767372
has title: Pandas read_excel returning 'not enough values to unpack (expected 2, got 1)'
has comment: http://stackoverflow.com/comment/84630799
type: Question
has comment: http://stackoverflow.com/comment/84631443
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/84631420
accepted answer: http://stackoverflow.com/a/48934263
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84631483
has body: My problem is pretty simple, I'm just trying to read a locally located excel file into a dataframe using pandas. filename = 'test.xlsx' df = pd.read_excel(filename) The xlsx file has multiple sheets, but I get the same "ValueError: not enough values to unpack (expected 2, got 1)" even when specifying sheetname. Traceback (most recent call last): File "", line 1, in pd.read_excel(filename) File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel.py", line 200, in read_excel io = ExcelFile(io, engine=engine) File "C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\excel.py", line 257, in init self.book = xlrd.open_workbook(io) File "C:\ProgramData\Anaconda3\lib\site-packages\xlrd__init__.py", line 422, in open_workbook ragged_rows=ragged_rows, File "C:\ProgramData\Anaconda3\lib\site-packages\xlrd\xlsx.py", line 833, in open_workbook_2007_xml x12sheet.process_stream(zflo, heading) File "C:\ProgramData\Anaconda3\lib\site-packages\xlrd\xlsx.py", line 553, in own_process_stream self.do_merge_cell(elem) File "C:\ProgramData\Anaconda3\lib\site-packages\xlrd\xlsx.py", line 609, in do_merge_cell first_cell_ref, last_cell_ref = ref.split(':') ValueError: not enough values to unpack (expected 2, got 1) Edit: I created a new Excel file, and copied two of the tabs from the original file over to the new Excel file. Pandas read_excel worked with the new file. However, I want to be able to work from the original.
has comment: http://stackoverflow.com/comment/84635583
answer count: 2
tagged with: python-import
tagged with: pandas
has answer: http://stackoverflow.com/a/48934263
downvote count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84633106
has comment: http://stackoverflow.com/comment/84635304

http://stackoverflow.com/q/48887720
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: utf-8
has answer: http://stackoverflow.com/a/48887978
accepted answer: http://stackoverflow.com/a/48887978
tagged with: export-to-excel
type: Question
type: AnsweredQuestion
has title: How to return multiple coulmns in a csv with correct format
answer count: 1
tagged with: utf-16
score: 0
has body: It's my first time posting here, and I'm new to working with python in my job. I've googled and trouble shot this to my best ability. Summary: I'm trying to take a file of usernames and file names and rip out all of the non utf8 characters. In the list of 40k or so records for file name, there are a mix of utf8, utf16, and other language encodings. Problem: I can't get python to correctly format the csv with both username and non utf8 file name. I can't get it to make a new tab and line for each record and its corresponding user. My print statement works exactly how I need it to look- it's perfectly delimited from what I can see. I just can't figure out out to write both columns to csv. I need the Sender_Email column to keep my primary key for some later joins. Here's what my source csv looks like: sender_email, file_name test@test.com, utf16filename.xlxs tester@test.com, utf16filename.xlxs mrstest@test.com, utf8filename1.pptx mctestertester@test.com, utf8filename2.pdf mrstest@test.com, utf8filename3.docx mctesterson@test.com, utf8filename4.docx mrstest@test.com, utf8filename5.docx Desired output: Rip all the non-utf8 or ascii characters out sender_email, file_name mrstest@test.com, utf8filename1.pptx mctestertester@test.com, utf8filename2.pdf mrstest@test.com, utf8filename3.docx mctesterson@test.com, utf8filename4.docx mrstest@test.com, utf8filename5.docx What I have so far- The print statement is exactly what I need and it works. All of my results in the file name output are utf8 when view them in Terminal from what I can see by spot checking. The code also works when I just write the file_names column without my Sender_Email column. I can only get the csv to format correctly if I just write the file_name column, but then I lose my primary key (sender_email). import csv with open ('MixedUTF8andUTF16FileNamesAndSenderEmail.csv', 'r') as inFile: readFile = csv.reader(inFile) for row in readFile: try: sender_email = row[0] file_names = row[1].decode('ascii') print se…

http://stackoverflow.com/q/48810310
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 4
downvote count: 0
has title: evaluate the Matern kernel with custom distances
has answer: http://stackoverflow.com/a/68851337
type: Question
tagged with: gaussian
score: 4
has body: I'm trying to evaluate the matern kernel from the scikit learn package. So basically, I do something like this import numpy as np from sklearn.gaussian_process.kernels import Matern as skMatern locs=np.array([[0, 0], [0, 0.5], [0.5, 0.7]]) K = skMatern(nu=1.8, length_scale=0.2) covMat = K(locs) My problem is that I want to be able to determine the way the kernel calculates distances between the points. In other words, the code I have above calculates where is the Matern covariance function and , are rows of the locs array. What I would like is to calculate and be able to specify d myself (maybe as a distance matrix). I've been looking at the scikit-learn documentation but haven't been able to figure out how to do it. Thanks for your help!
answer count: 1
tagged with: scikit-learn

http://stackoverflow.com/comment/84930111
type: Comment
comment on: http://stackoverflow.com/q/48961738
has text: @KlausD.I honestly had a hard time to make this small single loop.I have no ideia of how to improve the code, making it to request mulltiple tasks at the same time. I am starting in python.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48818411
downvote count: 1
has body: key param with the max function is used to notify max on which value you want to perform max operation. itemgetter(2) fetches the value at 2nd index, and lexicographically "PM" is the highest value in the list at index 2 (lexicographically 'PM' > 'AM'). You may use a lambda function to calculate the maximum on tuple at index 0 and 1 as: &gt;&gt;&gt; timeList = [('4', '12', 'PM'), ('8', '23', 'PM'), ('4', '03', 'AM'), ('1', '34', 'AM'), ('12', '48', 'PM'), ('4', '13', 'AM'), ('11', '09', 'AM'), ('3', '12', 'PM'), ('4', '10', 'PM')] # type-casting it to `int` to avoid incorrect result # due lexicographical comparision of `str` &gt;&gt;&gt; max(timeList, key=lambda x: (x[2], int(x[0]), int(x[1]))) ('12', '48', 'PM') # ^ ^ ^ Third priority to `int` value of minute # ^ ^ Second priority to int value of `hour` # ^ First priority to lexicographically sort on `AM`/`PM` OR, you perform the comparison on datetime.datetime object as: &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; max(timeList, key=lambda x: datetime.strptime('{}:{}{}'.format(*x), '%I:%M%p')) ('8', '23', 'PM') I think you should have created the list of datetime.datetime instead of time tuples initially.
score: 2
answers question: http://stackoverflow.com/q/48818380
has comment: http://stackoverflow.com/comment/84640813
type: Answer
has comment: http://stackoverflow.com/comment/84641989
upvote count: 3

http://stackoverflow.com/q/48825785
tagged with: python
score: 19
has answer: http://stackoverflow.com/a/48826574
has comment: http://stackoverflow.com/comment/84686441
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48869963
downvote count: 1
tagged with: tensorflow
has title: How can I filter tf.data.Dataset by specific values?
type: Question
upvote count: 20
tagged with: tensorflow-datasets
possible better answer: http://stackoverflow.com/a/66040707
has answer: http://stackoverflow.com/a/66040707
accepted answer: http://stackoverflow.com/a/48869963
has body: I create a dataset by reading the TFRecords, I map the values and I want to filter the dataset for specific values, but since the result is a dict with tensors, I am not able to get the actual value of a tensor or to check it with tf.cond() / tf.equal. How can I do that? def mapping_func(serialized_example): feature = { 'label': tf.FixedLenFeature([1], tf.string) } features = tf.parse_single_example(serialized_example, features=feature) return features def filter_func(features): # this doesn't work #result = features['label'] == 'some_label_value' # neither this result = tf.reshape(tf.equal(features['label'], 'some_label_value'), []) return result def main(): file_names = ["/var/data/file1.tfrecord", "/var/data/file2.tfrecord"] dataset = tf.contrib.data.TFRecordDataset(file_names) dataset = dataset.map(mapping_func) dataset = dataset.shuffle(buffer_size=10000) dataset = dataset.filter(filter_func) dataset = dataset.repeat() iterator = dataset.make_one_shot_iterator() sample = iterator.get_next()
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/50220751

http://stackoverflow.com/a/48829840
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84667789
has body: Assuming there is a real camera attached to your computer, you will need to look into the camera driver to accomplish that. This process is a unique to your camera model and manufacturer. If you are lucky, you might even be able to find a 3rd party library that does exactly that (for your particular camera) and offers a module to do it more easily in Python. Good luck!
downvote count: 0
has comment: http://stackoverflow.com/comment/84663579
type: Answer
answers question: http://stackoverflow.com/q/48827085

http://stackoverflow.com/comment/84873333
has text: Nitpick: going with `[-1]` is safer imho.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48933315
type: Comment

http://stackoverflow.com/comment/84923593
type: QuestionComment
score: 0
has text: Why without selenium?
type: Comment
comment on: http://stackoverflow.com/q/48958010

http://stackoverflow.com/comment/84889414
has text: As in 1 or 0. So I have a neuron on the first hidden layer containing a value of 0.65 (after my sigmoid has collapsed it), which is above my threshold so I fire the neuron. Is the output 1, or is it 0.65 and why?
score: 0
comment on: http://stackoverflow.com/q/48941188
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48936139
has comment: http://stackoverflow.com/comment/84880021
answer count: 1
duplicate of: http://stackoverflow.com/q/23327293
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/84879074
has comment: http://stackoverflow.com/comment/84879347
has answer: http://stackoverflow.com/a/48936712
has comment: http://stackoverflow.com/comment/84879866
has comment: http://stackoverflow.com/comment/84879559
tagged with: python
has comment: http://stackoverflow.com/comment/84880303
has comment: http://stackoverflow.com/comment/84879727
has comment: http://stackoverflow.com/comment/84880038
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48936712
has comment: http://stackoverflow.com/comment/84879454
score: -1
has body: I know a similar question has been asked before but the answers were not able to help me. I am following this tutorial: https://www.youtube.com/watch?v=zRwy8gtgJ1A but i am unable to retrieve the template 'home.html' as I get the error jinja2.exceptions.TemplateNotFound: home.html I have ensured I have the right directory. As inside the folders I have my program (App.py) as well as a folder called 'Templates' and inside that I have my 'home.html' I have tried changing the capital letters. Recreating the folder. Tried following the tutorial again but no luck what so ever. I would be really happy if you could help me. If you have any questions then feel free to hit me up: p.s my code is : from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): return render_template('home.html') if __name__=='__main__': app.run() My dictionary is like this: Program/ app.py&lt;br&gt; Templates/ home.html
type: Question
has title: Python Flask- Not able to retrieve my templates
linked to: http://stackoverflow.com/q/23327293
has comment: http://stackoverflow.com/comment/84879912
upvote count: 0

http://stackoverflow.com/q/48861546
score: 1
upvote count: 1
has title: PyQt4 Application takes time on startup for the very fist time
has comment: http://stackoverflow.com/comment/86156630
type: Question
tagged with: pyqt4
has answer: http://stackoverflow.com/a/55756507
tagged with: pyqt
downvote count: 0
answer count: 1
tagged with: tango-controls
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have developed an application using Python 2.7 and PyQt4. Usually when I start my application it start within a second, but when I do start/restart my computer an than I start application for the very first time, It takes countable amount of time. I did following module import to my application. import cStringIO import imp import os import sys import taurus import time import traceback from PyQt4 import QtCore from PyQt4 import QtGui from taurus.qt.qtgui.display import TaurusLabel from taurus.qt.qtgui.util.ui import UILoadable Then I have my main function as if __name__ == "__main__": logger.debug("In mainWindow - Executing Main function.") app = QtGui.QApplication(sys.argv) I tried using print statement and also checked time for every import. Sometimes it takes time to import lines from PyQt4 import QtCore from PyQt4 import QtGui and sometime app = QtGui.QApplication(sys.argv) takes too much time to execute. I don't know why this strange behavior is happening. My application is working on Ubuntu 16.04 and software version are PyQt4, Python 2.7, Taurus-4.1.1, PyTango 8.1.8, This behavior happens only for the first time after start up of system. Please suggest something that I can tryout. I think this is some serious issue with the tool or application developed by me. Any help is appreciated...
tagged with: qt

http://stackoverflow.com/a/48894528
score: 4
type: Answer
upvote count: 4
has body: You are missing a comma after the 'hello': 'a'. Make it: import json Services = {} Services['Refrigerator repair &amp; services'] = { 'hello': 'a', 'Brand': [ 'Bosch', 'BPL', 'Croma', 'Electrolux', 'Godrej', 'Haier', 'Hitachi', 'IFB', 'Kelvinator', 'Kenstar', 'LG', 'Lloyd', 'Panasonic', 'Samsung', 'Sansui', 'Videocon', 'Whirlpool' ] } s=json.dumps(Services)
accepted answer of: http://stackoverflow.com/q/48894501
has comment: http://stackoverflow.com/comment/84794875
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48894501

http://stackoverflow.com/comment/84778467
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48886605
has text: Please mark the answer as solved so people don’t waste time thinking the question is unresolved :)

http://stackoverflow.com/q/48956789
has title: Converting NaN in dataframe to zero
answer count: 3
tagged with: pandas
tagged with: nan
favorite count: 0
has comment: http://stackoverflow.com/comment/84920713
type: UnansweredQuestion
tagged with: python
upvote count: 15
downvote count: 0
has answer: http://stackoverflow.com/a/48956877
has answer: http://stackoverflow.com/a/78608995
has body: I have dictionary and created Pandas using cars = pd.DataFrame.from_dict(cars_dict, orient='index') and sorted the index (columns in alphabetical order cars = cars.sort_index(axis=1) After sorting I noticed the DataFrame has NaN and I wasn't sure if the really np.nan values? print(cars.isnull().any()) and all column shows false. I have tried different method to convert those "NaN" values to zero which is what I want to do but non of them is working. I have tried replace and fillna methods and nothing works Below is sample of my dataframe.. speedtest size toyota 65 NaN honda 77 800
has answer: http://stackoverflow.com/a/62370485
type: Question
has comment: http://stackoverflow.com/comment/84920497
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84920516
score: 15
tagged with: replace

http://stackoverflow.com/a/77254467
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48919279
type: Answer
has body: Thanks for brining up this question as I was surprised the showcase of find examples does not mention this problem. I agree with your reasoning that and I have been unable to find specific justification for such an important implementation decision. If you take a look at the find method and its most significant implementation component, fastsearch, you will see that it returns -1 when unable to locate the substring, as stated in the documentation. There are no, however, indications in the code explaining why it is written in such a way. Interestingly, one of the comments includes a warning about that return value, suggesting that the developers were aware of this detail being a quirk. Why is it a problem? Imagine you have strings that contain lowercase spaceless company name-based ids that may end with inc, which you would like to remove to normalise them. In a typical scenario, you could do: s = "fastcareinc" idx = s.find("inc") >>> s[:idx] 'fastcare' However, if the name is already in your normalised form, you would end up with a severe bug that leads to a misrepresentation of the id: s = "fastcare" idx = s.find("inc") >>> s[:idx] 'fastcar' Above, the name has been altered from "fastcare" to "fastcar", because the variable idx is -1, thus slicing removes the last character from s. If str.find returned None, that would not be a problem: s = "fastcare" idx = None >>> s[:idx] 'fastcare' The best way to resolve this issue would be to voice it in the Python community with a PR to cPython. For now, however, I would suggest you to use str.index in lieu of str.find to avoid such situations in production code. Alternatively, I propose a workaround that would keep you away from that bug, based on the outlined scenario: >>> s[:None if (idx := s.find("inc")) == -1 else idx] 'fastcare'
score: 1

http://stackoverflow.com/comment/84752058
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48873515
has text: @juanpa.arrivillaga Originally I was trying to import all csv files in a folder as dataframes. Each dataframe would have the name of the csv file (minus the extension). I couldn't figure out how to have them all as "independent" dataframes without putting them in a dictionary. So that's how they ended up in a dictionary. I could definitely do `name1 = df_dict['name1']` 6 different times, but I thought there might be a way to loop over all of them and do it at once without having to hard-code it. So that's why I asked the question.
score: 0

http://stackoverflow.com/q/48840267
has comment: http://stackoverflow.com/comment/84686134
type: Question
has comment: http://stackoverflow.com/comment/84685854
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48840496
has body: I have a countries.txt file that contains the following sample text: [Country "Kenya"]\n[CapitalCity "Nairobi"]\n\n [Country "Uganda"]\n[CapitalCity "Kampala"]\n\n [Country "Tanzania"]\n[CapitalCity "Dodoma"]\n\n The country can have up to 20 attributes. For simplicity, i have only included Country and CapitalCity. I need a regex that works in python that will return for the sample data above: a) n matches, in the above case n=3 b) Each match should have m groups, in this case m=2: Country and CapitalCity I have read this https://www.regular-expressions.info/captureall.html but cannot seem to get it to work for my usecase. I have tried this (\[([A-Za-z]+)\s\"([^\"]*)\"\]\\n\\n)+ here https://regex101.com/r/cujIDd/1 but it does not give me the Country. EDIT: Expected input and output Example 1: input [Country "Kenya"]\n[CapitalCity "Nairobi"]\n\n [Country "Uganda"]\n[CapitalCity "Kampala"]\n\n [Country "Tanzania"]\n[CapitalCity "Dodoma"]\n\n expected output matches: 3 match 1: Country: Kenya CapitalCity: Nairobi match 2: Country: Uganda CapitalCity: Kampala match 3: Country: Tanzania CapitalCity: Dodoma Example 2: input [Country "Kenya"]\n[CapitalCity "Nairobi"]\n[President "Kenyatta"]\n\n [Country "Uganda"]\n[CapitalCity "Kampala"]\n[President "Museveni"]\n\n [Country "Tanzania"]\n[CapitalCity "Dodoma"]\n[President "Magufuli"]\n\n expected output matches: 3 match 1: Country: Kenya CapitalCity: Nairobi President: Kenyatta match 2: Country: Uganda CapitalCity: Kampala President: Museveni match 3: Country: Tanzania CapitalCity: Dodoma President: Magufuli Example 3: input [Country "Kenya"]\n[CapitalCity "Nairobi"]\n[President "Kenyatta"]\n[Continent "Africa"]\n\n [Country "Uganda"]\n[CapitalCity "Kampala"]\n[President "Museveni"]\n[Continent "Africa"]\n\n [Country "Tanzania"]\n[CapitalCity "Dodoma"]\n[President "Magufuli"]\n[Continent "Africa"]\n\n expected output matches: 3 match 1: Country: Kenya CapitalCity: Nairobi President: Kenyatta Continent: Africa match 2: Coun…
tagged with: python
tagged with: regex
has answer: http://stackoverflow.com/a/48841019
favorite count: 0
type: UnansweredQuestion
upvote count: 1
has comment: http://stackoverflow.com/comment/84684714
has title: Regex to match repeating groups in python
score: 1
has comment: http://stackoverflow.com/comment/84684781

http://stackoverflow.com/comment/84861879
has text: For your first problem, your derivative is `0` at `a=0`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48926943
score: 1

http://stackoverflow.com/comment/84934932
score: 1
comment on: http://stackoverflow.com/a/48963987
type: AnswerComment
has text: Wow, that's exactly what I wanted to do. I'll try to implement it by myself, and if I get stuck, I will look at your code. I'd like to know if this method works with other puzzles too, but I'll have to wait. Thanks!
type: Comment

http://stackoverflow.com/comment/84725503
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48845663
has text: @wessport I guess that would be a way of approaching it. Or you could loop and put an 'if' statement inside.
score: 0

http://stackoverflow.com/comment/84896388
score: 0
type: QuestionComment
type: Comment
has text: Floats are the default type for numpy arrays.
comment on: http://stackoverflow.com/q/48944783

http://stackoverflow.com/comment/84778889
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48887007
has text: your dataframe columns seem to contain many tabs in front of and after their real names; thus not matching the db columns
score: 0

http://stackoverflow.com/a/48814268
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48814098
has body: Assuming you are starting with a list of lists of strings, you could do this: dataset = [ ['food=3', 'party=2'], ['word=2', 'apple=3'], ] def multiply_word(item): word, freq = item.split('=') return [word] * int(freq) result = [ sum((multiply_word(item) for item in row), []) for row in dataset ] result # [ # ['food', 'food', 'food', 'party', 'party'], # ['word', 'word', 'apple', 'apple', 'apple'] # ] Or you could use this "one-liner" (inspired by @jp_data_analysis's answer): [ sum( ([word] * int(freq) for word, freq in (item.split('=') for item in row)), [] ) for row in dataset ] If you have a lot of words in each row, then you should probably use itertools.chain instead of sum. See why sum on lists is (sometimes) faster than itertools.chain? .
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48814098

http://stackoverflow.com/a/49065611
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/48880273
downvote count: 0
score: 4
has body: You're on the right track. Usually, you would either balance your data set before training, i.e. reducing the over-represented class or generate artificial (augmented) data for the under-represented class to boost its occurrence. Reduce over-represented class This one is simpler, you would just randomly pick as many samples as there are in the under-represented class, discard the rest and train with the new subset. The disadvantage of course is that you're losing some learning potential, depending on how complex (how many features) your task has. Augment data Depending on the kind of data you're working with, you can "augment" data. That just means that you take existing samples from your data and slightly modify them and use them as additional samples. This works very well with image data, sound data. You could flip/rotate, scale, add-noise, in-/decrease brightness, scale, crop etc. The important thing here is that you stay within bounds of what could happen in the real world. If for example you want to recognize a "70mph speed limit" sign, well, flipping it doesn't make sense, you will never encounter an actual flipped 70mph sign. If you want to recognize a flower, flipping or rotating it is permissible. Same for sound, changing volume / frequency slighty won't matter much. But reversing the audio track changes its "meaning" and you won't have to recognize backwards spoken words in the real world. Now if you have to augment tabular data like sales data, metadata, etc... that's much trickier as you have to be careful not to implicitly feed your own assumptions into the model.

http://stackoverflow.com/comment/84768644
type: AnswerComment
score: 0
has text: @barciewicz Upvote this/any Answer which is/was useful to you for the benefit of future readers.
type: Comment
comment on: http://stackoverflow.com/a/48855222

http://stackoverflow.com/a/48845165
type: AcceptedAnswer
has body: You can't specify custom font folders, but it is possible to add individual fonts using the QFontDatabase class. So all you need to do is iterate over the files in a given folder and add any font files it contains. The documentation notes these limitations: Currently only TrueType fonts, TrueType font collections, and OpenType fonts are supported. Note: Adding application fonts on Unix/X11 platforms without fontconfig is currently not supported. Once all the valid font files have been added, they will show up immediately in the font-dialog. Here is a simple demo (only tested on Linux): import sys, os, glob from PyQt5 import QtCore, QtGui, QtWidgets class Window(QtWidgets.QWidget): def __init__(self): super(Window, self).__init__() self.button1 = QtWidgets.QPushButton('Open Font Folder') self.button1.clicked.connect(self.handleButton1) self.button2 = QtWidgets.QPushButton('Show Font Dialog') self.button2.clicked.connect(self.handleButton2) self.fontList = QtWidgets.QListWidget() layout = QtWidgets.QVBoxLayout(self) layout.addWidget(self.fontList) layout.addWidget(self.button1) layout.addWidget(self.button2) def handleButton1(self): path = QtWidgets.QFileDialog.getExistingDirectory(self) if path: fonts = set() self.fontList.clear() db = QtGui.QFontDatabase() db.removeAllApplicationFonts() for filename in glob.glob(os.path.join(path, '*.ttf')): fontid = db.addApplicationFont(os.path.join(path, filename)) if fontid &gt;= 0: fonts.update(db.applicationFontFamilies(fontid)) self.fontList.addItems(sorted(fonts)) self.fontList.setCurrentRow(0) def handleButton2(self): font = QtGui.QFont() item = self.fontList.currentItem() if item is not None: font.setFamily(item.text()) QtWidgets.QFontDialog.getFont(font, self) if __name__ == '__main__': app = QtWidgets.QApplication(sys.argv) window = Window() window.setGeometry(600, 100, 200, 200) window.show() sys.exit(app.exec_())
type: Answer
accepted answer of: http://stackoverflow.com/q/48839658
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48839658
upvote count: 2

http://stackoverflow.com/a/48821633
has comment: http://stackoverflow.com/comment/84647002
accepted answer of: http://stackoverflow.com/q/48821402
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48821402
upvote count: 1
has body: Why don't you just do: a = list(map(int,input().split())) Say your input is "1 2 3 4 5", a will be [1, 2, 3, 4, 5], and you can use its elements however you want.

http://stackoverflow.com/a/48938692
type: Answer
has comment: http://stackoverflow.com/comment/84885035
score: 0
has body: num = '7/8'.split('/') dec = int(num[0]) / int(num[1])
answers question: http://stackoverflow.com/q/48938632

http://stackoverflow.com/q/48818659
favorite count: 0
tagged with: compare
tagged with: python
has body: I'm trying to make a soccer division and get both the first and second place of the teams after playing their respective matches, I need to do this by comparing their total wins and in case of tie, by difference of total goals. This is the class for the team: class Equipo: pais = None media_gol = 0 penal = 0 nextGol = 0 puntos_divisionales = 0 dif_goles = 0 def __init__(self, pais, mg, pen): self.pais = pais self.media_gol = mg self.penal = pen def getPais(self): return self.pais def getMedia(self): return self.media_gol def getPenal(self): return self.penal def getGol(self): return self.nextGol def getPuntos(self): return self.puntos_divisionales def getDif(self): return self.dif_goles def setNextGol(self, gol): self.nextGol += gol def setGol(self, gol): self.nextGol = gol def setDif(self, dif): self.dif_goles = dif def incPuntos(self): self.puntos_divisionales += 1 And this is the Division class: class Division: primerLugar = None segundoLugar = None equipo1 = None equipo2 = None equipo3 = None equipo4 = None equipos = [equipo1, equipo2, equipo3, equipo4] matches = [] def __init__(self, e1, e2, e3, e4): self.equipo1 = e1 self.equipo2 = e2 self.equipo3 = e3 self.equipo4 = e4 def get1(self): return self.primerLugar def get2(self): return self.segundoLugar def match(self): self.matches.append([self.equipo1, self.equipo2]) self.matches.append([self.equipo1, self.equipo3]) self.matches.append([self.equipo1, self.equipo4]) self.matches.append([self.equipo2, self.equipo3]) self.matches.append([self.equipo2, self.equipo4]) self.matches.append([self.equipo3, self.equipo4]) def winner(self): for m in self.matches: p = Partido(m[0], m[1]) p.tiempoPartido() p.scoreGoles() p.getGanador().incPuntos() Class "Partido" is just the game between both teams and the calculator for goals and winner. I need to decide the winner in the Division Class
type: UnansweredQuestion
upvote count: 1
score: 1
tagged with: class
type: Question
has answer: http://stackoverflow.com/a/48819320
answer count: 1
downvote count: 0
has title: get first and second place of a game

http://stackoverflow.com/q/48883694
has comment: http://stackoverflow.com/comment/84773254
accepted answer: http://stackoverflow.com/a/48907074
type: AnsweredQuestion
answer count: 1
downvote count: 0
score: 1
favorite count: 0
type: Question
has comment: http://stackoverflow.com/comment/84785015
tagged with: field
has comment: http://stackoverflow.com/comment/84772276
tagged with: python
has comment: http://stackoverflow.com/comment/84779649
has answer: http://stackoverflow.com/a/48907074
tagged with: dynamic
tagged with: odoo
has comment: http://stackoverflow.com/comment/84773179
upvote count: 1
tagged with: selection
has body: I am stuck with this problem anybody could help ? I would like to get a list of present product in stock.pack.operation for a certain picking_id. I pass the picking_id using a context via the form view. When I try to setup the Selection Field i got nothing but when I try with a Char field it works. Here is the code: def _default_products_list(self): active_id = self.env.context.get('default_picking_id', []) or [] vals=[] for record in self.env['stock.pack.operation'].search([('picking_id','=',active_id)]): vals.extend([(record.product_id.name,record.product_id.name)]) return vals name = fields.Char(string='test', required=True, default=_default_products_list) product = fields.Selection(_default_products_list, string="Product")
has comment: http://stackoverflow.com/comment/84818385
has comment: http://stackoverflow.com/comment/84772902
has title: Odoo 9 - Dynamic Selection field depending context
has comment: http://stackoverflow.com/comment/84773789

http://stackoverflow.com/q/48953373
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84913814
score: 1
accepted answer: http://stackoverflow.com/a/48955947
has comment: http://stackoverflow.com/comment/84913660
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84913766
has body: I have a numpy array which when print-ed looks like this: print(a.shape) (21,) print(a) [array([8.55570588e+03, 4.23078573e+05, 2.81254715e+07, 2.10356201e+09, 4.24558286e+05, 2.10032147e+07, 1.39638949e+09, 1.04453957e+11, 2.81593475e+07, 1.39354786e+09, 9.26480296e+10, 6.92992796e+12, 2.10047682e+09, 1.03982525e+11, 6.91296507e+12, 5.17021191e+14]) array([8.55404706e+03, 4.23328400e+05, 2.80891690e+07, 2.09651453e+09, 4.23874124e+05, 2.09628073e+07, 1.39044370e+09, 1.03745119e+11, 2.81060928e+07, 1.38935279e+09, 9.21288996e+10, 6.87207671e+12, 2.09626303e+09, 1.03584989e+11, 6.86712650e+12, 5.12107449e+14]) array([6.71569608e+03, 3.32364057e+05, 2.20526342e+07, 1.64564735e+09, 3.32826578e+05, 1.64539763e+07, 1.09116635e+09, 8.13888141e+10, 2.20612069e+07, 1.08976996e+09, 7.22409501e+10, 5.38629510e+12, 1.64474898e+09, 8.11907944e+10, 5.38026989e+12, 4.01021156e+14]) array([ 97, 120, 147, 106, 115, 151, 300, 268, 326, 454, 684, 1594, 2202, 2229, 1205, 2]) array([ 1, 0, 0, 0, 0, 1, 0, 1, 0, 2, 1, 11, 359, 1355, 3921, 4348]) array([ 1, 0, 0, 1, 0, 0, 6, 11, 31, 644, 2312, 3046, 3618, 321, 7, 2]) 625.0 625.0 625.0 537178.875 1874648.75 1373895.875 1.275734191674592 2.066594119913508 1.6749058704798478 0.11276410212887233 2.55304393588347 1.1167704949278905 2.177796835501801 1.1323869527951895 1.3940068452456151] Ideally I would want all of these values in one big array of length (3*16 + 3*16 + 15) np.concatenate did not work, flatten also did bring the desired result.
tagged with: numpy
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48955947
favorite count: 0
has comment: http://stackoverflow.com/comment/84913640
has comment: http://stackoverflow.com/comment/84914701
has comment: http://stackoverflow.com/comment/84913801
has title: Cant seem to flatten numpy array

http://stackoverflow.com/a/48859831
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48857018
has comment: http://stackoverflow.com/comment/84749246
accepted answer of: http://stackoverflow.com/q/48857018
type: Answer
has comment: http://stackoverflow.com/comment/84749443
has comment: http://stackoverflow.com/comment/84723707
has comment: http://stackoverflow.com/comment/84752125
has comment: http://stackoverflow.com/comment/84750881
has body: This code reads in the file you provided, removes the unwanted characters in one pass (VS creating a new string for each use of .replace) and saves the word counts in a dict called result. The keys are the doc nums ('XXX9' -> 'tf9') and the values are collections.Counter objects with the word counts. &gt;&gt;&gt; import re ... from collections import Counter ... ... with open('filename.txt', 'r') as f: ... data = f.read().lower() ... ... clean_data = re.sub(r'[,"./()]', '', data) ... ... result = {} ... for line in clean_data.splitlines(): ... if not line: ... continue # skip blank lines ... elif line.startswith('xxx'): ... doc_num = 'tf{}'.format(line[3:]) ... else: ... result[doc_num] = Counter(line.split()) ... &gt;&gt;&gt; list(result.keys()) ['tf7', 'tf10', 'tf5', 'tf2', 'tf9', 'tf4', 'tf11', 'tf3', 'tf6', 'tf8', 'tf1'] &gt;&gt;&gt; for k, v in list(result['tf1'].items())[:15]: ... print("'{}': {}".format(k, v)) ... 'class': 1 'then': 1 'emerge': 1 'industry': 1 'common': 1 'ourselves': 2 'models': 1 'short': 1 'mgi': 1 'it': 1 'actionable': 1 'time': 1 'why': 1 'theory': 1 'equip': 2 Let me know if any changes need to be made to help answer your question!
score: 0
has comment: http://stackoverflow.com/comment/84752493

http://stackoverflow.com/a/72266527
downvote count: 0
answers question: http://stackoverflow.com/q/48874113
has body: I've not enough rep to comment on last submission but after testing input files with differing CRS's, gdf = gpd.GeoDataFrame(pd.concat([gpd.read_file(i) for i in path], ignore_index=True), crs=gpd.read_file(path[0]).crs) should be gdf = gpd.GeoDataFrame(pd.concat([gpd.read_file(i).to_crs(gpd.read_file(path[0]).crs) for i in path], ignore_index=True), crs=gpd.read_file(path[0]).crs)
type: Answer
upvote count: 3
score: 3

http://stackoverflow.com/q/48810391
upvote count: 2
accepted answer: http://stackoverflow.com/a/48811827
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84630319
tagged with: numpy
has comment: http://stackoverflow.com/comment/84630438
has body: I've got some trouble with the precision of my array operations. I'm doing alot of array calculations where some cells of the array have to be left out, done either by masking or, in this case, by assigning very small values neary np.finfo(float).tiny to the array cells to leave out. But during array operations this causes an error of around 1e-14 which is quite near to machine epsilon. But still I don't know where the error is coming from and how to avoid it. Since I perform these operations several million times, the errors stack up to a total error of around 2-3%. Here is my minimum working example: arr = np.arange(20).astype(float) arr[0] = 1e-290 t1 = np.random.rand(20) * 100 t2 = np.random.rand(20) * 100 a = (arr * (t1 - t2)).sum() b = (arr * (t1 - t2))[1:].sum() d = (arr * (t1 - t2))[0].sum() c = b - a print(c) # Out[99]: 4.5474735088646412e-13 To avoid this problem, I tried to mask arr: arr_mask = np.ma.masked_where(arr &lt; 1e-200, arr) a_mask = (arr_mask * (t1 - t2)).sum() b_mask = (arr_mask * (t1 - t2))[1:].sum() c_mask = b_mask - a_mask print(c_mask) # Out[118]: 4.5474735088646412e-13 Why is the difference, c so many magnitudes bigger than d, which should be the difference? I guess some machine epsilon problem from assigning such a small value to the array in the first place? But still np.finfo(float).eps with 2.2204460492503131e-16 is around a 1000 times smaller than c. How can I avoid this? Setting the elements to zero won't work, since I have lots of divisions. In this case I can't use masking to several reasons. BUT the position of the cells which have to be left out does NEVER change. So can I somehow assign a "safe" value to these cells to leave them out while altering the result of the total array operations? Thanks in advance!
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48811827
has comment: http://stackoverflow.com/comment/84629389
favorite count: 0
tagged with: precision
has comment: http://stackoverflow.com/comment/84630561
has comment: http://stackoverflow.com/comment/84626923
tagged with: python
has comment: http://stackoverflow.com/comment/84630242
has title: Numpy array operation precision with very small values
score: 2

http://stackoverflow.com/a/48950047
has body: ATSPI is an Linux accessibility technology to obtain GUI text/rectangle properties programmatically. See how to find and run ATSPI registry daemon and how to enable ATSPI for the most popular types of GUI apps. Usually it's $ /usr/libexec/at-spi-registryd &amp; There is a Python bindings for ATSPI. See this answer for details: How to install pyatspi? The pyatspi package has too many dependencies like pygobject etc. It also requires some compilation during installation steps. We think this is not user friendly so we decided to use libatspi.so directly (without any dependencies). This work status can be tracked here: https://github.com/pywinauto/pywinauto/pull/449 There is no exact deadline for pywinauto 0.7.0 with this feature (it's a hobby project), but I would say this summer sounds realistic.
answers question: http://stackoverflow.com/q/48927607
score: 0
type: Answer

http://stackoverflow.com/a/48854764
answers question: http://stackoverflow.com/q/48854663
type: Answer
score: 0
has body: You need to access first the a tag and then access it's href attribute like you would with a dictionary: &gt;&gt;&gt; titles.a['href'] 'https://therecipecritic.com/2018/02/mint-oreo-cheesecake/'

http://stackoverflow.com/comment/84657298
type: QuestionComment
has text: @BryanOakley Surely you mean that for this particular function, right? Because I think it makes the code easier to read when used properly as it indicates the scope of the nested method as narrow as they come.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48817792

keras
tags question: http://stackoverflow.com/q/48855343
tags question: http://stackoverflow.com/q/48880922
tags question: http://stackoverflow.com/q/48845016
tags question: http://stackoverflow.com/q/48953145
tags question: http://stackoverflow.com/q/48823331
tags question: http://stackoverflow.com/q/48853066
tags question: http://stackoverflow.com/q/48903689
tags question: http://stackoverflow.com/q/48846332
tags question: http://stackoverflow.com/q/48880273
tags question: http://stackoverflow.com/q/48841927
tags question: http://stackoverflow.com/q/48898104
tags question: http://stackoverflow.com/q/48957335
tags question: http://stackoverflow.com/q/48819561
tags question: http://stackoverflow.com/q/48844790
tags question: http://stackoverflow.com/q/48951109
tags question: http://stackoverflow.com/q/48956407
tags question: http://stackoverflow.com/q/48860388
tags question: http://stackoverflow.com/q/48835999
tags question: http://stackoverflow.com/q/48870598
tags question: http://stackoverflow.com/q/48893528
tags question: http://stackoverflow.com/q/48900949
tags question: http://stackoverflow.com/q/48869563
tags question: http://stackoverflow.com/q/48951409
tags question: http://stackoverflow.com/q/48852970
tags question: http://stackoverflow.com/q/48883170
tags question: http://stackoverflow.com/q/48840025
tags question: http://stackoverflow.com/q/48842303
tags question: http://stackoverflow.com/q/48950745
tags question: http://stackoverflow.com/q/48819393
tags question: http://stackoverflow.com/q/48955231
tags question: http://stackoverflow.com/q/48867173
tags question: http://stackoverflow.com/q/48934338
tags question: http://stackoverflow.com/q/48850277
tags question: http://stackoverflow.com/q/48859378
tags question: http://stackoverflow.com/q/48828478
tags question: http://stackoverflow.com/q/48942780
tags question: http://stackoverflow.com/q/48963329
tags question: http://stackoverflow.com/q/48820093
tags question: http://stackoverflow.com/q/48929098
tags question: http://stackoverflow.com/q/48954694
tags question: http://stackoverflow.com/q/48946687
tags question: http://stackoverflow.com/q/48922811
tags question: http://stackoverflow.com/q/48851558
tags question: http://stackoverflow.com/q/48908811
tags question: http://stackoverflow.com/q/48844024
tags question: http://stackoverflow.com/q/48832753
tags question: http://stackoverflow.com/q/48815087
tags question: http://stackoverflow.com/q/48817095
tags question: http://stackoverflow.com/q/48805046
tags question: http://stackoverflow.com/q/48830704
tags question: http://stackoverflow.com/q/48815350
tags question: http://stackoverflow.com/q/48901427
tags question: http://stackoverflow.com/q/48831893
tags question: http://stackoverflow.com/q/48906481
tags question: http://stackoverflow.com/q/48959914
tags question: http://stackoverflow.com/q/48930933
tags question: http://stackoverflow.com/q/48869168
tags question: http://stackoverflow.com/q/48912449
tags question: http://stackoverflow.com/q/48912038
tags question: http://stackoverflow.com/q/48890758
tags question: http://stackoverflow.com/q/48874635
tags question: http://stackoverflow.com/q/48845889
tags question: http://stackoverflow.com/q/48855290
tags question: http://stackoverflow.com/q/48952526
tags question: http://stackoverflow.com/q/48908641
tags question: http://stackoverflow.com/q/48879228
tag name: keras
tags question: http://stackoverflow.com/q/48887428
tags question: http://stackoverflow.com/q/48857864
tags question: http://stackoverflow.com/q/48844536
tags question: http://stackoverflow.com/q/48852716
tags question: http://stackoverflow.com/q/48812613
tags question: http://stackoverflow.com/q/48921326
type: Tag
tags question: http://stackoverflow.com/q/48819828
tags question: http://stackoverflow.com/q/48827687
tags question: http://stackoverflow.com/q/48810731
tags question: http://stackoverflow.com/q/48880221

http://stackoverflow.com/a/49322165
score: 6
downvote count: 0
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/48951109
has body: A naive implementation of Binary Cross Entropy will suffer numerical problem on 0 output or larger than one output, eg log(0) -&gt; NaN. The formula you posted is reformulated to ensure stability and avoid underflow. The following deduction is from tf.nn.sigmoid_cross_entropy_with_logits. z * -log(sigmoid(x)) + (1 - z) * -log(1 - sigmoid(x)) = z * -log(1 / (1 + exp(-x))) + (1 - z) * -log(exp(-x) / (1 + exp(-x))) = z * log(1 + exp(-x)) + (1 - z) * (-log(exp(-x)) + log(1 + exp(-x))) = z * log(1 + exp(-x)) + (1 - z) * (x + log(1 + exp(-x)) = (1 - z) * x + log(1 + exp(-x)) = x - x * z + log(1 + exp(-x)) For x &lt; 0, to avoid overflow in exp(-x), we reformulate the above x - x * z + log(1 + exp(-x)) = log(exp(x)) - x * z + log(1 + exp(-x)) = - x * z + log(1 + exp(x)) And the implementation use the equivalient form: max(x, 0) - x * z + log(1 + exp(-abs(x)))

http://stackoverflow.com/comment/84704774
comment on: http://stackoverflow.com/q/48849428
has text: Why have you got an infinite loop doing nothing? `while True:`
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48947836
answer count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
upvote count: 0
downvote count: 5
has body: I'm doing some practice on solving 8 puzzle. When I was searching for references, I came across this code on gitHub: def _generate_moves(self): free = self._get_legal_moves() zero = self.find(0) def swap_and_clone(a, b): p = self._clone() p.swap(a,b) p._depth = self._depth + 1 p._parent = self return p return map(lambda pair: swap_and_clone(zero, pair), free) # &lt;- what does this mean? What does the line with: return map(lambda pair: swap_and_clone(zero, pair), free) mean? What does it return? Here's the complete code on https://gist.github.com/flatline/838202
tagged with: lambda
type: AnsweredQuestion
score: -5
has comment: http://stackoverflow.com/comment/84902104
has comment: http://stackoverflow.com/comment/84902060
has answer: http://stackoverflow.com/a/48947912
accepted answer: http://stackoverflow.com/a/48947912
type: Question
has title: Can someone explain what map and lambda does?

selenium
tags question: http://stackoverflow.com/q/48833301
tags question: http://stackoverflow.com/q/48865290
tags question: http://stackoverflow.com/q/48843826
tags question: http://stackoverflow.com/q/48834199
tags question: http://stackoverflow.com/q/48945476
tags question: http://stackoverflow.com/q/48814291
tags question: http://stackoverflow.com/q/48957851
tags question: http://stackoverflow.com/q/48932642
tags question: http://stackoverflow.com/q/48953127
tags question: http://stackoverflow.com/q/48859561
tags question: http://stackoverflow.com/q/48941260
tags question: http://stackoverflow.com/q/48940274
tags question: http://stackoverflow.com/q/48885476
tags question: http://stackoverflow.com/q/48869775
tags question: http://stackoverflow.com/q/48956585
tags question: http://stackoverflow.com/q/48901728
tags question: http://stackoverflow.com/q/48923396
tags question: http://stackoverflow.com/q/48883565
tags question: http://stackoverflow.com/q/48876458
tags question: http://stackoverflow.com/q/48875911
tags question: http://stackoverflow.com/q/48909709
tags question: http://stackoverflow.com/q/48812282
tags question: http://stackoverflow.com/q/48957805
tags question: http://stackoverflow.com/q/48820860
tags question: http://stackoverflow.com/q/48855482
tags question: http://stackoverflow.com/q/48812910
tags question: http://stackoverflow.com/q/48867450
tags question: http://stackoverflow.com/q/48847881
tags question: http://stackoverflow.com/q/48961552
tags question: http://stackoverflow.com/q/48916783
tags question: http://stackoverflow.com/q/48898896
tags question: http://stackoverflow.com/q/48895434
tags question: http://stackoverflow.com/q/48867899
tags question: http://stackoverflow.com/q/48897137
tags question: http://stackoverflow.com/q/48911081
tags question: http://stackoverflow.com/q/48960059
tag name: selenium
tags question: http://stackoverflow.com/q/48860738
tags question: http://stackoverflow.com/q/48846700
tags question: http://stackoverflow.com/q/48938988
tags question: http://stackoverflow.com/q/48943349
tags question: http://stackoverflow.com/q/48839355
tags question: http://stackoverflow.com/q/48955762
tags question: http://stackoverflow.com/q/48946396
tags question: http://stackoverflow.com/q/48954842
tags question: http://stackoverflow.com/q/48891791
tags question: http://stackoverflow.com/q/48828470
tags question: http://stackoverflow.com/q/48956802
tags question: http://stackoverflow.com/q/48850545
tags question: http://stackoverflow.com/q/48829049
tags question: http://stackoverflow.com/q/48958823
tags question: http://stackoverflow.com/q/48850089
tags question: http://stackoverflow.com/q/48852976
tags question: http://stackoverflow.com/q/48844108
tags question: http://stackoverflow.com/q/48867221
tags question: http://stackoverflow.com/q/48849192
tags question: http://stackoverflow.com/q/48952920
tags question: http://stackoverflow.com/q/48905123
tags question: http://stackoverflow.com/q/48861078
tags question: http://stackoverflow.com/q/48841435
tags question: http://stackoverflow.com/q/48934915
tags question: http://stackoverflow.com/q/48932676
tags question: http://stackoverflow.com/q/48875705
tags question: http://stackoverflow.com/q/48892117
tags question: http://stackoverflow.com/q/48931459
tags question: http://stackoverflow.com/q/48850675
tags question: http://stackoverflow.com/q/48807942
tags question: http://stackoverflow.com/q/48938449
tags question: http://stackoverflow.com/q/48956036
tags question: http://stackoverflow.com/q/48814810
tags question: http://stackoverflow.com/q/48940286
tags question: http://stackoverflow.com/q/48893414
tags question: http://stackoverflow.com/q/48857871
tags question: http://stackoverflow.com/q/48878844
tags question: http://stackoverflow.com/q/48842964
tags question: http://stackoverflow.com/q/48954847
tags question: http://stackoverflow.com/q/48859312
tags question: http://stackoverflow.com/q/48883577
tags question: http://stackoverflow.com/q/48818010
tags question: http://stackoverflow.com/q/48895991

http://stackoverflow.com/a/48820766
score: 28
has comment: http://stackoverflow.com/comment/84645519
has body: I think you are right, submit a documentation patch? also you can cast the generator to a list to get around this: G.remove_nodes_from(list(nx.isolates(G))) But why does your work-around work? I don't understand it; the situation has not changed! I would have to look at their code, but my hunch is the lazyness of a generator is working against it based on the Exception message. Casting to list, the collection is created before it is fed as an argument, so there is no side effects on the object as it is iterated. As noted from @Dyz's answer, the documentation is correct, you are using Nx 2.0. https://networkx.github.io/documentation/networkx-2.0/reference/algorithms/generated/networkx.algorithms.isolate.isolates.html Does this collection creation before fed as argument behaviour hold for any kind of cast (say to dict or set) ? – Well not quite (a set will work) dict won't because it wants a pair of items. list and set when called like a function (and dict but again it needs pairs (a list of tuples will work)) calls __iter__ Generators have __iter__ which makes them iterables (+ a lot of other objects). Generators are really nice to have to address various usecases, for example when you have a large collection of items, and need to loop through them multiple times, it can save you on runtime complexity. However, there is nuances such as what you ran into, where you have to understand some of the internals for proper use.
type: AcceptedAnswer
downvote count: 0
upvote count: 28
type: Answer
has comment: http://stackoverflow.com/comment/139444872
answers question: http://stackoverflow.com/q/48820586
accepted answer of: http://stackoverflow.com/q/48820586

http://stackoverflow.com/a/48915438
answers question: http://stackoverflow.com/q/48915163
has body: Have you try making your file public via API with .set_canned_acl('public-read')? import boto import boto.s3.connection from boto.s3.key import Key conn = boto.connect_s3( aws_access_key_id = &lt;access_key&gt;, aws_secret_access_key = &lt;secret_key&gt;, host = &lt;host&gt;, calling_format = boto.s3.connection.OrdinaryCallingFormat(), ) bucket = conn.get_bucket(&lt;bucket name&gt;, validate=False) k = Key(bucket) k.key = &lt;filename&gt; k.set_contents_from_filename(&lt;filename&gt;) hello_key = bucket.get_key(&lt;filename&gt;) hello_key.set_canned_acl('public-read')
score: 0
type: Answer

http://stackoverflow.com/comment/84949627
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48962746
has text: But assigning to vector seems to be simple and flexible: alpha[i] = pymc.Normal(0, 1)
type: Comment

http://stackoverflow.com/q/48830107
has comment: http://stackoverflow.com/comment/84664159
score: 1
favorite count: 0
type: Question
upvote count: 1
tagged with: python
has title: Setting the value of one column based on three conditions of another column
linked to: http://stackoverflow.com/q/39405628
answer count: 1
has answer: http://stackoverflow.com/a/48830158
has body: I have a DataFrame with 2 columns, a and b, and I would like to populate a third column, c based on the following three conditions: if a.diff() &gt; 0 then c = b.shift() + b elif a.diff() &lt; 0 then c = b.shift() - b elif a.diff() == 0 then c = b.shift() What is a Pythonic, one-liner way of doing this? Example: a b c 0 2 10 Nan 1 3 16 26 2 1 12 4 3 1 18 12 4 3 11 29 5 1 13 -2
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48830158
downvote count: 0
tagged with: pandas
type: AnsweredQuestion

http://stackoverflow.com/a/48906116
has comment: http://stackoverflow.com/comment/84858707
has body: Update 3 I was unable to reproduce results in given sample with given ST implementation. Sorry. But I updated code to return same shape as in sample and skip NaN. Vectorization will give you huge improvement. Like 31.4 ms vectorized version vs 14.9 seconds original on sample of 10**5 values. #generate sample n = 10**5 stockdata = pd.DataFrame(np.random.randint(0,100,size=(n,7)), columns = ['atr','high', 'low','close','finaluband','finallband','supert']) print (stockdata.shape) stockdata.head() SuperST will return all DataFrame on stockdata for i in range(3) it is exactly loop of different multiplied, your can rewrite it as for i in [7,8,9]: SuperST(stockdata,estim,i) You ST realisation is depends on results of previous call. It uses 'finaluband','finallband','supert' and returns them by itself. Initially they are zeros, but after first call they will have some value. So estim give you control on that situation, you can call SuperST with results of previous call or with initial zeros. Just rename initial DataFrame with zeros and pass it to SuperST. df_res = stockdata estim = pd.DataFrame(np.zeros((df_res.shape[0],5)), index = df_res.index, columns=['uband', 'lband', 'finaluband', 'finallband', 'supert']) for i in range(3): estim = SuperST(stockdata,estim) df_res = df_res.join(estim,rsuffix="{}".format(i)) print(df_res'open', 'high', 'low', 'close', 'atr', 'lband2', 'finaluband', 'finaluband1', 'finaluband2', 'finallband', 'finallband1', 'finallband2', 'supert', 'supert1', 'supert2') SuperST is the same ST def SuperST(stockdata,estim,multiplier = 7): #first we need next row value df_prev = estim'finaluband','finallband','supert'.join(stockdata'close').shift(1) # name colums as it was in paramas df_prev.columns = ['prevfinaluband', 'prevfinallband', 'prevsupertrend', 'prevclose'] # working matrix parmas with shifed values w/o NaN in ATR df = stockdata.dropna().join(df_prev).fillna(0) #calulate vectors upperbasicband = ((df.high+df.low)/2 + (multiplier * df.…
has comment: http://stackoverflow.com/comment/84858122
has comment: http://stackoverflow.com/comment/84859491
has comment: http://stackoverflow.com/comment/84819609
answers question: http://stackoverflow.com/q/48904375
has comment: http://stackoverflow.com/comment/84857587
has comment: http://stackoverflow.com/comment/84856954
score: 0
has comment: http://stackoverflow.com/comment/84854538
has comment: http://stackoverflow.com/comment/84850960
type: Answer

http://stackoverflow.com/comment/84736413
type: QuestionComment
has text: Yes. These are recurring bills with static dates. You would have to log into the online bank to check for unforeseen bills with unknown dates, which defeats the purpose of logging in as seldom as possible. (Unless all bills are notified by a separate channel such as email, but that's not part of the exercise.)
comment on: http://stackoverflow.com/q/48865959
score: 0
type: Comment

http://stackoverflow.com/comment/84712071
score: 0
type: AnswerComment
has text: If you want to truly tally the Product amounts, you probably would use a dictionary, not a list. `{'milk':2, 'dozen_eggs':3}`
type: Comment
comment on: http://stackoverflow.com/a/48854243

http://stackoverflow.com/comment/84675770
score: 0
comment on: http://stackoverflow.com/q/48835297
type: Comment
type: QuestionComment
has text: thanks very much for all the quick comments! appreciated it!

http://stackoverflow.com/q/48915440
score: 0
tagged with: pandas
has title: Pandas Multiprocessing Can't Get Attribute 'function' on '__main__'
tagged with: python
has comment: http://stackoverflow.com/comment/84837687
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
has body: I am attempting to use Multiprocessing to speed up pandas apply(). import multiprocessing import pandas as pd import numpy as np from multiprocessing import Pool num_partitions = 5 num_cores = multiprocessing.cpu_count() def parallelize_dataframe(df, func): a,b,c,d,e = np.array_split(df, num_partitions) pool = Pool(num_cores) df = pd.concat(pool.map(func, [a,b,c,d,e])) pool.close() pool.join() return df def square(x): return x**2 def test_func(data): print("Process working on: ",data) data["square"] = data["col"].apply(square) return data df = pd.DataFrame({'col': [0,1,2,3,4,5,6,7,8,9]}) if __name__ == '__main__': test = parallelize_dataframe(df, test_func) print(test) It is resulting in this error: Can't Get Attribute 'test_func' on &lt;module '__main__' (built-in)&gt;. I understand this is potentially the result of a circular import somehow, but I'm not sure what to alter in my code. Why is this error occurring?
tagged with: circular-dependency
has comment: http://stackoverflow.com/comment/84837452
has comment: http://stackoverflow.com/comment/85142945
tagged with: python-multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/84837616
has comment: http://stackoverflow.com/comment/84837360

http://stackoverflow.com/a/48949137
answers question: http://stackoverflow.com/q/48948898
type: AcceptedAnswer
downvote count: 0
has body: If you don't need to update an existing dictionary and just want a dictionary containing only nested dictionaries, you can do this instead: only_nested = {k: v for k, v in my_nested_dictionary.items() if isinstance(v, dict)} For example, given this code: my_nested_dictionary = {'key5': 'value5', 'key6': {'inner_key6_1': 'inner_value6_1'}, 'key7': 'value7', 'key8': {'inner_key8_1': 'inner_value8_1'}} only_nested = {k: v for k, v in my_nested_dictionary.items() if isinstance(v, dict)} print(only_nested) We get this output: {'key6': {'inner_key6_1': 'inner_value6_1'}, 'key8': {'inner_key8_1': 'inner_value8_1'}}
type: Answer
upvote count: 2
score: 2
accepted answer of: http://stackoverflow.com/q/48948898

http://stackoverflow.com/comment/84703496
score: 0
type: Comment
type: QuestionComment
has text: @CristiFati I updated the post with the changes I made(I changed the `get_time` to `get_UbiTimestamp`. The same error produced
comment on: http://stackoverflow.com/q/48849227

http://stackoverflow.com/comment/87448931
type: Comment
has text: You may want to format your code and describe your answer a bit
comment on: http://stackoverflow.com/a/50215616
type: AnswerComment
score: 0

http://stackoverflow.com/q/48879482
score: -5
has answer: http://stackoverflow.com/a/48879618
accepted answer: http://stackoverflow.com/a/48879618
upvote count: 1
possible better answer: http://stackoverflow.com/a/48879617
type: Question
has comment: http://stackoverflow.com/comment/84763021
has comment: http://stackoverflow.com/comment/84763318
answer count: 3
has comment: http://stackoverflow.com/comment/84762978
has body: I am having string as below: a ='sruthi' I want to convert this string into list like below: ['sruthi'] Can anyone help me with this?
has answer: http://stackoverflow.com/a/48879617
favorite count: 0
has comment: http://stackoverflow.com/comment/84762876
has title: How to convert a string into a list as a single element?
tagged with: python
has comment: http://stackoverflow.com/comment/84763024
has answer: http://stackoverflow.com/a/48879765
downvote count: 6
type: AnsweredQuestion

http://stackoverflow.com/a/72210947
has body: EASY PEASY LEMON SQUEEZY You can access the key without knowing the name of the key just with the index of a list. Make all the keys a list and then look for the index number you want of the keys. tell_me_why = { 'You': 56, 'Are': 23, 'My': 43, 'Fire': 78, 'The': 11, "One":10, 'Desire':8, 'Belive':6, 'When':134, 'I':1234, 'Say':77, "I Want":123, 'It':12345, "That":123211, 'Way':12345 } #make the keys a list tell_me_why_keys = list(tell_me_why.keys()) #print the list of the keys print(tell_me_why_keys) #print certain key print(tell_me_why_keys[5]) #print certain key value print(tell_me_why[tell_me_why_keys[5]])
answers question: http://stackoverflow.com/q/48894060
type: Answer
score: 2
downvote count: 2
upvote count: 4

http://stackoverflow.com/comment/84914955
score: 0
type: Comment
type: QuestionComment
has text: Since it's Windows, maybe it should be `"python3.exe mapper.py"` or whatever you use to run mapper.py from your command prompt.
comment on: http://stackoverflow.com/q/48916243

http://stackoverflow.com/q/48830033
has body: Am new to python development and trying to understand exception handling. I have 2 functions 1st to find 1 occurrence of duplicate value in a list and 2nd to call the function. But if try to pass the name of list that does not exist it should print message from except block , but its not working , please help def first_duplicate(a): x = 0 for i, j in enumerate(a): for k in a[i + 1:]: if j == k: x = 1 return j if x == 1: break def call_main (list_name): try: x = first_duplicate(list_name) if x is None: print("No duplicates") else: print(x, "is the first duplicate") except NameError: print("exception occurred Name ") except ValueError: print("exception occurred value") my command is like call_main(y) where I have not created the list : y , it should print the exception message in this case but its not , please help
type: Question
has comment: http://stackoverflow.com/comment/84679884
score: 5
accepted answer: http://stackoverflow.com/a/48831669
has comment: http://stackoverflow.com/comment/84665105
upvote count: 5
has comment: http://stackoverflow.com/comment/84667028
has title: python basics , why exception handling is not working?
answer count: 2
has comment: http://stackoverflow.com/comment/84666232
downvote count: 0
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84665305
has answer: http://stackoverflow.com/a/48831669
tagged with: python
has comment: http://stackoverflow.com/comment/84666592
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48830953
tagged with: pycharm
has comment: http://stackoverflow.com/comment/84666406
has answer: http://stackoverflow.com/a/48830953

http://stackoverflow.com/comment/84880294
comment on: http://stackoverflow.com/q/48936533
type: Comment
type: QuestionComment
has text: OK, the basic answer is that there's no simple shorthand for this. There are ways to avoid the variable, but they'll be more complicated and confusing, like @ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000's comment.
score: 1

http://stackoverflow.com/comment/84903103
type: QuestionComment
comment on: http://stackoverflow.com/q/48948014
has text: @ThierryLathuille oops, thanks a lot
score: 0
type: Comment

http://stackoverflow.com/comment/84740971
has text: looking at your data it seems that you have some restocking going on, its just not represented in its own column, is that correct?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48866978
score: 0

http://stackoverflow.com/comment/84708377
type: QuestionComment
comment on: http://stackoverflow.com/q/48852452
score: 0
has text: Use json for this.
type: Comment

vertica
tag name: vertica
type: Tag
tags question: http://stackoverflow.com/q/48954831

http://stackoverflow.com/comment/84792997
has text: try `from security import authenticate, identity`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48893545
score: 1

http://stackoverflow.com/comment/84838982
has text: @user3166881. I've added some stuff to the answer. See edits.
type: Comment
comment on: http://stackoverflow.com/a/48915925
score: 0
type: AnswerComment

http://stackoverflow.com/q/48842064
has comment: http://stackoverflow.com/comment/84688305
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/20714517
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84688158
tagged with: makemigrations
has comment: http://stackoverflow.com/comment/84688459
duplicate of: http://stackoverflow.com/q/20714517
answer count: 0
has comment: http://stackoverflow.com/comment/84688223
type: Question
has body: I'm new started to Django.where is my fault?
has comment: http://stackoverflow.com/comment/84688071
has title: Django makemigrations error?
score: 0
tagged with: django-manage.py

http://stackoverflow.com/a/48937534
downvote count: 0
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48937399
score: 2
has comment: http://stackoverflow.com/comment/84882281
has comment: http://stackoverflow.com/comment/84882323
has body: I will take it as you don't quite get the terminologies in python. Lambda is a key word in python. If you want to define a function, just say define a function. In fact, you don't use lambda to define a named function at all. Following code should do what you are asking for: def bb(x): for i in a: if i['prop'] == x: return i['cat'] else: return None It's in the style guide, PEP8, that you shouldn't define a named function using lambda: https://www.python.org/dev/peps/pep-0008/ Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier. Yes: def f(x): return 2*x No: f = lambda x: 2*x

http://stackoverflow.com/q/48838086
accepted answer: http://stackoverflow.com/a/48838423
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/48838423
tagged with: python
has comment: http://stackoverflow.com/comment/84680882
type: AnsweredQuestion
type: Question
tagged with: amazon-ec2
has title: "successfully opened CUDA library" not showing
score: 0
has body: I am following a tutorial at https://www.datacamp.com/community/tutorials/deep-learning-jupyter-aws. I would like to connect to a (CUDA compatible) GPU to do computations in a Jupyter notebook. Following the tutorial linked above, I have chosen (AWS EC2) deep learning AMI ubuntu, p2.xlarge, and the instance is running. Once I log into the cloud server using the IP address of the p2.xlarge instance, I import keras as they do in the tutorial. However, instead of "Using TensorFlow backend....successfully opened CUDA library" being returned in the IPython shell, I get: In [1]: import keras /home/ubuntu/anaconda3/lib/python3.6/site-packages/h5py/__init__.py:34: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`. from ._conv import register_converters as _register_converters Using TensorFlow backend. /home/ubuntu/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py:962: UserWarning: Duplicate key in file "/home/ubuntu/.config/matplotlib/matplotlibrc", line #2 (fname, cnt)) /home/ubuntu/anaconda3/lib/python3.6/site-packages/matplotlib/__init__.py:962: UserWarning: Duplicate key in file "/home/ubuntu/.config/matplotlib/matplotlibrc", line #3 (fname, cnt)) Could someone tell me what's going wrong? Also, if I get it working, will this instance work even for computations not involving keras (e.g., for reducing the dimension of data for a t-SNE)?
has comment: http://stackoverflow.com/comment/84680955
answer count: 1

http://stackoverflow.com/comment/84724827
type: Comment
comment on: http://stackoverflow.com/q/48860897
score: 0
has text: I feel that you should be storing an absolute figure for each person, e.g. the birthday, and then calculating based on this.
type: QuestionComment

http://stackoverflow.com/q/48804937
has body: Please tell me how to be? I want to receive the text and tags of all the children "alarmTime". However, I get an error. How to assign the attribute 'list'? Or tell me how to avoid the error. My code is: import xml.etree.ElementTree as ET tree = ET.parse('sample.xml') root = tree.getroot() for elem in root.iter(tag ='alarmTime'): data = elem.getchildren() print(data.text) Error is: AttributeError: 'list' object has no attribute 'text'
has comment: http://stackoverflow.com/comment/84612620
accepted answer: http://stackoverflow.com/a/48805769
type: AnsweredQuestion
has title: How i can use 'list' object on other attributes on xml.etree.ElementTree parse
tagged with: http://stackoverflow.com/tag/xml
type: Question
score: 0
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/48805769

http://stackoverflow.com/comment/84655261
comment on: http://stackoverflow.com/a/48825708
score: 0
type: Comment
has text: I had this line in my data `data/processed/10/blueprint-0.png,952.0,724.0,1010.0,734.0` for some reason it became `data/processed/10/blueprint-0.png,1010.0,724.0,952.0,734.0`
type: AnswerComment

http://stackoverflow.com/q/48855921
type: Question
tagged with: matplotlib
answer count: 1
has body: I am trying to animate n circles in 2D with matplotlib, but when run, my code only shows one circle, stationary, regardless of what I make n. Does anyone know how to fix it, and what is wrong with it? %matplotlib notebook import numpy as np from matplotlib import pyplot as plt from matplotlib import animation fig=plt.figure() ax = plt.axes(xlim=(0, 40), ylim=(0, 40)) number_of_particles = int(input("How many particles would you like?")) data = np.zeros((1000,number_of_particles)) dict_of_circles = {} for n in range(number_of_particles): data[:,n] = [20*(1+np.sin(float(x)/50*n+50)) for x in range(1000)] dict_of_circles["circle"+str(n+1)] = plt.Circle((data[0,n],1.0),0.5,fc='b') def init(): for n in range(number_of_particles): dict_of_circles["circle"+str(n+1)].center = (data[0,n],1) ax.add_patch(dict_of_circles["circle"+str(n+1)]) return dict_of_circles["circle"+str(n+1)] def animate(i): for n in range(number_of_particles): dict_of_circles["circle"+str(n+1)].center = (data[i,n],1) return dict_of_circles["circle"+str(n+1)] anim=animation.FuncAnimation(fig,animate,init_func=init,frames=1000,blit=True) plt.show()
has title: Can't get my program to animate circles in 2D in matplotlib
favorite count: 0
score: 0
has answer: http://stackoverflow.com/a/48856983
tagged with: python
type: UnansweredQuestion
tagged with: animation
upvote count: 1
downvote count: 1
tagged with: plot

http://stackoverflow.com/a/48869583
score: 0
answers question: http://stackoverflow.com/q/48869407
has body: Adding it as another answer, If you want to solve the timeout you can use the requests library import requests try: requests.get('http://url/to/file') catch Exception as e: print('Error code: ', e.code) if you haven't specified any time it won't timeout
type: Answer

http://stackoverflow.com/comment/84647432
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48821858
has text: Error is for second iteration, because lambda get NoneType but in must be real number.

http://stackoverflow.com/comment/84677506
has text: Yes that shall be no problem.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48833803

http://stackoverflow.com/comment/84730158
comment on: http://stackoverflow.com/a/48853597
score: 0
type: AnswerComment
has text: If your engines are playing weak, nearly-random moves then the game outcome won't be predictable. You can encode current score as a constant channel for CNN's. And yes, MCTS by itself might make a strong bot!
type: Comment

http://stackoverflow.com/q/48859456
answer count: 2
upvote count: 1
tagged with: data-structures
has answer: http://stackoverflow.com/a/56037347
favorite count: 0
has answer: http://stackoverflow.com/a/48859624
type: UnansweredQuestion
has body: I'm trying to create a 2d list with shape of [n,784] (the same shape as the MNIST image batches) using multiple [1,784] lists. mylist.append(element) doesn't give me what I'm looking for, where mylist is the 2d [n,784] list and element is the [1,784] lists. It would return a list with shape [n,1,784]. I've also tried mylist[index].append(element), and I got a [784] 1d list instead. Any idea how to solve my problem? Thanks a lot
score: -3
tagged with: python
has title: Concatenate 2d list in python
type: Question
tagged with: mnist
has comment: http://stackoverflow.com/comment/84722421
downvote count: 4

http://stackoverflow.com/a/48853128
score: 2
answers question: http://stackoverflow.com/q/48853094
downvote count: 0
has body: In django default reverse lookup name is modelname_set. So when you trying to get user.nazwa_set.all() this means that there is some model Nazwa related with User. Since in your code you don't have model named Nazwa this line raise the error. I suppose you mean Cudzoziemiec or Firma so to fix problem you need to replace user.nazwa_set.all() with user.firma_set.all() in form's __init__ method.
type: Answer
has comment: http://stackoverflow.com/comment/84709701
upvote count: 2

http://stackoverflow.com/q/48818425
score: 2
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48818586
favorite count: 0
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/48818586
tagged with: python
has title: python slice() function vs slice notation - How to handle empty values in slice()?
accepted answer: http://stackoverflow.com/a/48818528
answer count: 2
has body: The docs cover 3 usages of the slice() object: obj[:stop] = obj[slice(stop)] obj[start:stop] = obj[slice(start, stop)] obj[start:stop:step] = obj[slice(start, stop, step)] But how to do this when I don't know the length of the object in advance? Setting stop to a very high value, like 2E32-1? obj[start:] = obj[slice(start, 2E32-1)]? obj[:] = obj[slice(2E32-1)]?
has answer: http://stackoverflow.com/a/48818528

http://stackoverflow.com/comment/84746879
type: Comment
comment on: http://stackoverflow.com/q/48871211
has text: In Python, it does not matter where an inline modifier is used, it will be applied to the whole regex pattern. `(<header)((?s).*)( )` = `(?s)(<header)(.*)( )`. Besides, you may just use `re.S` or `re.DOTALL` flag passed to `re.compile`.
score: 1
type: QuestionComment

http://stackoverflow.com/comment/84909605
score: 0
has text: We were just discussing that in some detail in https://stackoverflow.com/q/48940544/901925
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48950424

http://stackoverflow.com/q/48836916
has comment: http://stackoverflow.com/comment/84678833
has title: Why does the AWS-EC2 CPU utilization drops gradually while the same python script is running?
answer count: 0
downvote count: 0
tagged with: amazon-ec2
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84678767
score: 1
has comment: http://stackoverflow.com/comment/84699903
favorite count: 0
has comment: http://stackoverflow.com/comment/84678657
type: Question
tagged with: cpu
upvote count: 1
has body: I have a python script running on Amazon Web Server. Initially the CPU utilization is high, ~60%. However it gradually drops to between ~0-1% rate and ranges around there while the same script runs. Why does this happen? My python script is as follows: `import numpy as np pd.set_option('max_colwidth',100) import scipy as sp from sklearn import preprocessing as pp import pickle from sklearn.linear_model import LogisticRegressionCV, LogisticRegression, SGDClassifier from sklearn.model_selection import cross_val_predict, GridSearchCV, train_test_split from sklearn import metrics from sklearn.preprocessing import StandardScaler import xgboost as xgb pred = pd.read_pickle('./couple_data_lasso_feature_selection_predictors') target = pd.read_pickle('./couple_data_without_resample_target') X_train, X_test, y_train, y_test = train_test_split(pred.values, target.values.ravel(), test_size=0.3, random_state=42) # Try TPOT from tpot import TPOTClassifier pipeline_optimizer = TPOTClassifier(scoring='f1', cv=5, random_state=42, verbosity=2, n_jobs=-1) pipeline_optimizer.fit(X_train, y_train) pipeline_optimizer.export('./tpot_exported_pipeline.py')`

http://stackoverflow.com/comment/84913909
type: QuestionComment
has text: No, if you notice, the value for key 'k3_3' is not the same. I would like the value to remain the same in the output, currently it takes the latest value and assigns it to all keys 'k3_*'
comment on: http://stackoverflow.com/q/48953557
score: 0
type: Comment

http://stackoverflow.com/a/62568222
has body: Here's my answer: def round_sum(a, b, c): return round10(a) + round10(b) + round10(c) def round10(num): if num % 10 &lt; 5: return num - (num % 10) return num + (10 - num % 10)
answers question: http://stackoverflow.com/q/48841342
score: 0
type: Answer

http://stackoverflow.com/comment/84633419
type: QuestionComment
type: Comment
score: 1
has text: Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, [describe the problem](https://meta.stackoverflow.com/questions/254393/what-exactly-is-a-recommendation-question) and what has been done so far to solve it.
comment on: http://stackoverflow.com/q/48814810

http://stackoverflow.com/comment/84702512
has text: Yes. Because of the exception `get()` is not suitable, `exists()` will do the trick
score: 0
comment on: http://stackoverflow.com/a/48845976
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48930008
downvote count: 2
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48930588
has title: How to perform univaraiate Analysis in Python using Plots
favorite count: 0
has comment: http://stackoverflow.com/comment/84867156
tagged with: seaborn
possible better answer: http://stackoverflow.com/a/48930607
tagged with: python
has answer: http://stackoverflow.com/a/48930607
type: AnsweredQuestion
has body: I have a dataset below and I wanted to perform univariate analysis on Income Category as the sample plot shown. Here the point is in the Number category 1 is treated as Male and 0 is treated as female. Is there any way possible to solve this. Income Population Number Category 54 77 1 A 23 88 1 A 44 87 0 B 55 88 0 B 66 89 1 B 73 90 0 A 12 89 1 C 34 9 0 C 54 77 1 A 23 88 1 A 44 87 0 B 55 88 0 B 66 89 1 B 73 90 0 A 12 89 1 C 34 9 0 C
has comment: http://stackoverflow.com/comment/84868578
type: Question
tagged with: numpy
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/48930588
has comment: http://stackoverflow.com/comment/84867284
upvote count: 2
score: 0

ebnf
type: Tag
tags question: http://stackoverflow.com/q/48824314
tag name: ebnf

http://stackoverflow.com/q/48911531
has answer: http://stackoverflow.com/a/58966153
tagged with: python
score: 8
possible better answer: http://stackoverflow.com/a/48911626
has answer: http://stackoverflow.com/a/48911626
type: Question
accepted answer: http://stackoverflow.com/a/48911908
has body: In pandas, I have a Dataframe indexed by timestamp. Looks like the following table: A B C D DATE 2018-01-17 157.52 163.74 157.28 159.84 2018-01-16 158.25 159.35 155.93 157.40 2018-01-15 157.15 159.59 156.79 158.86 2018-01-12 158.25 158.62 157.40 157.52 And I'm trying to select a row by index, and also select the next few rows. (For example, select two rows start at 2018-01-12). I found both .loc and .iloc are hard to do such task. Is there any other ways to do that?
type: AnsweredQuestion
has title: Pandas Dataframe: How to select a row by index, and then get the next few rows
tagged with: dataframe
tagged with: pandas
has answer: http://stackoverflow.com/a/79248323
downvote count: 0
favorite count: 0
upvote count: 8
has answer: http://stackoverflow.com/a/48911908
answer count: 5
has answer: http://stackoverflow.com/a/48911822

http://stackoverflow.com/q/48935673
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48938156
type: Question
has body: I'm trying to export my site as flat files with django bakery. I made a dummy site with a sample polls app and I get this error when I run python manage.py build File "python3.6/site-packages/bakery/management/commands/build.py", line 112, in handle self.build_views() File "python3.6/site-packages/bakery/management/commands/build.py", line 240, in build_views view = get_callable(view_str) File "python3.6/site-packages/django/urls/utils.py", line 25, in get_callable raise ImportError("Could not import '%s'. The path must be fully qualified." % lookup_view) ImportError: Could not import 'p'. The path must be fully qualified. I followed all their instructions correctly: polls/views.py: from bakery.views import BuildableTemplateView class HomePageView(BuildableTemplateView): template_name = "home.html" build_path = 'index.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', 'bakery' ] BUILD_DIR = '/Users/me/Downloads/build/' BAKERY_VIEWS = ( 'polls.views.HomePageView' ) mysite/urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('polls/', include('polls.urls')), ] polls/urls.py: from django.urls import path from . import views from polls.views import HomePageView urlpatterns = [ path('', HomePageView.as_view(), name='home'), ] Maybe it is something related to the urls? But I can't see what. The site works fine in the browser...
answer count: 1
has title: Django bakery ImportError: Could not import 'p'. The path must be fully qualified
score: 0
has answer: http://stackoverflow.com/a/48938156
tagged with: django

http://stackoverflow.com/comment/84636555
comment on: http://stackoverflow.com/q/48816332
score: 1
has text: Also, why `name_list=list(zip(capitals.keys()))`??? You almost certainly just want `name_list = list(capitals)`, why are you using `zip`???
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84798825
comment on: http://stackoverflow.com/q/48852577
has text: Maybe it is unrelated to the problem but you may want to use apache-beam 2.2. Otherwise, TF version on the DF service would be TF 1.0 (not 1.4.1) when any version older than apache-beam 2.0 is used.
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48878059
has comment: http://stackoverflow.com/comment/84760133
tagged with: python
has body: I am working on a project, using python, that will take an image[s] from an online webcam such as this and then be able to apply some edge detection and motion detection. I have the edge and motion detection running if I import an image already saved on the pi. I can import an image from the terminal with: wget -nd /pi/Documents/ -A jpg https://www.skikelly.com/sf/liveview/?rand=1234556789 I don't know how to put that in a script though.
answer count: 0
has title: Download picture from internet using python
linked to: http://stackoverflow.com/q/13137817
type: Question
tagged with: image
has comment: http://stackoverflow.com/comment/84760135
score: 0
has comment: http://stackoverflow.com/comment/84760127
has comment: http://stackoverflow.com/comment/84760136
linked to: http://stackoverflow.com/q/3042757
type: UnansweredQuestion

http://stackoverflow.com/a/78432641
type: Answer
upvote count: 2
score: 2
has body: Here's the asyncio example from Fluent Python (copied here as an allowed use of the book content) which covers this exact program. It uses async functions (aka coroutines) and the asyncio built-in Python library to display a spinner until a separate coroutine waits 3 seconds and returns a value (the integer 42). You can read more about asyncio from Chapter 19 in the book. # spinner_await.py # credits: Example by Luciano Ramalho inspired by # Michele Simionato's multiprocessing example in the python-list: # https://mail.python.org/pipermail/python-list/2009-February/538048.html # BEGIN SPINNER_AWAIT import asyncio import itertools import sys async def spin(msg): # &lt;1&gt; write, flush = sys.stdout.write, sys.stdout.flush for char in itertools.cycle('|/-\\'): status = char + ' ' + msg write(status) flush() write('\x08' * len(status)) try: await asyncio.sleep(.1) # &lt;3&gt; except asyncio.CancelledError: # &lt;4&gt; break write(' ' * len(status) + '\x08' * len(status)) async def slow_function(): # &lt;5&gt; # pretend waiting a long time for I/O await asyncio.sleep(3) # &lt;6&gt; return 42 async def supervisor(): # &lt;7&gt; spinner = asyncio.ensure_future(spin('thinking!')) # &lt;8&gt; print('spinner object:', spinner) # &lt;9&gt; result = await slow_function() # &lt;10&gt; spinner.cancel() # &lt;11&gt; return result def main(): loop = asyncio.get_event_loop() # &lt;12&gt; result = loop.run_until_complete(supervisor()) # &lt;13&gt; loop.close() print('Answer:', result) if __name__ == '__main__': main() # END SPINNER_AWAIT
answers question: http://stackoverflow.com/q/48854567
downvote count: 0

kivy-language
type: Tag
tags question: http://stackoverflow.com/q/48870710
tags question: http://stackoverflow.com/q/48812242
tags question: http://stackoverflow.com/q/48928276
tags question: http://stackoverflow.com/q/48950989
tags question: http://stackoverflow.com/q/48812442
tags question: http://stackoverflow.com/q/48810449
tags question: http://stackoverflow.com/q/48910863
tags question: http://stackoverflow.com/q/48871327
tag name: kivy-language

http://stackoverflow.com/a/49290981
upvote count: 6
has comment: http://stackoverflow.com/comment/97507992
accepted answer of: http://stackoverflow.com/q/48831838
has body: Question 0 A "module" in the Python context is simply a file that contains definitions and statements. So "related modules under a package" really just means "split your code into separate files based on what the code is doing". Describing it as "an app made of other apps" is to start confusing Django's concept of an app with Python's concept of a module (which, as stated above is just a file that houses some code). Question 1 What should I do when apps share models? You should still try and stick to the "apps do one thing and do it well" maxim. In this case separate profile and registration apps seems like a good idea - because they have quite different functions. A registration app is going to contain the logic for allowing users to register on your site. A profile app is all about what information you will store about a user. There is nothing wrong with these two apps having a relationship to each other - see below. Question 2 Let's say that my main app (or some other app that is used by the main app) utilizes some aspect of the user model (e.g. recently active members if it was a chat site). Clearly my main app gets this information from the user model. Does my main app now get bundled under the user-app? No. It should still be a separate app, with links to the other app. The user model is actually a good example. Django allows you to specify a custom user model that lets you store whatever additional data you want about a user. Now, there are loads of third party apps out there that do things like registration, authentication, etc for users. They are designed to work with any user model, not just Django's default one. The way they do that is to use get_user_model() wherever they need to reference the User model, instead of directly importing django.contrib.auth.models.User. This means that you can use those third party apps with whatever user model you have defined for your own project. Django's get_user_model() utility is there to serve a very common use case.…
has comment: http://stackoverflow.com/comment/85613968
downvote count: 1
answers question: http://stackoverflow.com/q/48831838
score: 5
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/85626775

http://stackoverflow.com/q/48953331
answer count: 2
tagged with: directory
tagged with: string
has comment: http://stackoverflow.com/comment/84918813
favorite count: 0
has comment: http://stackoverflow.com/comment/84918710
has answer: http://stackoverflow.com/a/48953392
accepted answer: http://stackoverflow.com/a/48953392
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84918625
tagged with: loops
has comment: http://stackoverflow.com/comment/84919298
type: Question
has title: Iterating Images in Directory By Name
has body: Hopefully this'll be relatively easy to answer as I'm still new to Python. I need to for-iterate through images of name [x]img[y] where x and y are identifiers that determine how the image is processed. x determines process and is valued 1 or 2 and y determines one of the values to be used in processing. So, in pseudo-code: directory = 'my/path/to/images' for image in directory: if x = 1: do process a with y elif x = 2: do process b with y else: print "ERROR" I'm not familiar enough yet with the code and extracting values from strings to piece together the various different examples I've seen around. I get the feeling I should be able to turn the string into an array and read the 1st and 5th values as integers, right? Your help is very much appreciated and if you'd like to get a better understanding of what I'm trying to accomplish with this project I've made a GitHub repository here. Many thanks :) EDIT Thanks to Ely for getting me this far however that introduced another error. Here's the test code I'm using to open the directory, which contains files 1img2.png, 1img4.png and 2img1.png. import os import re DIRECTORY = '/home/pi/Desktop/ScannerDev/TestPhotos/' for img_filename in os.listdir(DIRECTORY): x, y = os.path.splitext(img_filename)[0].split('img') print 'Camera is ', x print 'Image is ', y """ for img_filename in os.listdir(DIRECTORY): a = re.search('^(.*)img(.*)\.png$', img_filename) if a is None: break else: x = a.group(1) y = a.group(2) print 'Camera is ', x print 'Image is ', y """ Which returns: Camera is 2 Image is 1 Traceback (most recent call last): File "iteratorTEST.py", line 10, in &lt;module&gt; x, y = os.path.splitext(img_filename)[0].split('img') ValueError: need more than 1 value to unpack
possible better answer: http://stackoverflow.com/a/48956225
has answer: http://stackoverflow.com/a/48956225
has comment: http://stackoverflow.com/comment/84919022
upvote count: 2

http://stackoverflow.com/a/48824547
has comment: http://stackoverflow.com/comment/84653014
has comment: http://stackoverflow.com/comment/84652566
upvote count: 1
answers question: http://stackoverflow.com/q/48824396
has body: Use this instead:- magicians=['feka','kuka','szuka'] st = "the Great" a = [(x+" "+y) for x,y in zip(magicians,[st]*len(magicians))] print(a)
score: 0
type: Answer
downvote count: 1

http://stackoverflow.com/a/48910838
accepted answer of: http://stackoverflow.com/q/48910709
has comment: http://stackoverflow.com/comment/84851510
has comment: http://stackoverflow.com/comment/84827991
has comment: http://stackoverflow.com/comment/84828111
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84828042
has comment: http://stackoverflow.com/comment/84827990
has comment: http://stackoverflow.com/comment/84828815
score: 4
has comment: http://stackoverflow.com/comment/84828082
type: Answer
has comment: http://stackoverflow.com/comment/84850093
has comment: http://stackoverflow.com/comment/84828134
answers question: http://stackoverflow.com/q/48910709
has comment: http://stackoverflow.com/comment/84827920
has comment: http://stackoverflow.com/comment/84827971
has body: I find the solution below the most elegant one: dict_comp = dict(zip(*map(lambda x: x.split('\t'), my_list))) print(dict_comp) # -&gt; {'header1': 'val1', 'header2': 'val2', 'header3': 'val3', 'header4': 'val4'} Alternatively, the lambda can be substituted by a generator expression: dict_comp = dict(zip(*(x.split('\t') for x in my_list))) and if the strings do not contain any spaces, it can be shortened even further to: dict_comp = dict(zip(*map(str.split, my_list))) # kudos @Chris_Rands
has comment: http://stackoverflow.com/comment/84828016
has comment: http://stackoverflow.com/comment/84828095

http://stackoverflow.com/comment/84712606
has text: At the website http://www.gisinternals.com/release.php I clicked release-1600-x64-gdal-2-2-3-mapserver-7-0-7 and then GDAL-2.2.3.win-amd64-py3.4.msi was the one I installed. I then followed the rest of those instructions exactly as it said 64-bit should do. I'm running python via pressing F5 while the code is open as a document in python shell (version shown in the original post). Should I be using cmd instead? Would that make a difference with the DLL Load Failed error?
score: 0
comment on: http://stackoverflow.com/q/48854161
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48885277
score: 1
upvote count: 1
downvote count: 0
has body: You had a syntax error in your list comprehension def tellQuarter(month): Q1 = ('JAN','FEB','MAR') Q2 = ('APR','MAY','JUN') Q3 = ('JUL','AUG','SEP') Q4 = ('OCT','NOV','DEC') if any(mon in month for mon in Q1): return ("Q1") if any(mon in month for mon in Q2): return ("Q2") print tellQuarter("2018_JAN_BGD") Output: Q1
type: Answer
answers question: http://stackoverflow.com/q/48885192

http://stackoverflow.com/q/48901371
has title: Tools/methods to extract math expressions from plain unstructured text
has comment: http://stackoverflow.com/comment/84845687
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: artificial-intelligence
tagged with: nlp
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/84821480
upvote count: 1
tagged with: named-entity-recognition
has body: I need to identify math expressions embedded in text. For example "Write down the value of A + B." Here 'A + B' is the part I need to extract and it is not expressed using any structured text like Latex, but in plain unstructured text. Are there any tools/methods to extract such expressions in text, like a POS tagger or a Name Entity recognition tool for math expressions? First I tried to do this using regular expressions, but that is not successful for complex expressions. I found many research papers to extract math expressions from scanned documents ( from an image) or from structured text, but I found nothing for plain text.
type: Question

http://stackoverflow.com/comment/84649887
has text: @LahiruKarunaratne any solution for that
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48820940
score: 0

http://stackoverflow.com/q/48914528
has answer: http://stackoverflow.com/a/68027284
has answer: http://stackoverflow.com/a/69287141
tagged with: python
has title: Is there a way to export Allure Report to a single html file? To share with the team
tagged with: allure
has body: Right now, I am generating the Allure Report through the terminal by running the command: allure serve {folder that contains the json files}, but with this way the HTML report will only be available to my local because The json files that generated the report are in my computer I ran the command through the terminal (if i kill the terminal, the report is gone) I have tried: Saving the Allure Report as Webpage, Complete, but the results did not reflect to the page, all i was seeing was blank fields. So, what im trying to to do is after I execute the command to generate the report, I want to have an html file of the report that i can store, save to my computer or send through email, so i do not have to execute the command to see the previous reports. (as much as possible into 1 html file)
has answer: http://stackoverflow.com/a/70380178
accepted answer: http://stackoverflow.com/a/48926889
linked to: http://stackoverflow.com/q/41960081
has comment: http://stackoverflow.com/comment/113212628
type: AnsweredQuestion
type: Question
upvote count: 15
tagged with: automation
tagged with: frameworks
downvote count: 0
answer count: 7
possible better answer: http://stackoverflow.com/a/77282528
score: 15
has answer: http://stackoverflow.com/a/77282528
favorite count: 0
has answer: http://stackoverflow.com/a/48926889
has answer: http://stackoverflow.com/a/63722118
has answer: http://stackoverflow.com/a/62147635

http://stackoverflow.com/q/48884204
has answer: http://stackoverflow.com/a/49772255
downvote count: 0
answer count: 1
favorite count: 0
has body: I am trying to install various python packages on Windows 10. I have anaconda installed, and have not been able to install packages not included in conda until now, because of lack of admin rights. I have python version 3.6.3 installed. I have OpenSSl version 1.0.2.k 26 Jan 2017. I am working from a python console inside JetBrains Pycharm. import pip pip.main(['install','Plotly']) The result: Collecting Plotly Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",),)': /simple/plotly/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",),)': /simple/plotly/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",),)': /simple/plotly/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",),)': /simple/plotly/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError("bad handshake: Error([('SSL routines', 'ssl3_get_server_certificate', 'certificate verify failed')],)",),)': /simple/plotly/ Could not find a version that satisfies the requirement Plotly (from versions: ) No matching distribution found for Plotly I get the exact same errors if I try to install a package that doesnt exist (fsldkjfs). If I try to install a package already installed, I get Requirement already satisfied: numpy in c:\program files\anaconda…
type: UnansweredQuestion
tagged with: python
score: 1
tagged with: pip
upvote count: 1
has title: Python pip install SSLError bad handshake
type: Question

http://stackoverflow.com/q/48887676
linked to: http://stackoverflow.com/q/27389227
has comment: http://stackoverflow.com/comment/84780410
has comment: http://stackoverflow.com/comment/85012730
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84786725
has title: Python 2.7 loads DLL while python 3.5 crashes
has comment: http://stackoverflow.com/comment/84800504
type: UnansweredQuestion
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/84789744
tagged with: dllimport
score: 3
has comment: http://stackoverflow.com/comment/84780403
answer count: 0
upvote count: 3
has comment: http://stackoverflow.com/comment/84804313
has comment: http://stackoverflow.com/comment/84792707
type: Question
tagged with: ctypes
has body: I'm running into problems with a proprietary dll, which unfortunetly prevents me from posting the code here. Luckily the problem reduces down to two lines anyway: import ctypes windll.LoadLibrary("K:\\Patch\\To\\DLL.dll") This code works with Python 2.7 but not with Python 3.5. In 3.5 in throws: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "K:\Miniconda\envs\...\lib\ctypes\__init__.py", line 429, in LoadLibrary return self._dlltype(name) File "K:\Miniconda\envs\...\lib\ctypes\__init__.py", line 351, in __init__ self._handle = _dlopen(self._name, mode) OSError: [WinError 1114] Eine DLL-Initialisierungsroutine ist fehlgeschlagen (Sorry about it being in German. Not my decision) Error in English should be: OSError: [WinError 1114] A dynamic link library (DLL) initialization routine failed I've tested my Python 3.5 interpreter with "C:\Windows\System32\aadtb.dll" and it worked so it can load other DLL's. The DLL I need to load is provided by a third party and closed source. The company we got the DLL from doesn't feel responsible and won't help. So what my question boils down to: What are the differences between Python 2.7 and Python 3.5? I know they changed the way errors are reported but I couldn't find anything else. Edit: The DLL and both python versions use 64bit addressing.
has comment: http://stackoverflow.com/comment/84792478
linked to: http://stackoverflow.com/q/18583061

http://stackoverflow.com/comment/84802486
comment on: http://stackoverflow.com/q/48884494
has text: I have added maven dependency . I'm new to python and jython so I don't how to work with them. All I want is to resolve the issue and run a python function from java and get a value returned by the function.
score: 0
type: Comment
type: QuestionComment

audacity
type: Tag
tags question: http://stackoverflow.com/q/48923943
tag name: audacity

http://stackoverflow.com/comment/84643242
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48819698
has text: Have you tried with `http.client` instead of `httplib2`?
type: Comment

http://stackoverflow.com/comment/85012261
has text: `print(account.archive_msg_folder_root.tree())` returns "Øverst i informasjonslageret", or "Top of Information Store" in English. I am suspecting the archive is not contained here?
type: Comment
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48944574

http://stackoverflow.com/q/48824283
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 1
tagged with: python
tagged with: vim
type: AnsweredQuestion
tagged with: call
score: 1
has title: python call vim open multiple files
type: Question
has body: I'm trying to call vim from a python script to open multiple files. files = [] for i in sys.argv[1:]: files.append(i) string = " ".join(str(x) for x in files) call(["vim", string]) when I call ./open.py 11 42 39 it only open one file called "11 42 39". How to open them as separates files ? Thank you.
has answer: http://stackoverflow.com/a/48824318
accepted answer: http://stackoverflow.com/a/48824318

http://stackoverflow.com/comment/84773789
score: 0
comment on: http://stackoverflow.com/q/48883694
type: Comment
has text: One field is a char, the other one is a selection, the possible selection values are not calculated when opening the view, but when restarting odoo and updating the module, it is not the same case
type: QuestionComment

http://stackoverflow.com/q/48814830
answer count: 3
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48815002
score: 22
upvote count: 22
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48815002
favorite count: 0
has body: As a simplified example, I've written an UpdateView for a Book model, as well as a ListView to redirect to upon success: from django.urls import reverse from django.views.generic import ListView from django.views.generic.edit import UpdateView from .models import Book class BookUpdate(UpdateView): model = Book fields = ['title', 'author'] class BookList(ListView): model = Book The Book model is defined as class Book(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100, blank=True) def get_absolute_url(self): return reverse('books-list') where urls.py is from django.urls import path from books.views import BookUpdate, BookList urlpatterns = [ path('books/', BookList.as_view(), name='books-list'), path('book/&lt;int:pk&gt;/', BookUpdate.as_view(), name='book-update') ] In books/tests.py I've tried to write the following test: class BookUpdateTest(TestCase): def test_update_book(self): book = Book.objects.create(title='The Catcher in the Rye') response = self.client.post( reverse('book-update', kwargs={'pk': book.id}), {'author': 'J.D. Salinger'}) self.assertEqual(response.status_code, 200) book.refresh_from_db() self.assertEqual(book.author, 'J.D. Salinger') However, this test fails because the book's author appears not to be updated after the POST request, even after refreshing from the database: FAIL: test_update_book (books.tests.BookUpdateTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/Scratch/book_project/books/tests.py", line 46, in test_update_book self.assertEqual(book.author, 'J.D. Salinger') AssertionError: '' != 'J.D. Salinger' + J.D. Salinger On the other hand, if I run the development server and fill out the fields manually, everything seems to work as expected. How can I write a unit test for the UpdateView which captures the user updating the fields, submitting the form, and making changes to the corresponding objec…
type: Question
possible better answer: http://stackoverflow.com/a/67548185
has title: How to test Django's UpdateView?
has answer: http://stackoverflow.com/a/67548185
has answer: http://stackoverflow.com/a/69623211

http://stackoverflow.com/q/48900470
tagged with: python
has comment: http://stackoverflow.com/comment/84806533
has comment: http://stackoverflow.com/comment/84806487
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84806579
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84806267
has answer: http://stackoverflow.com/a/48900568
has body: Sorry if my question is duplicate. Because I can't find related to my question (or I miss the question, sorry about that) FYI, this is my file : BLP33 8172192873.xlsx BLP31 3612739412.xlsx BLP3 3612738402.xlsx BLPR73 9173913823.xlsx BLPR12 8172367132.xlsx BR8 1827328367.xlsx BR23 5928721983.xlsx I'm trying to loop excel files with glob using var loop var = ["BR*.xlsx", "BLPR*.xlsx", "BLP*.xlsx"] for fly in var: for f in glob.glob(fly): print f print "--" print "Clearly done." Please have a look at BLP* and BLPR*, that's when the problem begin. When I loop BLP*, script will show BLPR files too. I can't figure how to separate BLP AND BLPR loop. Anybody know how? This is the result, sorry forgot to attach BLP33 8172192873.xlsx -- BLP31 3612739412.xlsx -- BLP3 3612738402.xlsx -- BLPR73 9173913823.xlsx -- BLPR12 8172367132.xlsx -- BLPR73 9173913823.xlsx -- BLPR12 8172367132.xlsx -- BR8 1827328367.xlsx -- BR23 5928721983.xlsx -- Clearly done. Thanks in advance!
score: -1
upvote count: 0
answer count: 1
tagged with: arrays
favorite count: 0
has title: Python Prevent Same Loop
tagged with: glob

http://stackoverflow.com/a/48904045
has body: Ideally, you should use a virtualenv. Once you have installed Django in a virtualenv, the django-admin command will work once you have activated the virtualenv. If you still want to use the Django that you installed using pip3, you should use the python3 command. python3 &gt;&gt;&gt; import django &gt;&gt;&gt; django.VERSION You can also use python -m django instead of django-admin or django-admin.py, to make sure that you are using the correct version of Python, for example: python3 -m django --version
score: 0
answers question: http://stackoverflow.com/q/48902662
type: Answer

http://stackoverflow.com/q/48938522
has comment: http://stackoverflow.com/comment/84884059
tagged with: function
has comment: http://stackoverflow.com/comment/84884063
score: 0
has comment: http://stackoverflow.com/comment/84884227
answer count: 2
has body: Using a save_ouput function, how can I save the output of every function? def a(): print("abc,") def b(): print("help,") def c(): print("please") def save_output(): # save output of all functions def main(): a() b() c() save_output() main() ^So it'd save abc,help,pleaseas a text file when main is called
has comment: http://stackoverflow.com/comment/84884095
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/616645
has answer: http://stackoverflow.com/a/48938674
has comment: http://stackoverflow.com/comment/84884129
has comment: http://stackoverflow.com/comment/84884107
tagged with: save
has answer: http://stackoverflow.com/a/48938582
has title: Print output from every function
tagged with: output
upvote count: 1
downvote count: 1
type: Question

http://stackoverflow.com/comment/84685514
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48840689
has text: Use Beautifulsoup.

http://stackoverflow.com/comment/84751720
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48873515
has text: @juanpa.arrivillaga I guess I don't understand why you would want to use a dictionary in this case? Is there an advantage to having them in a dictionary vs not? It seems to me I can save typing and confusion by not having to say `df_dict['df1']` or `df_dict['df2']`. My plan later is to merge each dataframe in the dictionary onto another set, seems like it would be less messy if they weren't in the dictionary.

http://stackoverflow.com/q/48946320
tagged with: python
has title: Scrapy get all links from any website
tagged with: web-crawler
tagged with: scrapy
has body: I have the following code for a web crawler in Python 3: import requests from bs4 import BeautifulSoup import re def get_links(link): return_links = [] r = requests.get(link) soup = BeautifulSoup(r.content, "lxml") if r.status_code != 200: print("Error. Something is wrong here") else: for link in soup.findAll('a', attrs={'href': re.compile("^http")}): return_links.append(link.get('href'))) def recursive_search(links) for i in links: links.append(get_links(i)) recursive_search(links) recursive_search(get_links("https://www.brandonskerritt.github.io")) The code basically gets all the links off of my GitHub pages website, and then it gets all the links off of those links, and so on until the end of time or an error occurs. I want to recreate this code in Scrapy so it can obey robots.txt and be a better web crawler overall. I've researched online and I can only find tutorials / guides / stackoverflow / quora / blog posts about how to scrape a specific domain (allowed_domains=["google.com"], for example). I do not want to do this. I want to create code that will scrape all websites recursively. This isn't much of a problem but all the blog posts etc only show how to get the links from a specific website (for example, it might be that he links are in list tags). The code I have above works for all anchor tags, regardless of what website it's being run on. I do not want to use this in the wild, I need it for demonstration purposes so I'm not going to suddenly annoy everyone with excessive web crawling. Any help will be appreciated!
upvote count: 15
has answer: http://stackoverflow.com/a/48947055
downvote count: 0
type: UnansweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48964940
favorite count: 0
tagged with: python-3.x
score: 15
answer count: 2

http://stackoverflow.com/a/48889774
downvote count: 0
score: 1
upvote count: 1
has body: you can do easily with pandas, import pandas as pd df=pd.DataFrame(sorted(dic.items())) df.to_csv("your_file.csv",index=False)
type: Answer
answers question: http://stackoverflow.com/q/48889368

http://stackoverflow.com/q/48958439
linked to: http://stackoverflow.com/q/29590365
has comment: http://stackoverflow.com/comment/85031262
has comment: http://stackoverflow.com/comment/85043315
type: Question
tagged with: python
has title: Unable to view data on basemap pcolormesh map
has comment: http://stackoverflow.com/comment/85052024
tagged with: matplotlib-basemap
has answer: http://stackoverflow.com/a/49057846
score: 0
answer count: 1
tagged with: netcdf
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85629614
has body: I'm new to python and still learning, so forgive me if I missed something obvious! I'm trying to plot a pcolormesh map of temperature data ('tg') using Basemap in matplotlib. tg is a 3D array of time, latitudes and longitudes. For some reason, my output only shows the continent and states, but the temperature data is not overlain and is not visible. What am I missing? Here is a sample of my code: import matplotlib.pyplot as plt from mpl_toolkits.basemap import Basemap, cm lon_0 = (lon_var[:].mean()) lat_0 = (lat_var[:].mean()) latcorners = lat_var[:] loncorners = lon_var[:] m = Basemap(projection = 'lcc',\ lon_0 = -100, lat_0 = 39, lat_ts = lat_0,\ llcrnrlat=latcorners[0,0],urcrnrlat=latcorners[169,56],\ llcrnrlon=loncorners[0,0],urcrnrlon= loncorners[169,56],\ resolution='l') m.drawcoastlines() m.drawstates() m.drawcountries() parallels = np.arange(lat_var[0,0], lat_var[169,56]) m.drawparallels(parallels) meridians = np.arange(lon_var[0,0], lon_var[169,56]) m.drawmeridians(meridians) clevs = np.linspace(30,50, 2) cs = m.pcolormesh(lon_var, lat_var, tg[0,:,:]) plt.show() Here is the output map that is created Thanks!

http://stackoverflow.com/a/48834353
has body: You are overcomplicating stuff. All you need to do is this: g = ('1','2','3') print('\n'.join(g)) Or with a function and an example: def printPile(g): print('\n'.join(g)) g = ('1','2','3') printPile(g) Returns 1 2 3 And how would I correct your example? def printPile(g): for i in range(len(g)): print(g[i]) or: def printPile(g): for i in g: print(i)
score: 0
answers question: http://stackoverflow.com/q/48834267
type: Answer

http://stackoverflow.com/comment/84835178
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48911885
has text: When I go to reset password, it says that VM Agent is unavailable. How to install this VM agent via CLI? Or ho do I provide my credentials like username and password through a command from CLI? please sugget. @VikranthS

http://stackoverflow.com/a/48911016
type: Answer
has comment: http://stackoverflow.com/comment/84881039
has comment: http://stackoverflow.com/comment/84828314
has comment: http://stackoverflow.com/comment/84881904
has comment: http://stackoverflow.com/comment/84879927
has comment: http://stackoverflow.com/comment/84920419
has comment: http://stackoverflow.com/comment/84832510
has comment: http://stackoverflow.com/comment/84879879
has comment: http://stackoverflow.com/comment/84889565
has comment: http://stackoverflow.com/comment/84893716
score: 0
has comment: http://stackoverflow.com/comment/84882427
answers question: http://stackoverflow.com/q/48910844
has comment: http://stackoverflow.com/comment/84834760
has body: Use a dict ([Python]: Mapping Types — dict): combo_dict = { "DAP": 46, "MAP": 52, "SPS": 21, "SPT": 46, } and its usage (as current values are ints, convert them to floats): float(combo_dict[combo.get()]) or better (in case the string returned by the combo is not present in combo_dict: [Python]: get(key[, default])): float(combo_dict.get(combo.get(), -1))

http://stackoverflow.com/q/48932642
has comment: http://stackoverflow.com/comment/84894429
upvote count: 4
has comment: http://stackoverflow.com/comment/84902644
tagged with: reactjs
has title: Logging in a React app with Selenium using ReduxPersist
downvote count: 0
score: 4
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84884206
tagged with: react-redux
answer count: 0
type: UnansweredQuestion
tagged with: selenium
tagged with: redux-persist
type: Question
has body: For an investigation I'm doing, I'm trying to programmatically log in to a React web app, and I can't use the log in form each time, I need to pretend that I'm just coming back to the site. The app does not use session cookies to identify logged in users, but a mix of values in IndexedDB and LocalStorage. My code looks like this (happy to provide you with the name of the website in a private message) but fails to successfully log in. When the website is visited for the second time, the selenium browser is not logged in. Any idea what could be wrong? cookies = { # All cookies set by the domain. } local_storage = { # All key value pairs found in the local storage # of a browser connected to the website. } driver = webdriver.Firefox() driver.get(website_url) time.sleep(5) for key, value in local_storage.items(): driver.execute_script("window.localStorage.setItem('%s', '%s');" % (key, value)) for key, value in cookies.items(): driver.add_cookie({"name": key, "value": value, "domain":domain_url, "path": "/"}) driver.execute_script(""" var db; var request = window.indexedDB.open("keyval-store", 1); request.onsuccess = function(event) { db = request.result; console.log("success: "+ db); }; request.onupgradeneeded = function(event) { var db = event.target.result; var objectStore = db.createObjectStore("keyval"); objectStore.add(value_found_in_the_IndexedDB,"reduxPersist:user"); objectStore.add(another_value_found_in_the_IndexedDB, "reduxPersist:appSettings"); }; """) time.sleep(5) driver.get(website_url) time.sleep(1)

http://stackoverflow.com/q/48946375
answer count: 0
score: 1
has body: I am new to sqlalchemy. I am trying to generate query using sqlalchemy core from sqlalchemy.dialects import oracle, mssql from sqlalchemy.sql import column, table, select, literal_column def genrate_query(db_type): cols = [literal_column('foo'), literal_column('bar')] qry = select([cols]).select_from(table('some_table')) if db_type == 'mssql': return qry.compile(dialect=mssql.dialect(), compile_kwargs={"literal_binds": True}) return qry.compile(dialect=oracle.dialect(), compile_kwargs={"literal_binds": True}) This is giving me: SELECT foo, bar FROM some_table I am trying to achieve SELECT foo, bar FROM some_table@dblink for oracle. Trying to generate dialect specific queries that is @dblink for oracle, host.dbname.schema.some_table for mssql, any idea how to achieve it?
upvote count: 1
tagged with: sqlalchemy
type: Question
has title: Add database link in query generated by sqlalchemy core
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48907135
downvote count: 0
upvote count: 2
has body: Try this from a command prompt: pip install pygame This should download and install pygame to a location that Python can find and use it. Then you can import pygame in Jupyter notebook. I tested this on Windows 8.
answers question: http://stackoverflow.com/q/48876935
type: Answer
has comment: http://stackoverflow.com/comment/84887743
score: 2
has comment: http://stackoverflow.com/comment/84901887

http://stackoverflow.com/q/48867604
downvote count: 1
has comment: http://stackoverflow.com/comment/84739312
has body: Could anybody help me, please? Django documantation says that 'render_to_response' is not used starting from the 2nd version. I can't display list on my template. For the model: class Partners(models.Model): title = models.CharField(max_length=256) description = models.TextField(blank=True) image = models.ImageField(upload_to="pictures", blank=True) link = models.URLField(max_length=128, blank=True) def __str__(self): return self.title i tried both of 2 methods: def partners(request): partners_list = Partners.objects.all() return render(request, 'partners.html', {'partners_list': partners_list}) and def partners(request): partners_list = Partners.objects.all() return TemplateResponse(request, 'partners.html', {'partners_list': partners_list}) Template is: {% for partners in partners_list %} {{partners.title}} {{partners.description}} Cras justo odio Card link {% endfor %} Urls are: urlpatterns = [ path('admin/', admin.site.urls), path(r'', headpage, name='headpage'), path(r'about/', about, name='about'), path(r'partners/$', partners, name='partners'), ] What i do wrong? List of partners isn't displayed..Thank's a lot for your help!
tagged with: django-views
score: -1
has comment: http://stackoverflow.com/comment/84763259
has title: Rendering in Django 2.0.2
type: Question
has comment: http://stackoverflow.com/comment/84748328
upvote count: 0
has comment: http://stackoverflow.com/comment/84740243
has comment: http://stackoverflow.com/comment/84738538
has comment: http://stackoverflow.com/comment/84744359
has answer: http://stackoverflow.com/a/48867651
answer count: 1
has comment: http://stackoverflow.com/comment/84738868
has comment: http://stackoverflow.com/comment/84741500
favorite count: 0
tagged with: django-templates
has comment: http://stackoverflow.com/comment/84745939
has comment: http://stackoverflow.com/comment/84738476
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/comment/84650594
type: Comment
score: 2
comment on: http://stackoverflow.com/q/48823387
has text: What do you mean "stored" ? "stored" where ?
type: QuestionComment

http://stackoverflow.com/comment/84844111
type: Comment
comment on: http://stackoverflow.com/a/48918892
type: AnswerComment
score: 0
has text: And don't the comments give the same answer? :)

http://stackoverflow.com/q/48808896
score: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/47975866
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48808978
tagged with: python
linked to: http://stackoverflow.com/q/26521266
has title: Pandas cannot read specific Excel sheet
type: AnsweredQuestion
has body: Seems like this has an answer here and here already, however, none of these solutions are working for me. I'm trying to do xls = pd.ExcelFile('input.xls') df = pd.read_excel(xls, sheet_name="Sheet2") ## Also tried sheet_name = 1 No matter what, df in the end still contains the first sheet instead of the second. I'm on Python 3 and Pandas 0.20.1 (Anaconda distro). What am I missing? How can I load the second sheet into df?
upvote count: 3
has comment: http://stackoverflow.com/comment/84620917
has comment: http://stackoverflow.com/comment/84620889
tagged with: excel
accepted answer: http://stackoverflow.com/a/48808978
type: Question

http://stackoverflow.com/comment/127950251
comment on: http://stackoverflow.com/a/48904483
score: 0
type: Comment
has text: This comment solved my problem.
type: AnswerComment

http://stackoverflow.com/comment/84816127
has text: Tried that. Next to `django-extensions` there are 10 more apps that have custom commands that are not being loaded.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48905271

http://stackoverflow.com/comment/84622754
type: QuestionComment
comment on: http://stackoverflow.com/q/48809681
score: 0
has text: The normal way to deal with this type of worry is to use cross-validation, whereby you train and test on multiple random splits of the data.
type: Comment

http://stackoverflow.com/comment/84722793
score: 0
type: AnswerComment
has text: I'm able to split it, however I'm not sure how make it iterate across the 1st index of every sublist, my program will evaluate the first index then make an entirely new deck without evaluating the rest of the sublists in the new list.
type: Comment
comment on: http://stackoverflow.com/a/48859573

http://stackoverflow.com/comment/84630909
type: QuestionComment
has text: What do you mean args? arguments are what you put into a function / script. If you want to take something out you'll have to `echo` each argument in the `.sh` script and read stdout.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48813627

python-2.7
tags question: http://stackoverflow.com/q/48875213
tags question: http://stackoverflow.com/q/48829227
tags question: http://stackoverflow.com/q/48900738
tags question: http://stackoverflow.com/q/48816711
tags question: http://stackoverflow.com/q/48953195
tags question: http://stackoverflow.com/q/48962594
tags question: http://stackoverflow.com/q/48900858
tags question: http://stackoverflow.com/q/48928293
tags question: http://stackoverflow.com/q/48918009
tags question: http://stackoverflow.com/q/48850089
tags question: http://stackoverflow.com/q/48835776
tags question: http://stackoverflow.com/q/48958035
tags question: http://stackoverflow.com/q/48945064
tags question: http://stackoverflow.com/q/48928944
tags question: http://stackoverflow.com/q/48817972
tags question: http://stackoverflow.com/q/48813114
tags question: http://stackoverflow.com/q/48917077
tags question: http://stackoverflow.com/q/48871845
tags question: http://stackoverflow.com/q/48934415
tags question: http://stackoverflow.com/q/48884494
tags question: http://stackoverflow.com/q/48845686
tags question: http://stackoverflow.com/q/48909852
tags question: http://stackoverflow.com/q/48892906
tags question: http://stackoverflow.com/q/48903434
tags question: http://stackoverflow.com/q/48849192
tags question: http://stackoverflow.com/q/48857612
tags question: http://stackoverflow.com/q/48897299
tags question: http://stackoverflow.com/q/48810652
tags question: http://stackoverflow.com/q/48855560
tags question: http://stackoverflow.com/q/48834300
tags question: http://stackoverflow.com/q/48918495
tags question: http://stackoverflow.com/q/48846980
tags question: http://stackoverflow.com/q/48957099
tags question: http://stackoverflow.com/q/48931681
tags question: http://stackoverflow.com/q/48901289
tags question: http://stackoverflow.com/q/48929950
tags question: http://stackoverflow.com/q/48895218
tags question: http://stackoverflow.com/q/48931719
tags question: http://stackoverflow.com/q/48845368
tags question: http://stackoverflow.com/q/48853692
tags question: http://stackoverflow.com/q/48883443
tags question: http://stackoverflow.com/q/48913031
tags question: http://stackoverflow.com/q/48808985
tags question: http://stackoverflow.com/q/48859616
tags question: http://stackoverflow.com/q/48932847
tags question: http://stackoverflow.com/q/48839280
tags question: http://stackoverflow.com/q/48876746
tags question: http://stackoverflow.com/q/48929553
tags question: http://stackoverflow.com/q/48949273
tags question: http://stackoverflow.com/q/48954842
tags question: http://stackoverflow.com/q/48909487
tags question: http://stackoverflow.com/q/48813329
tags question: http://stackoverflow.com/q/48946338
tags question: http://stackoverflow.com/q/48944703
tags question: http://stackoverflow.com/q/48813285
tags question: http://stackoverflow.com/q/48936463
tags question: http://stackoverflow.com/q/48941102
tags question: http://stackoverflow.com/q/48941440
tags question: http://stackoverflow.com/q/48898406
tags question: http://stackoverflow.com/q/48870758
tags question: http://stackoverflow.com/q/48839120
tags question: http://stackoverflow.com/q/48867875
tags question: http://stackoverflow.com/q/48804790
tags question: http://stackoverflow.com/q/48832630
tags question: http://stackoverflow.com/q/48918231
tags question: http://stackoverflow.com/q/48868480
tags question: http://stackoverflow.com/q/48917785
tags question: http://stackoverflow.com/q/48925609
tags question: http://stackoverflow.com/q/48809682
tags question: http://stackoverflow.com/q/48837220
tags question: http://stackoverflow.com/q/48960087
tags question: http://stackoverflow.com/q/48810342
tags question: http://stackoverflow.com/q/48885930
tags question: http://stackoverflow.com/q/48904453
tags question: http://stackoverflow.com/q/48856874
tags question: http://stackoverflow.com/q/48809312
tags question: http://stackoverflow.com/q/48905051
tags question: http://stackoverflow.com/q/48850945
tags question: http://stackoverflow.com/q/48903408
tags question: http://stackoverflow.com/q/48838050

http://stackoverflow.com/a/48839205
score: -1
has comment: http://stackoverflow.com/comment/84683177
has body: You Can Use the following script to really get a true output def mystrcmp(x,y): x, y = str(x),str(y) print(x.lower(),y.lower()) if x.lower() == y.lower(): print ("true") else: print ("false") mystrcmp("python", "pYTHON")
type: AcceptedAnswer
downvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48838682
upvote count: 0
answers question: http://stackoverflow.com/q/48838682

http://stackoverflow.com/q/48948065
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/48948150
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/2150108
tagged with: python
type: AnsweredQuestion
tagged with: list
has title: Rotating a list n times when n is greater than the number of elements in list
possible better answer: http://stackoverflow.com/a/71374865
has body: The following function (taken from this SO question) works fine as long as number of rotations does not exceed the number of elements in list. After that it just repeats the original list. Is there any modification that can be done to rotate a list any number of times? def shift(l,n): return l[n:] + l[:n]
has answer: http://stackoverflow.com/a/71374865
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48948150
answer count: 2

http://stackoverflow.com/q/48846085
has answer: http://stackoverflow.com/a/66111302
favorite count: 0
has comment: http://stackoverflow.com/comment/84698957
has comment: http://stackoverflow.com/comment/84704718
answer count: 5
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/29629103
tagged with: python
tagged with: jupyter
has title: Python Multiprocessing within Jupyter Notebook
upvote count: 19
has comment: http://stackoverflow.com/comment/84698125
has answer: http://stackoverflow.com/a/73619062
score: 19
has answer: http://stackoverflow.com/a/50385056
linked to: http://stackoverflow.com/q/19547443
tagged with: multiprocessing
type: Question
has body: I am new to the multiprocessing module in Python and work with Jupyter notebooks. I have tried the following code snippet from PMOTW: import multiprocessing def worker(): """worker function""" print('Worker') return if __name__ == '__main__': jobs = [] for i in range(5): p = multiprocessing.Process(target=worker) jobs.append(p) p.start() When I run this as is, there is no output. I have also tried creating a module called worker.py and then importing that to run the code: import multiprocessing from worker import worker if __name__ == '__main__': jobs = [] for i in range(5): p = multiprocessing.Process(target=worker) jobs.append(p) p.start() There is still no output in that case. In the console, I see the following error (repeated multiple times): Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "C:\Program Files\Anaconda3\lib\multiprocessing\spawn.py", line 106, in spawn_main exitcode = _main(fd) File "C:\Program Files\Anaconda3\lib\multiprocessing\spawn.py", line 116, in _main self = pickle.load(from_parent) AttributeError: Can't get attribute 'worker' on &lt;module '__main__' (built-in)&gt; However, I get the expected output when the code is saved as a Python script and exectued. What can I do to run this code directly from the notebook without creating a separate script?
has comment: http://stackoverflow.com/comment/84698014
linked to: http://stackoverflow.com/q/2738809
has comment: http://stackoverflow.com/comment/84698060
has comment: http://stackoverflow.com/comment/84699349
has answer: http://stackoverflow.com/a/72663473
has comment: http://stackoverflow.com/comment/84698097
has comment: http://stackoverflow.com/comment/84701302
has comment: http://stackoverflow.com/comment/84698052
downvote count: 0
has answer: http://stackoverflow.com/a/54252710

http://stackoverflow.com/q/48930068
answer count: 3
tagged with: pandas
upvote count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48931059
has answer: http://stackoverflow.com/a/48930121
possible better answer: http://stackoverflow.com/a/48930214
accepted answer: http://stackoverflow.com/a/48930121
has body: I would like to create a data frame from the following lists: list1 = [1, 1, 1, 0, 4, 3, 10, 6, 16, 18, 39, 284, 3857, 3924, 334, 43, 14, 4, 3, 3] list2 = ['-150&lt; n &lt;-138', '-137&lt; n &lt;-127', '-126&lt; n &lt;-115', '-114&lt; n &lt;-104', '-103&lt; n &lt;-92', '-91&lt; n &lt;-81', '-80&lt; n &lt;-69', '-68&lt; n &lt;-58', '-57&lt; n &lt;-46', '-45&lt; n &lt;-35', '-34&lt; n &lt;-23', '-22&lt; n &lt;-12', '-11&lt; n &lt;0', '0&lt; n &lt;11', '12&lt; n &lt;22', '23&lt; n &lt;34', '35&lt; n &lt;45', '46&lt; n &lt;57', '58&lt; n &lt;68', '69&lt; n &lt;80'] I tried this but it does not work my_dict = {} for i in range(len(temp)): my_dict[temp2[i]] = temp[i] df1 = pd.DataFrame(data=my_dict) ValueError: If using all scalar values, you must pass an index I want to understand why this wrong and I want to create a data frame with the columns being the string and the values being the numbers. Thank you in advance
has answer: http://stackoverflow.com/a/48930214
tagged with: python
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
has title: Creating a dataframe from lists
type: Question
has comment: http://stackoverflow.com/comment/84866850
has comment: http://stackoverflow.com/comment/84866883
has comment: http://stackoverflow.com/comment/84866777
tagged with: dataframe

http://stackoverflow.com/q/48813238
tagged with: raspberry-pi3
has title: Connecting Raspberry Pi 3 to MSSQL Server using pyodbc
favorite count: 0
has comment: http://stackoverflow.com/comment/84634481
possible better answer: http://stackoverflow.com/a/61902825
has answer: http://stackoverflow.com/a/61902825
tagged with: python
tagged with: pyodbc
accepted answer: http://stackoverflow.com/a/48863215
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84631049
has comment: http://stackoverflow.com/comment/84630331
type: Question
tagged with: raspbian
linked to: http://stackoverflow.com/q/9723656
score: 5
upvote count: 5
has comment: http://stackoverflow.com/comment/84630856
has answer: http://stackoverflow.com/a/48863215
tagged with: sql-server
has comment: http://stackoverflow.com/comment/84634781
answer count: 2
has body: I am currently trying to get my raspberry pi 3 with Raspbian Stretch Lite (November 2017) connecting to an MSSQL Server. I was following this guide and replaced the Driver and the Setup fields with Driver=/usr/lib/arm-linux-gnueabihf/odbc/libtdsodbc.so Setup=/usr/lib/arm-linux-gnueabihf/odbc/libtdsS.so to match the paths on my pi, as someone proposed in the comment section. When im trying to connect via a python script with conn = pyodbc.connect('DRIVER=FreeTDS;SERVER&lt;IP_OR_HOSTNAME&gt;;PORT=1433;DATABASE&lt;DATABASE_NAME&gt;;UID=&lt;USERNAME&gt;;PWD=&lt;PASSWORD&gt;;') where &lt;> is filled with the correct strings, my script gets stuck on this line without printing anything until i do a keyboard interrupt. I was also trying to get the official MS Drivers to work, using the Debian 9 Versions, but I can't manage to install the packages since msodbcsql still cant be located after the curl commands and apt-get update. Am I missing something to get FreeTDS working or does the script getting stuck mean the pi cant connect to the server? Is there any other possibility to get the pi connected to MSSQL? Thank you in advance.
downvote count: 0

http://stackoverflow.com/q/48825114
upvote count: 0
has comment: http://stackoverflow.com/comment/84653862
type: Question
tagged with: arrays
has answer: http://stackoverflow.com/a/48825130
downvote count: 3
has body: I've made a Python program with array that has 2 items. I want to split and join those 2 items into one item. So the result should be 'first item, second item'. It gives that error AttributeError: 'list' object has no attribute 'split'. I attached the code. items_in_cart=['first item','second item'] a,b=items_in_cart.split(", ") items_in_cart=a+b print(items_in_cart)
answer count: 1
favorite count: 0
type: UnansweredQuestion
score: -3
has title: How to split 2 items of an array and join into one item?
tagged with: python

http://stackoverflow.com/comment/84644037
has text: Where's the `global` keyword? It isn't `global`.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48820118
score: 0

http://stackoverflow.com/a/48827615
has body: After adapting this answer (for cosmetic essentially) I got: from functools import reduce import operator def nested_get(dictionary, *keys): return reduce(operator.getitem, keys, dictionary) def nested_set(dictionary, value, *keys): nested_get(dictionary, *keys[:-1])[keys[-1]] = value example = { 'a': {'b': 'c'}, '1': { '2': { '3': {'4': '5'} } } } nested_set(example, "foo", "1", "2", "3") print(example) keys = ["1", "2"] nested_set(example, "yay", *keys) print(example) Output: {'a': {'b': 'c'}, '1': {'2': {'3': 'foo'}}} {'a': {'b': 'c'}, '1': {'2': 'yay'}} Same idea (to use the fact that the variables are passed by reference), but this time adapting one of my answers: def nested_set(element, value, *keys): if type(element) is not dict: raise AttributeError('nested_set() expects dict as first argument.') if len(keys) &lt; 2: raise AttributeError('nested_set() expects at least three arguments, not enough given.') _keys = keys[:-1] _element = element for key in _keys: _element = _element[key] _element[keys[-1]] = value example = {"foo": { "bar": { "baz": "ok" } } } nested_set(example, "yay", "foo", "bar") print(example) Output {'foo': {'bar': 'yay'}} This one does not requires any fancy imports, so I tend to like it more.. Chose your flavor
type: Answer
answers question: http://stackoverflow.com/q/48827501
score: 0

http://stackoverflow.com/a/48906228
has comment: http://stackoverflow.com/comment/84850172
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84818612
has comment: http://stackoverflow.com/comment/84818547
answers question: http://stackoverflow.com/q/48906155
score: 1
has comment: http://stackoverflow.com/comment/84849915
downvote count: 0
has body: I think you need loop by range and value k add to column name - each loop is created another column: def total_calc(i,n): for k in range(n): input = pd.read_csv(file_name) input['calc' + str(i)] = 0.0 for index, row in input.iterrows(): # perform calculations input.at[index, 'calc' + str(i)] = calc_value input.to_csv(file_name, index=False)
has comment: http://stackoverflow.com/comment/84818776
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48906155
has comment: http://stackoverflow.com/comment/84849620
has comment: http://stackoverflow.com/comment/84849726
has comment: http://stackoverflow.com/comment/84850137

http://stackoverflow.com/comment/84811020
has text: I think that `multiprocessing` is making a full copy of your `AnytimeAlgorithm` instance and running the `update_forever` method on that instance. Meanwhile your local thread and local instance never gets modified.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48902620
score: 0

http://stackoverflow.com/comment/84661975
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48826935
type: Comment
has text: It isn't natural form. When you want to pass a string into the method, you shouldn't think about it. And I can't pass string like `'a.first.test_one'`, all splitted by char

http://stackoverflow.com/q/48958204
accepted answer: http://stackoverflow.com/a/48958930
tagged with: machine-learning
type: Question
tagged with: time-series
has answer: http://stackoverflow.com/a/48958930
score: 0
tagged with: pandas
answer count: 1
has body: I think the best explanation would be an input-output example of what I need (in links attached). In words: I have a data frame with dates and values of some arrays A/B/C. and a result column (1/0 values). I want to make new data frame. The rows are dates. the feature columns are of the kind: "the value of array A/B/C ,X months before current row date". where X can change on my demand. The result column is 1 if there is 1 in the next or next next month in the original data frame. Is there a pythonic way of doing this? I've tried stuff with lops and indexes but it just doesnt feel right... (nor working :() Input Output
tagged with: python
has title: Convert time series data to features - panda way?
type: AnsweredQuestion

http://stackoverflow.com/q/48812105
linked to: http://stackoverflow.com/q/33259477
score: 26
upvote count: 26
has answer: http://stackoverflow.com/a/78181476
type: Question
has body: I had a custom user model in my project. I wanted to delete it and return default user model by deleting all tables in my database and deleting migrations. After this, I tried to run python manage.py makemigrations command but it writes: Traceback (most recent call last): File "manage.py", line 15, in &lt;module&gt; execute_from_command_line(sys.argv) File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 678, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_removed File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/contrib/contenttypes/apps.py", line 9, in &lt;module&gt; from .management import ( File "/home/irakliy01/Projects/Project/PythonVEnv/lib/python3.6/site-packages/django/contrib/c…
linked to: http://stackoverflow.com/q/47849765
has comment: http://stackoverflow.com/comment/84628166
downvote count: 0
has answer: http://stackoverflow.com/a/67473918
has comment: http://stackoverflow.com/comment/87010504
has answer: http://stackoverflow.com/a/76300128
has comment: http://stackoverflow.com/comment/84628029
has title: Django No module named 'django.db.migrations.migration'
tagged with: python
favorite count: 0
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/52463046
tagged with: django
has answer: http://stackoverflow.com/a/79253843
has comment: http://stackoverflow.com/comment/84628381

http://stackoverflow.com/comment/84644670
has text: Assuming a list of unique words, build a dictionary like this `{k:i for i, k in enumerate(lst)}`
comment on: http://stackoverflow.com/q/48817141
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48911848
answers question: http://stackoverflow.com/q/48911638
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84857774
downvote count: 0
has body: You can using string import string l=list(string.ascii_uppercase) b=l+[x+y for x in l for y in l] b[50-1] Out[1240]: 'AX'
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/48911638

http://stackoverflow.com/comment/84930256
type: Comment
comment on: http://stackoverflow.com/a/48956860
score: 1
has text: is there any way to get all URLs programmatically ? for example , i want to extract the data from these URLs but i don't prefer to go in each URL to copy it and past in the list to do sth , http://www.poetsgate.com/Poet.aspx?id=45&type=cat&typeid=5
type: AnswerComment

http://stackoverflow.com/q/48958387
possible better answer: http://stackoverflow.com/a/49046025
has answer: http://stackoverflow.com/a/49113855
favorite count: 0
tagged with: python-3.x
tagged with: google-api
tagged with: python
answer count: 4
type: AnsweredQuestion
has body: I'm trying out google customsearch api to search image and but the weird thing is my search through api returns different result than regular search through browser. for example from apiclient.discovery import build import pprint import sys api_key='xxxxxxx' service = build('customsearch', 'v1', developerKey=api_key) request=service.cse() query=request.list(cx='xxxx:xxxxx',q='dogs and cats',searchType='image',imgType='photo') result=query.execute() pprint.pprint(result) for i in result.get('items',[]): print (i['link']) running this code gives totally different result here is result from running above code https://s.yimg.com/ny/api/res/1.2/tarWzt2ZXfPOEg8oQVlOWw--/YXBwaWQ9aGlnaGxhbmRlcjtzbT0xO3c9ODAw/http://media.zenfs.com/en-US/homerun/people_218/4d82a5fa19dd37247717704975fdf602 https://www.google.com/about/main/machine-learning-qa/img/cat-dog-flow-horizontal.gif https://www.google.com/trends/2014/static/images/pets-snapshot-reveal-1920.jpg https://www.google.com/trends/2014/static/images/pets-share.png https://www.google.com/about/main/machine-learning-qa/img/cat-dog-flow-vertical.gif https://s.yimg.com/uu/api/res/1.2/YQWuQgTnzQuwXjYzX.QrWg--~B/aD0xMzMzO3c9MjAwMDtzbT0xO2FwcGlkPXl0YWNoeW9u/http://media.zenfs.com/en-US/homerun/people_218/4d82a5fa19dd37247717704975fdf602 https://www.google.com/trends/2014/static/images/pets-video-1080.jpg https://www.google.com/trends/2014/static/images/pets-video-320.jpg https://www.google.com/maps/d/thumbnail?mid=1hO0YkGLATyy-ZI9JxX1lbv-wK1M&amp;hl=en_US here is a snapshot of google search from chrome queries are same, anyone knows why?
has comment: http://stackoverflow.com/comment/85102005
tagged with: google-custom-search
accepted answer: http://stackoverflow.com/a/49113855
type: Question
upvote count: 15
has title: google customsearch returns different result?
downvote count: 0
has answer: http://stackoverflow.com/a/49046025
score: 15
tagged with: search
has answer: http://stackoverflow.com/a/49114197
has answer: http://stackoverflow.com/a/49153075

http://stackoverflow.com/comment/84737327
type: Comment
type: QuestionComment
has text: Have you checked if the values of `inverse` actually fit in a 8 bytes integer? (I bet they don't.) Try to make your life easy and cast to `np.float64` instead. Also think about if you really want to discard the imaginary part.
comment on: http://stackoverflow.com/q/48865868
score: 0

http://stackoverflow.com/comment/84890112
comment on: http://stackoverflow.com/a/48941410
has text: @ArchivistG No problem! Should also make note of some style stuff for future reference -- `generate_euid()` would be much better with a final line `return inits + str(...)` instead of a `print()`, because returning it affords you flexibility in what you do with the data: you can write, for instance, `print(Your EUID: ', user.generate_euid())` from the outside without affecting the function's return value. Less-important: `import random` should be at the top of the file (for clarity/transparency), and [PEP8](https://python.org/dev/peps/pep-0008) suggests snake_case over camelCase for var names!
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/118557190
type: AnswerComment
comment on: http://stackoverflow.com/a/48907758
score: 0
type: Comment
has text: @perymerdeka let me google that for you: https://werkzeug.palletsprojects.com/en/1.0.x/middleware/dispatcher/

http://stackoverflow.com/q/48884782
favorite count: 0
has answer: http://stackoverflow.com/a/48886754
type: UnansweredQuestion
has body: I am running the example from this link. I have successfully ran the code after few modifications. Here is the code modified: import quandl, math import numpy as np import pandas as pd from sklearn import preprocessing, cross_validation, svm from sklearn.linear_model import LinearRegression import matplotlib.pyplot as plt from matplotlib import style import datetime style.use('ggplot') df = quandl.get("WIKI/GOOGL") df = df'Adj. Open', 'Adj. High', 'Adj. Low', 'Adj. Close', 'Adj. Volume' df['HL_PCT'] = (df['Adj. High'] - df['Adj. Low']) / df['Adj. Close'] * 100.0 df['PCT_change'] = (df['Adj. Close'] - df['Adj. Open']) / df['Adj. Open'] * 100.0 df = df'Adj. Close', 'HL_PCT', 'PCT_change', 'Adj. Volume' forecast_col = 'Adj. Close' df.fillna(value=-99999, inplace=True) forecast_out = int(math.ceil(0.01 * len(df))) df['label'] = df[forecast_col].shift(-forecast_out) X = np.array(df.drop(['label'], 1)) X = preprocessing.scale(X) X_lately = X[-forecast_out:] X = X[:-forecast_out] df.dropna(inplace=True) y = np.array(df['label']) X_train, X_test, y_train, y_test = cross_validation.train_test_split(X, y, test_size=0.2) clf = LinearRegression(n_jobs=-1) clf.fit(X_train, y_train) confidence = clf.score(X_test, y_test) forecast_set = clf.predict(X_lately) df['Forecast'] = np.nan last_date = df.iloc[-1].name last_unix = last_date.timestamp() one_day = 86400 next_unix = last_unix + one_day for i in forecast_set: next_date = datetime.datetime.fromtimestamp(next_unix) next_unix += 86400 df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i] df['Adj. Close'].plot() df['Forecast'].plot() plt.legend(loc=4) plt.xlabel('Date') plt.ylabel('Price') plt.show() But the issue I am facing is with the forecasting of the future dataframe. Here is the output image: I am getting till 2017-2018 as in the image. How to move further to 2019, 2020 or 5 years from now?
tagged with: python
tagged with: sklearn-pandas
score: 2
downvote count: 2
type: Question
has title: How to forecast future dataframe using sklearn python?
has answer: http://stackoverflow.com/a/48885038
tagged with: forecasting
upvote count: 4
tagged with: python-2.7
answer count: 2
tagged with: scikit-learn

http://stackoverflow.com/q/48942649
has title: Django PasswordChangeForm won't load widget attributes
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84892453
has comment: http://stackoverflow.com/comment/84895841
type: UnansweredQuestion
tagged with: django
tagged with: python
answer count: 0
tagged with: widget
score: 1
has comment: http://stackoverflow.com/comment/84891980
upvote count: 1
tagged with: django-forms
has body: I am trying to make a "Change Password"-page by using the PasswortChangeForm (with old_password, new_password1, new_password2). The function itself works perfectly, but it will not load any widget attribute. I did the same thing with the RegistrationForm (to create a user) and it worked fine. forms.py class PasswordChangeForm(SetPasswordForm): old_password = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', 'autofocus': 'autofocus', } ) ) new_password1 = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', } ) ) new_password2 = forms.CharField(required=True, widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'type': 'password', 'name': 'password1', } ) ) class Meta: model = User fields = ( 'old_password', 'new_password1', 'new_password2', ) def clean_old_password(self): old_password = self.cleaned_data["old_password"] if not self.user.check_password(old_password): raise forms.ValidationError( self.error_messages['password_incorrect'], code='password_incorrect', ) return old_password views.py def change_password(request): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) return redirect('accounts:change_password_done') else: form = PasswordChangeForm(request.user) return render(request, 'accounts/change_password.html', { 'form': form }) change_password.html {% load widget_tweaks %} {% csrf_token %} {{ form.non_field_errors }} Altes Passwort* {{ form.old_password }} Neues Passwort* {{ form.new_password1 }} Neues Passwort bestätigen* {{ form.new_password2 }} Bestätigen Zurück {% if form.old_password.errors %} Ihre altes Passwort ist nicht korrekt. Bitte versuchen Sie es erneut. {% endif %} {% if form.new_password2.errors %} Ihr neues Passwort stimmt nicht überein. Bitte versuchen Sie es er…
type: Question

http://stackoverflow.com/comment/84874497
type: Comment
type: QuestionComment
has text: What happens if you `import unittest` inside a virtual environment using python3.6? If you've never used virtualenv, you can ignore this comment.
comment on: http://stackoverflow.com/q/48933845
score: 0

http://stackoverflow.com/a/48834570
score: 1
answers question: http://stackoverflow.com/q/48833947
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: This is one way. Just set your index as Axis, then rename columns to first row. df = df.set_index('Axis').rename(columns=df.iloc[0]) df.loc['ZAB', 'GHI'] # 'XX'
accepted answer of: http://stackoverflow.com/q/48833947

http://stackoverflow.com/comment/84865786
has text: @narunasK - I guess that makes sense. However, don't I want the migration file to be local as well? If so, how? If not, why not?
comment on: http://stackoverflow.com/q/48929409
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84909463
has text: Using iterrows would work for the rows, but I'm also trying to iterate over the columns. That's why my question is not exaclty the same as the other thread pointed as the answer...
comment on: http://stackoverflow.com/q/48951047
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84854354
comment on: http://stackoverflow.com/q/48924029
has text: What is that error ?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48854847
accepted answer of: http://stackoverflow.com/q/48854656
answers question: http://stackoverflow.com/q/48854656
upvote count: 1
type: AcceptedAnswer
has body: Simply add the documented: listbox.delete('0', 'end') in order to delete all entries in listbox to, -- the method that updates your Listbox, checker as the first line.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/q/48853391
has answer: http://stackoverflow.com/a/48853429
type: Question
has answer: http://stackoverflow.com/a/48853422
downvote count: 4
answer count: 3
has answer: http://stackoverflow.com/a/48853424
has comment: http://stackoverflow.com/comment/84710205
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: parity
tagged with: python
has title: Counting the occurrences of a character in each element of a list
tagged with: list
has body: lst = ['10010001','01101001'] I need to count the number of times the number '1' appears in each element
upvote count: 1

http://stackoverflow.com/q/48916226
has comment: http://stackoverflow.com/comment/84839093
downvote count: 1
has comment: http://stackoverflow.com/comment/84839103
has answer: http://stackoverflow.com/a/48916492
has body: I have a string of text like following 1. Foobar { abc } ( Explanation - Foo { cde } - Count - 5301435 ) 2. Foobaz { memo } ( Explanation - baz {bleh } - Count - 13946664 ) And I want to extract abc and memo in the above string. I have the regex as follows [link here] essentially {(?:[^{}])*} But it captures everything (returns abc, cde, memo, bleh)
has comment: http://stackoverflow.com/comment/84838934
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48916501
has answer: http://stackoverflow.com/a/48916441
type: Question
accepted answer: http://stackoverflow.com/a/48916441
has comment: http://stackoverflow.com/comment/84839401
has comment: http://stackoverflow.com/comment/84838932
favorite count: 0
answer count: 3
has comment: http://stackoverflow.com/comment/84839187
has comment: http://stackoverflow.com/comment/84838960
tagged with: regex
has answer: http://stackoverflow.com/a/48916501
has comment: http://stackoverflow.com/comment/84839280
score: 6
has title: Extracting text between curly braces in python
tagged with: python
upvote count: 7

http://stackoverflow.com/q/48818431
has title: webscraping data and use pandas read_html to convert it to dataframe and merge the dataset together
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48818529
has body: I'm kinda new to python and having some problem with my code. Would appreciate any suggestions on what I try to do. import pandas as pd from bs4 import BeautifulSoup import requests def trade(): tickers = ["AAPL","AMZN", "INTC", "MSFT", "SNAP"] for ticker in tickers: url = "http://finance.yahoo.com/quote/%s?p=%s"%(ticker,ticker) res = requests.get(url) soup = (BeautifulSoup(res.content, 'lxml')) table = soup.find_all('table')[0] df = pd.read_html(str(table)) print("DF") print(df) df_string = str(df) print(df_string_parse) print(type(df_string_parse)) When I look at df, it displays string like this [ 0 1 0 Previous Close 167.37 1 Open 169.79 2 Bid 157.23 x 300 3 Ask 157.29 x 500 4 Day's Range 169.00 - 173.09 5 52 Week Range 134.84 - 180.10 6 Volume 51124085 7 Avg. Volume 33251246] What I want to do, is to store each ticker's table into dataframe, and merge them together like below. Or I guess if there is a way, I Could turn that into dictionary so that I could use its variable more easily. APPL AMAZN INTC MSFT SNAP Previous Close Open Bid Ask Day's Range Volume Avg. Volume For now, there are 2 problems that I face: how to turn the table into data frame and/or dictionary after using pd.read_html(str(table)) how to store each ticker's results separately eventually to merge them together? I know how to use for loop to read them one by one, but I don't seem to know how to store them in such way.
accepted answer: http://stackoverflow.com/a/48818529
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
tagged with: beautifulsoup
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
tagged with: web-scraping

http://stackoverflow.com/q/48879108
linked to: http://stackoverflow.com/q/12060863
tagged with: python
has comment: http://stackoverflow.com/comment/84763445
has title: running shell command from python
has comment: http://stackoverflow.com/comment/84762184
has comment: http://stackoverflow.com/comment/84763627
has comment: http://stackoverflow.com/comment/84763014
score: 2
has answer: http://stackoverflow.com/a/48879162
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84762183
has body: I want to automatically check if some KB is installed on the machine. Part of my python script: import subprocess result = subprocess.run(['cmd', '/c wmic qfe'], shell=True, stdout=subprocess.PIPE) ftemp = open('mylog.txt','w') #just to check what is going wrong ftemp.write(str(result.stdout)) ftemp.close() if str(result.stdout).find('KB2999226')==-1: print('Nah, you don't have KB') sys.exit() What I got in the shell while executing: qfe" - Alias not found. Nah, you don't have KB mylog.txt: b'' So, looks like some stupid problem with dashes or encodings. I've tried variety of commands, but nothing succeded. (Yeah, "dism" causes another tons of errors). Some advices?
has comment: http://stackoverflow.com/comment/84763151
has comment: http://stackoverflow.com/comment/84773811
tagged with: shell
tagged with: cmd
favorite count: 0
has comment: http://stackoverflow.com/comment/84763264
has comment: http://stackoverflow.com/comment/84762890
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/84762936
has answer: http://stackoverflow.com/a/48879131
has comment: http://stackoverflow.com/comment/84762486
answer count: 2
has comment: http://stackoverflow.com/comment/84762881

http://stackoverflow.com/comment/84746238
has text: Try: `(<header)((?s).*)( )` This matched your string for me, but note that using inline modifiers in the middle of a regex is considered bad practice I believe.
score: 2
comment on: http://stackoverflow.com/q/48871211
type: Comment
type: QuestionComment

encoder-decoder
type: Tag
tags question: http://stackoverflow.com/q/48899234
tags question: http://stackoverflow.com/q/48918964
tag name: encoder-decoder

http://stackoverflow.com/a/57703338
has body: For marshmallow version >= 3 (Python 3) You can achieve this by using Pluck fields to allow the parent to get data from its child. class ActualDataSchema(ModelSchema): useful = fields.String() also_useful = fields.String() class ObjectSchema(ModelSchema): useful = fields.Pluck(ActualDataSchema, 'useful') also_useful = fields.Pluck(ActualDataSchema, 'also_useful') class DestSchema(ModelSchema): id = fields.Integer() objects = fields.Nested(ObjectSchema, many=True) For marshmallow version &lt; 3 (Python 2) You have to use Method or Function fields instead. class ObjectSchema(ModelSchema): useful = fields.Function(lambda obj: obj.actual_data.useful) also_useful = fields.Function(lambda obj: obj.actual_data.also_useful) class DestSchema(ModelSchema): id = fields.Integer() objects = fields.Nested(ObjectSchema, many=True) More info For another example of this exact problem that's a bit more fleshed out and involves SQLAlchemy and Flask, see my other answer here. documentation for fields.Pluck() documentation for fields.Function() and fields.Method()
answers question: http://stackoverflow.com/q/48951151
score: 9
upvote count: 9
downvote count: 0
type: Answer

http://stackoverflow.com/a/48856079
answers question: http://stackoverflow.com/q/48855674
downvote count: 0
has body: You add the number of each candidates votes at the same time you calculate the percent vote for each candidate. You need to find the total votes first, then divide each candidates votes by the total You are returning the max of a list of integers. Obviously you aren't going to get a string. You need some way to connect the number votes with the candidate. Don't bother. You can try to figure out how many tabs you need to get the whole thing lined up, but from experience, it is basically impossible. You could separate them with commas and open it in excel as a csv, or you could just make the user figure out what number goes with what. The other answer uses data tables, so I will take another, more vanilla and cool approach to getting what you want. class candidate(): def __init__(self, name, votes): self.name = name self.votes = int(votes) def percentvotes(self, total): self.percent = self.votes/total def printself(self, i): print('{}\t{}\t\t{}\t\t{}'.format(i, self.name, self.votes, self.percent)) def getinput(): inp = input('Please enter your candidates name and votes') return inp candidates = [] inp = getinput() s = 0 while inp != '': s+=1 candidates.append(candidate(*inp.split(" "))) inp = getinput() for c in candidates: c.percentvotes(s) candidates.sort(key = lambda x:-x.percent) print('ID\tname\t\tvotes\t\tpercentage') for i, c in enumerate(candidates): c.printself(i+1)
has comment: http://stackoverflow.com/comment/84720766
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84752239
upvote count: 2
has comment: http://stackoverflow.com/comment/84722237

http://stackoverflow.com/comment/84755710
type: Comment
comment on: http://stackoverflow.com/a/48859067
score: 0
type: AnswerComment
has text: thanks for putting this together. sorry for the additional questions, but how would this work with a function? I'm new to python so trying to figure out how I can pass two values (i.e. a key and a value) into a function and then use the for loop you put together to iterate through everything. I want to figure out how to keep it as close as possible to the script I used above: def func2(k, v): new_k = k + v return new_k for k, v in integer_dictionary.items(): new_dict2[k] = func2(k, v)

http://stackoverflow.com/q/48847926
type: Question
tagged with: reference-counting
tagged with: python
tagged with: dictionary
has title: Python C Extension Nested Dictionary Segmentation Fault
upvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/48868849
type: AnsweredQuestion
score: 2
has body: I am trying to create a Python (2.7.12) extension in C that does the following: Provide a read only nested dictionary with module level scope for the Python programmer. A background thread invisible to the Python programmer will add, delete, and modify entries in the dictionary. The extension will be built directly into the Python interpreter. I created a simplified version of this extension that adds one entry to the dictionary and then constantly modifies it with new values. Below is the C file containing comments about what it is doing along with my understanding how the reference counts are being handled. #include &lt;Python.h&gt; #include &lt;pthread.h&gt; static PyObject *module; static PyObject *pyitem_error; static PyObject *item; static PyObject *item_handle; static pthread_t thread; void *stuff(void *param) { int garbage = 0; PyObject *size; PyObject *value; while(1) { // Build a dictionary called size containg two integer objects // Py_BuildValue will pass ownership of its reference to size to this thread size = NULL; size = Py_BuildValue("{s:i,s:i}", "l", garbage, "w", garbage); if(size == NULL) { goto error; } // Build a dictionary containing an integer object and the size dictionary // Py_BuildValue will create and own a reference to the size dictionary but not steal it // Py_BuildValue will pass ownership of its reference to value to this thread value = NULL; value = Py_BuildValue("{s:i,s:O}", "h", garbage, "base", size); if(value == NULL) { goto error; } // Add the new data to the dictionary // PyDict_SetItemString will borrow a reference to value PyDict_SetItemString(item, "dim", value); error: Py_XDECREF(size); Py_XDECREF(value); garbage++; } return NULL; } // There will be methods for this module in the future static PyMethodDef pyitem_methods[] = { {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initpyitem(void) { // Create a module object // Own a reference to it since Py_InitModule returns a borrowed reference module = Py_InitModule("pyitem", pyitem_me…
downvote count: 0
tagged with: segmentation-fault
favorite count: 0
accepted answer: http://stackoverflow.com/a/48868849

http://stackoverflow.com/comment/84881640
type: Comment
has text: Thank you very much. Out of interest, if text ="a" was in a separate function and not outside them all, how would one call it in a different function?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48937285

http://stackoverflow.com/comment/84640434
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48818213
has text: Some example dataset and your desired output will be helpful.

http://stackoverflow.com/a/48914954
downvote count: 0
has body: The problem is caused because you are creating 2 buttons: # # View Evidence Button self.viewEvidenceButton = QtWidgets.QPushButton(self.centralwidget) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(12) font.setBold(True) font.setWeight(75) self.viewEvidenceButton.setFont(font) self.viewEvidenceButton = QtWidgets.QPushButton(self.centralwidget) # &lt;--- remove this line self.viewEvidenceButton.setObjectName("viewEvidenceButton") removes the second creation of the button and thus that button does not appear.
type: Answer
answers question: http://stackoverflow.com/q/48914098
accepted answer of: http://stackoverflow.com/q/48914098
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/q/48879011
has title: Confusion and conflicts with multiple Python bins and package locations
accepted answer: http://stackoverflow.com/a/48879549
downvote count: 0
has body: *I hope this isn't a repeat. I've tried looking for clarity, but I'm having trouble. I'm fairly new to Python and used Homebrew to avoid using the system Python on Mac. I guess I also installed anaconda at some point. (probably following some tutorial) Now when I do which for the following, I get different bins: which python: /Users/ryangoree/anaconda3/bin/python which python2: /usr/local/bin/python2 which python3: /Users/ryangoree/anaconda3/bin/python3 which pip: /Users/ryangoree/anaconda3/bin/pip So my issue is that when I'm using python2, there are modules that that I can't use. If I try to pip install them, It just tells me they're already installed since they are in the anaconda directory. I don't know what I don't know right now, but I'm sure there is a better way to handle this. Can someone enlighten me or send me on the right path to developing with Python and managing the packages. Thank you!
type: AnsweredQuestion
score: 1
tagged with: macos
favorite count: 0
type: Question
tagged with: pip
has answer: http://stackoverflow.com/a/48879549
upvote count: 1
tagged with: python
answer count: 1
has comment: http://stackoverflow.com/comment/84761958

http://stackoverflow.com/q/48913153
linked to: http://stackoverflow.com/q/21435176
answer count: 1
tagged with: pyspark
linked to: http://stackoverflow.com/q/3207219
type: UnansweredQuestion
has body: I have a directory that contains CSV files that have the same columns but not in the same order. I would like to append them in one CSV file but when do that with pyspark using the following code I get the csv but with mixed data inside (i.e. it it is not sorting out the order of the columns correctly). from pyspark import SparkContext from pyspark.sql import SQLContext from pyspark.sql.functions import col sc = SparkContext("local", "Simple App") sqlContext = SQLContext(sc) df = sqlContext.read.format('com.databricks.spark.csv').options(header='true', inferschema='true').load('/myPATH/TO_THE_CSV_FILES/') df.coalesce(1).write.option("header", "true").format('com.databricks.spark.csv').save('/myPATH/TO_APPENDED_CSV_FILE/')
has answer: http://stackoverflow.com/a/48913264
has title: Append multiple CSV files with different order of headers
type: Question
tagged with: apache-spark
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
score: 0

http://stackoverflow.com/comment/84868158
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48902452
type: Comment
has text: Amazing, thank you! I'll see what I can do with this.

http://stackoverflow.com/q/48944696
answer count: 3
has comment: http://stackoverflow.com/comment/84896422
tagged with: python-3.x
has title: counting consecutive duplicates in a list. Considering only two digits at a time
tagged with: python
has answer: http://stackoverflow.com/a/48944853
has answer: http://stackoverflow.com/a/48945182
has body: I have an issue with my code: Problem Statement: Count the consecutive two's in the list within a dictionary. For example: If the list is [2,1,0,2,2,2] then the answer would be 3 i.e (2,2) and (2,2) This the code that I have written import ast def calstats(data_dict): consec2Cnt = 0 for key,value in data_dict.items(): for i in range(len(value)-1): if int(value[i]) == int(value [i+1]) and int(value[i]) == 2 and int(value[i+1]) == 2: consec2Cnt += 1 return(consec2Cnt) #print(str(consec2Cnt)) sumCnt = 0 fileinput = open("1.txt",'r') lines = fileinput.readlines() data_dict = {} for eline in lines: data_dict = eline.strip() sumCnt += calstats(ast.literal_eval(data_dict)) print(sumCnt) The link to the file is given here The final result that I am getting is 205 . But the correct answer is 213 . Am I doing something wrong?
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48945182
possible better answer: http://stackoverflow.com/a/48944853
type: Question
has answer: http://stackoverflow.com/a/48945461
has comment: http://stackoverflow.com/comment/84896728
has comment: http://stackoverflow.com/comment/84896502
score: 0

amazon-s3
tags question: http://stackoverflow.com/q/48830418
tags question: http://stackoverflow.com/q/48958072
tags question: http://stackoverflow.com/q/48836860
type: Tag
tags question: http://stackoverflow.com/q/48945389
tags question: http://stackoverflow.com/q/48877925
tags question: http://stackoverflow.com/q/48920726
tags question: http://stackoverflow.com/q/48815646
tags question: http://stackoverflow.com/q/48954080
tags question: http://stackoverflow.com/q/48901990
tags question: http://stackoverflow.com/q/48958005
tags question: http://stackoverflow.com/q/48861162
tags question: http://stackoverflow.com/q/48883208
tag name: amazon-s3
tags question: http://stackoverflow.com/q/48915163
tags question: http://stackoverflow.com/q/48874089
tags question: http://stackoverflow.com/q/48808956
tags question: http://stackoverflow.com/q/48879056
tags question: http://stackoverflow.com/q/48931887

http://stackoverflow.com/a/48941785
answers question: http://stackoverflow.com/q/48941102
upvote count: 1
has body: I suggest you filter out words that endswith the first character. words = ['xerox', 'trust', 'follow', 'blurb', 'maroon', 'ready', 'salad', 'yummy', 'evidence'] result = [w for w in words if w.endswith(w[:1])] This has the particular behavior that it will even work on the empty string.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/84656094
score: 0
type: Comment
has text: That works if I first use the `dropna()` and then `group by` before printing. Based on one column (A), let's say we have an ID 11111. We have 5 rows for this ID without empty fields. Then we have 1 row of which one column (B) has an empty value. I want all the 6 rows for this ID to count as an error.
comment on: http://stackoverflow.com/a/48813157
type: AnswerComment

relative-path
type: Tag
tags question: http://stackoverflow.com/q/48931254
tag name: relative-path

http://stackoverflow.com/comment/84789751
type: Comment
score: 0
has text: I'm trying to get variables a and b to export onto an external .txt document
comment on: http://stackoverflow.com/q/48892101
type: QuestionComment

http://stackoverflow.com/comment/84812147
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48903362
has text: Thumbs up for using multiprocessing. Only this will benefit from multicore systems in this situation.

http://stackoverflow.com/q/48913156
answer count: 1
has comment: http://stackoverflow.com/comment/84832701
has comment: http://stackoverflow.com/comment/84833109
linked to: http://stackoverflow.com/q/8554153
has title: What data structure would be ideal for top/bottom popping?
tagged with: python
type: AnsweredQuestion
has body: I have a list in Python that I share between a few different processes (listproxy) and I need the ability to limit this list to a certain number of elements. The unit is running on a Raspberry Pi with all data stored in memory so I need the list to be able to be limited over time. The list stores log messages just to fill you in on the context, and we are willing to remove the earliest items as it fills up so it's a rolling list essentially. I know I could use an array and just pop off the bottom but then I'm running an O(n-1) operation to move all the elements over 1 element in that array. I can use a Queue, Stack, or Array for this, so long as they are multiprocessing friendly. I know I could create a linked list but I wanted to reach out in case someone else has an idea as a linked list isn't supported out of the box for multiprocessing so I would have to create one. Thanks in advance!
tagged with: python-multiprocessing
type: Question
has comment: http://stackoverflow.com/comment/84832660
has comment: http://stackoverflow.com/comment/84832644
tagged with: data-structures
score: 0
has answer: http://stackoverflow.com/a/48913546
accepted answer: http://stackoverflow.com/a/48913546

http://stackoverflow.com/comment/84932043
type: Comment
has text: I thought using slug in the urls would have made it a bit easier? But it was not working
comment on: http://stackoverflow.com/a/48962105
score: 0
type: AnswerComment

http://stackoverflow.com/q/48951380
has comment: http://stackoverflow.com/comment/84910138
possible better answer: http://stackoverflow.com/a/48951898
has answer: http://stackoverflow.com/a/48951898
has answer: http://stackoverflow.com/a/48951539
tagged with: dataframe
duplicate of: http://stackoverflow.com/q/17071871
has title: Delete row from DataFrame where value is present in another column and 'col3' == Missing
tagged with: pandas
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84910191
has comment: http://stackoverflow.com/comment/84909668
accepted answer: http://stackoverflow.com/a/48951539
type: Question
answer count: 2
has body: I am dealing with this example DataFrame: A B C 1 Cat 0 Missing 2 Dog Dog Match 3 Cat Cat Match I would like to remove row[1] as it meets the condition of 'C' == "Missing" and 'A'.isin('B') Could use help writing this. Currently I have tried; if df['C'] == "Missing": df = df.loc[~df.A.isin(B)] But no luck thus far. Thanks.
tagged with: python
linked to: http://stackoverflow.com/q/17071871
has comment: http://stackoverflow.com/comment/84909815
score: 0

http://stackoverflow.com/a/48952327
answers question: http://stackoverflow.com/q/48949289
accepted answer of: http://stackoverflow.com/q/48949289
upvote count: 1
type: AcceptedAnswer
has body: Apparently, the logic of the solver for this type of systems is incorrect; I raised an issue. Aside: the constants in a solution of a system of differential equations can be presented in multiple ways, there is not a single canonical form of them. It can be expected that the order in which equations are presented will influence the order in which they are processed (like it happens with systems of linear equations), which will affect the form of solution. But, as you point out, neither of two solutions is correct. This can be checked by plugging them in: eq1 = (Eq(Derivative(x(t),t), k3*y(t)), Eq(Derivative(y(t),t), -(k3+k2)*y(t)), Eq(Derivative(z(t),t), k2*y(t))) sol1 = dsolve(eq1) print([eqn.subs({e.lhs: e.rhs for e in sol1}).doit().simplify() for eqn in eq1]) eq2 = (Eq(Derivative(z(t),t), k2*y(t)), Eq(Derivative(x(t),t), k3*y(t)), Eq(Derivative(y(t),t), -(k3+k2)*y(t))) sol2 = dsolve(eq2) print([eqn.subs({e.lhs: e.rhs for e in sol2}).doit().simplify() for eqn in eq2]) The first prints [Eq(C3*k3*(k2 + k3)*exp(-t*(k2 + k3))/k2, -(C2*k2*exp(t*(k2 + k3)) - C3*k3*(k2 + k3))*exp(-t*(k2 + k3))/k2), True, True] indicating that the 2nd and 3rd equations are satisfied, but the 1st is not. The second prints [Eq(C3*k2*exp(-t*(k2 + k3)), C2 + C3*k2*exp(-k2*t)*exp(-k3*t)), True, True] So once again, the first equation fails to be solved correctly, even though it's a different one now. Giving the initial conditions as ics={x(0):0, y(0):1,...etc doesn't work or influence the answer. The support for initial conditions was added after SymPy 1.1.1 was released. They work in development version and will work in SymPy 1.2+.
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/48895507
accepted answer of: http://stackoverflow.com/q/48895397
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84824473
has body: With einsum the calculation writes itself: np.einsum('ip,iq-&gt;ipq', a,b) That expression also makes it clear that there's no summation - just products. This is a kind of outer product, not an inner or matrix one. In which case tensordot won't help. But broadcasting should: a[:,:,None] * b[:,None,:] (Sometimes I have to reverse the order of the None. It helps to use p and q that are different to check that.) You didn't provide a MCVE to check my answer against.
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48895397
type: Answer

http://stackoverflow.com/comment/84905755
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48949054
has text: That's a shot in the dark, but I'm wondering if `pip install --upgrade setuptools` will help. Judging from the code, current setuptools shouldn't throw this exception on this line.
type: Comment

http://stackoverflow.com/q/48925332
has comment: http://stackoverflow.com/comment/84858010
type: Question
tagged with: pipeline
score: 0
has comment: http://stackoverflow.com/comment/84857197
has comment: http://stackoverflow.com/comment/84973726
tagged with: imputation
has comment: http://stackoverflow.com/comment/84856921
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84865718
answer count: 0
has body: I analysing the gapminder dataset [1] using a pipeline in Python but for some reason the imputer does not replace the nan values. According to the documentation ("For missing values encoded as np.nan, use the string value “NaN”.") I should do it like below but the code crashes with "ValueError: Input contains NaN" in the line "gm_cv.fit(X_train, y_train)". But gm_cv was created based on the pipeline and the pipeline contains the imputation which should remove the nans. Why does this not work? import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.preprocessing import Imputer from sklearn.pipeline import Pipeline from sklearn.linear_model import ElasticNet from sklearn.preprocessing import StandardScaler from sklearn.model_selection import GridSearchCV fn = 'gapminder.csv' df = pd.read_csv(fn, delimiter=',') # replace empty strings with numpy nans df.replace('', np.nan, inplace=True) df.replace(' ', np.nan, inplace=True) targetVariable = 'lifeexpectancy' X = df.drop([targetVariable, 'country'], axis=1).values y = df[targetVariable] steps = [('imputation', Imputer(missing_values='NaN', strategy='mean', axis=0)), ('scaler', StandardScaler()), ('elasticnet', ElasticNet())] pipeline = Pipeline(steps) # Specify the hyperparameter space parameters = {'elasticnet__l1_ratio': np.linspace(0,1,30)} # Create train and test sets X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.4, random_state=98) # Create the GridSearchCrossValidation object gm_cv = GridSearchCV(pipeline, parameters, cv=3) # Fit to the training set gm_cv.fit(X_train, y_train) # results: r2 = gm_cv.score(X_test, y_test) print("Tuned ElasticNet Alpha: {}".format(gm_cv.best_params_)) print("Tuned ElasticNet R squared: {}".format(r2)) stack trace of full error: python.exe pipline_and_classification_II.py Traceback (most recent call last): File "pipline_and_classification_II.py", line 55, in &lt;module&gt; gm_cv.fit(X_train, y_train) File "lib\site…
has title: python pipeline does not execute imputer
has comment: http://stackoverflow.com/comment/84858095

http://stackoverflow.com/tag/xml
tags question: http://stackoverflow.com/q/48896070
tags question: http://stackoverflow.com/q/48890861
tags question: http://stackoverflow.com/q/48941023
tags question: http://stackoverflow.com/q/48953277
tags question: http://stackoverflow.com/q/48852898
type: Tag
tags question: http://stackoverflow.com/q/48874148
tags question: http://stackoverflow.com/q/48813109
tags question: http://stackoverflow.com/q/48829205
tags question: http://stackoverflow.com/q/48897016
tags question: http://stackoverflow.com/q/48904567
tags question: http://stackoverflow.com/q/48826469
tags question: http://stackoverflow.com/q/48959559
tags question: http://stackoverflow.com/q/48941032
tags question: http://stackoverflow.com/q/48899897
tags question: http://stackoverflow.com/q/48908045
tag name: xml
tags question: http://stackoverflow.com/q/48957632
tags question: http://stackoverflow.com/q/48928973
tags question: http://stackoverflow.com/q/48817162
tags question: http://stackoverflow.com/q/48957960
tags question: http://stackoverflow.com/q/48847177
tags question: http://stackoverflow.com/q/48884184
tags question: http://stackoverflow.com/q/48804937
tags question: http://stackoverflow.com/q/48901338

http://stackoverflow.com/comment/84785015
has text: @dccdany you are half right the selection is calculated when rendering the view exactly not when the module is lawed. use many2one field for this kind of situation.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48883694

http://stackoverflow.com/comment/84704712
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48850397
has text: No worries, I put the (IMO) most important bit back.
score: 0

http://stackoverflow.com/a/48932023
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Hopefully, as discussed in the comments, this works for you: parallel -k --dry-run python3 test.py --x "a b" --y "2 3" --z ::: 10 20 30 40 Sample Output python3 test.py --x a b --y 2 3 --z 10 python3 test.py --x a b --y 2 3 --z 20 python3 test.py --x a b --y 2 3 --z 30 python3 test.py --x a b --y 2 3 --z 40 Remove the --dry-run part if the command looks good, then run it again for real.
upvote count: 4
score: 4
answers question: http://stackoverflow.com/q/48910369
accepted answer of: http://stackoverflow.com/q/48910369

http://stackoverflow.com/comment/84877519
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48935441
has text: After the loop, `actual_node` must be `None`. Therefore, it can't have a `next_node` attribute.

http://stackoverflow.com/q/48904801
possible better answer: http://stackoverflow.com/a/48905271
has body: EDIT: management commands. Not comments. Auto correct.. I was using django 1.7.final.0 for a while, but am now trying to upgrade to 1.8 (..and eventually to the newest version). When running manage.py help, the commands I see are only the base commands. I've added a print statement, to see if INSTALLED_APPS works and it does. import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") from config import settings print(settings.INSTALLED_APPS) # prints apps like django-extensions that have commands. from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) There are no errors, but it simply doesn't list the other commands. If I try to run a command, like ./manage.py shell_plus it returns Unknown Command as can be seen below. Note the print statement, indicating that INSTALLED_APPS can be read. (venv) rootadmin@annotatie01:/data_nfs/opensurfaces2/server$ python manage.py shell_plus ('admin_tools', 'admin_tools.theming', 'admin_tools.menu', 'admin_tools.dashboard', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'django.contrib.admindocs', 'django.contrib.humanize', 'gunicorn', 'storages', 'queued_storage', 'django_extensions', 'account', 'django_forms_bootstrap', 'imagekit', 'compressor', 'endless_pagination', 'cacheback', 'captcha', 'mptt', 'debug_toolbar', 'cache_panel', 'memcache_status', 'common', 'home', 'accounts', 'analytics', 'licenses', 'poly', 'mturk', 'categories', 'photos', 'shapes', 'bsdfs', 'normals', 'intrinsic', 'points', 'boxes', 'matclass', 'paintings', 'binaryQuestion') Unknown command: 'shell_plus' Type 'manage.py help' for usage. (venv) rootadmin@annotatie01:/data
has answer: http://stackoverflow.com/a/48905271
type: Question
answer count: 2
tagged with: django-1.8
score: 0
tagged with: python
linked to: http://stackoverflow.com/q/31107287
has title: Django management comments not loaded, while settings.INSTALLED_APPS are configured
tagged with: django
has answer: http://stackoverflow.com/a/48907610
accepted answer: http://stackoverflow.com/a/48907610
type: AnsweredQuestion

http://stackoverflow.com/q/48918303
upvote count: 0
has body: I am stumped with how to write this in python code. Can anyone help? ***For hours over 60, you need to calculate the overage above 60 to multiply at the 2x pay rate + the hours between 40 and 60 to be compensated at 1.5x rate + the first 40 hours at the regular rate.****
has answer: http://stackoverflow.com/a/48918394
type: Question
has title: Python payroll calculator
answer count: 1
tagged with: calculator
favorite count: 0
type: UnansweredQuestion
score: -4
tagged with: python
downvote count: 4

http://stackoverflow.com/comment/84678600
type: AnswerComment
score: 0
type: Comment
has text: what i would do is paste that line into a separate file, read it into pandas and see what it gives you.
comment on: http://stackoverflow.com/a/48836651

http://stackoverflow.com/q/48864890
type: Question
tagged with: numpy
tagged with: arrays
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48865163
favorite count: 0
has body: Right now I have this numpy array: [[ 0 9 18 27 36 45 54 63 72 81 90 99] [ 108 117 126 135 144 153 162 171 180 189 198 207] [ 216 225 234 243 252 261 270 279 288 297 306 315] [ 324 333 342 351 360 369 378 387 396 405 414 423] [ 432 441 450 459 468 477 486 495 504 513 522 531] [ 540 549 558 567 576 585 594 603 612 621 630 639] [ 648 657 666 675 684 693 702 711 720 729 738 747] [ 756 765 774 783 792 801 810 819 828 837 846 855] [ 864 873 882 891 900 909 918 927 936 945 954 963] [ 972 981 990 999 1008 1017 1026 1035 1044 1053 1062 1071] [1080 1089 1098 1107 1116 1125 1134 1143 1152 1161 1170 1179] [1188 1197 1206 1215 1224 1233 1242 1251 1260 1269 1278 1287]] What I want to do is from every column, the first element needs + 0, the second element +1, the third +2, the fourth +3 etc etc. So the first two lines needs to look like this: [[ 0 10 20 30 40 50 60 70 80 90 100 110] [ 108 118 128 138 148 158 168 178 188 198 208 218] I have already the following code: nw = [x for x in np.hsplit(array, array.shape[1])] column = 0 upd = [] for x in nw: x += column column += 1 upd.append(x) nw2 = np.reshape(upd,(12,12)) nw3 = np.hsplit(nw2,12) nw4 = np.reshape(nw3,(12,12)) nw4 Which gives exactly the output that I want. But here is the thing, I want to do it more efficiently in (I prefer) 1 line of code and without the for-loop. But I'm stuck at how I can do that. So I hoped that someone here could help me out!
has title: How to get the same array output without the for loop Python
tagged with: python
has answer: http://stackoverflow.com/a/48865163
type: AnsweredQuestion
score: 3
upvote count: 3

http://stackoverflow.com/a/48882065
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48881953
has body: you have a list of lists inside your tuple, but each list contains one element. Rebuild the list using a list comprehension, taking the one and only element of the list: L = ('AAA', '193.0', 'GGG', 'BBB', '196.33333333333334', 'TTT', 'CCC', '18.666666666666668', 'AAA') L = [x[0] for x in L] print(L) result: [['AAA', '193.0', 'GGG'], ['BBB', '196.33333333333334', 'TTT'], ['CCC', '18.666666666666668', 'AAA']]
downvote count: 0

http://stackoverflow.com/q/48812282
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48820253
tagged with: python
has body: I am trying to extract the most recent headlines from the following news site: http://news.sina.com.cn/hotnews/ #save ids of relevant buttons that need to be clicked on the site buttons_ids = ['Tab21' , 'Tab22', 'Tab32'] #save ids of relevant subsections con_ids = ['Con11'] #start webdriver, go to site, hover over buttons driver = webdriver.Chrome() driver.get("http://news.sina.com.cn/hotnews/") time.sleep(3) for button_id in buttons_ids: button = driver.find_element_by_id(button_id) ActionChains(driver).move_to_element(button).perform() Then I iterate through each section that I am interested in and within each section through all the headlines which are rows in an HTML table. However, on every iteration, it returns the first element for con_id in con_ids: for news_id in range(2,10): print(news_id) headline = driver.find_element_by_xpath("//div[@id='"+con_id+"']/table/tbody/tr["+str(news_id)+"]") text = headline.find_element_by_xpath("//td[2]/a") print(text.get_attribute("innerText")) print(text.get_attribute("href")) com_no = comment.find_element_by_xpath("//td[3]/a") print(com_no.get_attribute("innerText")) I also tried the following approach by essentially saving the table as a list and then iterating through the rows: for con_id in con_ids: table = driver.find_elements_by_xpath("//div[@id='"+con_id+"']/table/tbody/tr") for headline in table: text = headline.find_element_by_xpath("//td[2]/a") print(text.get_attribute("innerText")) print(text.get_attribute("href")) com_no = comment.find_element_by_xpath("//td[3]/a") print(com_no.get_attribute("innerText")) In the second case I get exactly the number of headlines in the section, so it apparently correctly picks up the number of rows. However, it is still only returning the first row on all iterations. Where am I going wrong? I know a similar question has been asked here: Selenium Python iterate over a table of rows it is stopping at the first row but I am still unable to figure out where I am going wrong.
linked to: http://stackoverflow.com/q/35581254
has title: Python Selenium only getting first row when iterating over table
answer count: 3
tagged with: selenium
upvote count: 1
has answer: http://stackoverflow.com/a/48816012
possible better answer: http://stackoverflow.com/a/48813868
has answer: http://stackoverflow.com/a/48820253
tagged with: html-table
has answer: http://stackoverflow.com/a/48813868
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/48944783
type: Question
has comment: http://stackoverflow.com/comment/84896346
score: 3
has answer: http://stackoverflow.com/a/48944916
accepted answer: http://stackoverflow.com/a/48944916
tagged with: numpy
upvote count: 3
has body: I have this basic example to understand the numpy append method. distances=[] for i in range (8): distances = np.append(distances, (i)) print(distances) distances=[] for i in range (8): distances.append(i) print(distances) The output gives me 2 arrays but are in different format (or what I understand of different format). [ 0. 1. 2. 3. 4. 5. 6. 7.] [0, 1, 2, 3, 4, 5, 6, 7] What is the exact different of both arrays and why is the output different?
possible better answer: http://stackoverflow.com/a/48944951
downvote count: 0
has comment: http://stackoverflow.com/comment/84896388
favorite count: 0
answer count: 3
has answer: http://stackoverflow.com/a/48945128
tagged with: python
has title: Differences between using numpy append or array append - Python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84896215
has comment: http://stackoverflow.com/comment/84896491
has answer: http://stackoverflow.com/a/48944951
has comment: http://stackoverflow.com/comment/84914112

http://stackoverflow.com/q/48866543
favorite count: 0
has body: I have a problem with loading the Python library I created by creating a Python API for a C++ project. When I load it into Python I get an error with Symbol not found:... Expected in: flat namespace... EDIT: I have given the solution to my problem below.
type: UnansweredQuestion
tagged with: python
tagged with: c++
upvote count: 2
score: 1
has comment: http://stackoverflow.com/comment/84738814
downvote count: 1
type: Question
tagged with: swig
has title: SWIG for C++, Symbol not found: Expected in: flat namespace
has answer: http://stackoverflow.com/a/48866544
has comment: http://stackoverflow.com/comment/84736164
answer count: 1

http://stackoverflow.com/comment/84800366
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48897354
score: 1
has text: In reshape function only get the whole image shaped.But I want to access the image data block by block.How sholud I do this?EX: It is needed to seperate whole image as seperate 8*8 pixel blocks.

http://stackoverflow.com/comment/85482295
type: AnswerComment
has text: @foraidt Glad to hear, there are many benefits to using pytest. Seems like this should be the accepted answer then.
type: Comment
comment on: http://stackoverflow.com/a/48958291
score: 0

http://stackoverflow.com/q/48846365
tagged with: django
has title: How to convert an existing Django app to run in a virtualenv?
has body: There are so many questions about this, and so many tries I've made and probably bungled... But let me stick to the real problem: I have a fledgling Django app that I want to insulate from future changes to support software. I think putting in under a virtual environment is the answer. I'd like guidance, even just a pointer to the right Howto (one about migrating, not a fresh install). My environment is Ubuntu 16.04.3 LTS, apache2, python3.5 and django 2.0. I'll be upgrading to the next LTS, which is why I want to insulate this app from changes. Complicating matters is the fact that python2 and python 3 are both here, and pyhton2 is the default (what you get when you just call for "python". That makes things weird, for instance, because pip3 is uses the default python, so the output of 'pip3 freeze' is very different from what I get when I run it under python3, and I don't know the details of why. What has failed in the past is my attempts to do it following guidance aimed at a freshly installed OS. What's more, probably because I did something wrong, pip3 lives in my $HOME/.local/bin/pip3. I don't know how to undo this.
tagged with: virtualenvwrapper
has comment: http://stackoverflow.com/comment/88014443
type: Question
upvote count: 4
downvote count: 0
answer count: 1
score: 4
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48846418
type: UnansweredQuestion

http://stackoverflow.com/comment/84676800
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48835887
type: Comment
has text: @AGNGazer Python 2 example though right? `filter` doesn't return a list in Python 3.

http://stackoverflow.com/a/48809540
upvote count: 24
accepted answer of: http://stackoverflow.com/q/48809458
has body: I would say that the package is still seen as imported. So performing import math again just redeclares the name, but with old contents. You could use reload to make sure your module is whole again, except that some versions of python require to remove the entry in sys.modules as well, which makes the use of reload redundant: import math del math.cos del math sys.modules.pop("math") # remove from loaded modules import math print(math.cos(0)) # 1.0 (this difference between various python versions, reload and import are discussed in a follow-up question: Should importlib.reload restore a deleted attribute in Python 3.6?)
answers question: http://stackoverflow.com/q/48809458
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84622658
has comment: http://stackoverflow.com/comment/84628783
score: 23
downvote count: 1

http://stackoverflow.com/comment/84638203
has text: But in reality the REST API isn't capable of doing 3 inputs in one call. That's why I still need to do a call per key.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48817008
score: 0

http://stackoverflow.com/q/48933052
has comment: http://stackoverflow.com/comment/84884520
has answer: http://stackoverflow.com/a/48934265
answer count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48934265
has body: I create a graph using networkx and i want to add a 'class' attribute in every edge to know if is forward,back,cross or tree. As a next step i tried to implement the following pseudocode in python but when i print the graph edges, the output has empty 'class' attribute for every edge. DFS (V, E) 1. for each vertex u in V[G] 2. do color[u] ← WHITE 3. π[u] ← NIL 4. time ← 0 5. for each vertex u in V[G] 6. do if color[u] ← WHITE 7. then DFS-Visit(u) ▷ build a new DFS-tree from u DFS-Visit(u) ▷ with edge classification. G must be a directed graph 1. color[u] ← GRAY 2. time ← time + 1 3. d[u] ← time 4. for each vertex v adjacent to u 5. do if color[v] ← BLACK 6. then if d[u] &lt; d[v] 7. then Classify (u, v) as a forward edge 8. else Classify (u, v) as a cross edge 9. if color[v] ← GRAY 10. then Classify (u, v) as a back edge 11. if color[v] ← WHITE 12. then π[v] ← u 13. Classify (u, v) as a tree edge 14. DFS-Visit(v) 15. color[u] ← BLACK 16. time ← time + 1 17. f[u] ← time Here is my code: def dfs_visit(u): color[u] = 'gray' global time time = time + 1 d[u] = time for v in G.neighbors(u): if color[v] == 'black': if d[u] &lt; d[v]: G.edges[u,v]['class'] = 'forward' else: G.edges[u,v]['class'] ='cross' if color[v] == 'gray': G.edges[u, v]['class'] = 'back' if color[v] == 'white': p[v] = u G.edges[u, v]['class'] = 'tree' dfs_visit(v) color[u] = 'black' time = time + 1 f[u] = time for u in G.nodes(): color[u] = 'white' time = 0 for u in G.nodes(): if color[u] == 'white': dfs_visit(u) print(G.edges(data=True)) If i print all the graph edges the i take the following output: [(1, 2, {'class': ''}), (1, 6, {'class': ''}), (2, 3, {'class': ''}), (6, 3, {'class': ''}), (3, 4, {'class': ''}), (3, 1, {'class': 'cross'}), (3, 7, {'class': ''}), (4, 5, {'class': ''}), (4, 7, {'class': ''})] The class attribute of every edge is empty. How can i fix it?
tagged with: breadth-first-search
tagged with: networkx
has title: Edge classification using DFS
type: Question
tagged with: graph-theory
tagged with: algorithm
score: 0

http://stackoverflow.com/q/48902767
has body: I tried to predict label of my newly added data through SGDClassifer.partial_fit as below: from sklearn import neighbors, linear_model import numpy as np def train_predict(): X = [[1, 1], [2, 2.5], [2, 6.8], [4, 7]] y = [1, 2, 3, 4] sgd_clf = linear_model.SGDClassifier(loss="log") sgd_clf.fit(X, y) X1 = [[6,9]] y1=[5] f1 = sgd_clf.partial_fit(X1,y1) f1.predict([[6,9]]) return f1 if __name__ == "__main__": clf = train_predict() fit perfectly predicts the labels. However, prediction with partial fit results in error as: in compute_class_weight raise ValueError("classes should include all valid labels that can be in y") similar to Sklearn SGDC partial_fit ValueError: classes should include all valid labels that can be in y, I read partial_fit manual, http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.SGDClassifier.html#sklearn.linear_model.SGDClassifier.partial_fit But i am still not able to figure out how to set the parameters of partial_fit so that i can be able to predict the data added on the fly. Any references or ideas ?
has title: SGDClassifier.partial_fit returns error of "classes should include labels"
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: scikit-learn
favorite count: 0
accepted answer: http://stackoverflow.com/a/48902986
type: Question
upvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/44075801
tagged with: machine-learning
answer count: 1
has answer: http://stackoverflow.com/a/48902986

http://stackoverflow.com/comment/84892337
has text: Many "mutator" methods for Python objects (such as lists and sets) do NOT return a reference to the object. This is an intentional implementation decision to discourage confusing between methods which mutate (modify) an object and those which return contents. It all started with list.sort() vs. sorted(some_list). Thus the expression fs.add(xxx) evaluates to None while modify the contents of fs.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48942762
type: Comment

http://stackoverflow.com/a/48817109
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48816693
has comment: http://stackoverflow.com/comment/84638799
has body: from random import choice from string import digits from textwrap import dedent def get_four_digit_number(msg): while True: try: num = int(input(msg)) except ValueError: pass else: if 1000 &lt;= num &lt;= 9999: return str(num) if __name__ == '__main__': secret_code = ''.join(choice(digits) for _ in range(4)) while True: guess = get_four_digit_number('Enter your 4-digit guess: ') correct = [] incorrect = [] for a, b in zip(guess, secret_code): if a == b: correct.append('^') incorrect.append(' ') else: correct.append(' ') incorrect.append('!') print(dedent(""" {} &lt;-- Incorrect Guess: {} {} &lt;-- Correct """.format(''.join(incorrect), guess, ''.join(correct)))) if correct == list('^^^^'): print('Nice guess! The secret code was {}'.format(secret_code)) break Output example: Enter your 4-digit guess: 1111 !!!! &lt;-- Incorrect Guess: 1111 &lt;-- Correct Enter your 4-digit guess: 2222 !!!! &lt;-- Incorrect Guess: 2222 &lt;-- Correct Enter your 4-digit guess: 3333 !! &lt;-- Incorrect Guess: 3333 ^ ^ &lt;-- Correct Enter your 4-digit guess: 3443 !! &lt;-- Incorrect Guess: 3443 ^ ^ &lt;-- Correct Enter your 4-digit guess: 3553 !! &lt;-- Incorrect Guess: 3553 ^ ^ &lt;-- Correct Enter your 4-digit guess: 3663 !! &lt;-- Incorrect Guess: 3663 ^ ^ &lt;-- Correct Enter your 4-digit guess: 3773 !! &lt;-- Incorrect Guess: 3773 ^ ^ &lt;-- Correct Enter your 4-digit guess: 3883 !! &lt;-- Incorrect Guess: 3883 ^ ^ &lt;-- Correct Enter your 4-digit guess: 3993 ! &lt;-- Incorrect Guess: 3993 ^^ ^ &lt;-- Correct Enter your 4-digit guess: 3903 &lt;-- Incorrect Guess: 3903 ^^^^ &lt;-- Correct Nice guess! The secret code was 3903
answers question: http://stackoverflow.com/q/48816693
type: Answer
has comment: http://stackoverflow.com/comment/84638965
has comment: http://stackoverflow.com/comment/84638899
has comment: http://stackoverflow.com/comment/84639021
has comment: http://stackoverflow.com/comment/84638833
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84639098
has comment: http://stackoverflow.com/comment/84638859
upvote count: 2

http://stackoverflow.com/a/48924184
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48923565
answers question: http://stackoverflow.com/q/48923565
type: Answer
upvote count: 2
has body: This one works fast enough for me. import numpy import math a = numpy.random.rand(100, 77) a = numpy.swapaxes(a, 0, 1) a = numpy.array([math.fsum(row) for row in a]) Hopefully it's the axis you are looking for (returns 77 sums).
score: 2
has comment: http://stackoverflow.com/comment/84876458

text-files
tags question: http://stackoverflow.com/q/48881883
tag name: text-files
type: Tag
tags question: http://stackoverflow.com/q/48829584

http://stackoverflow.com/a/48950889
upvote count: 15
has body: You have a multi-channel 32-bit TIFF image, and Pillow doesn't yet support that format. See issue #1888: Pillow (and PIL) is currently able to open 8 bit per channel multi-channel images (such as RGB) but is able to open higher bit depth images (e.g. I16, I32, or Float32 images) if they are single channel (e.g., grayscale). [...] Requirements We should be able to support common GIS formats as well as high bit depth RGB(A) images. At least 4 channels, but potentially more (see #1839) Different pixel formats, including I16, I32, and Float. I determined this by using the TIFF plugin image reader directly, with debug mode enabled: from PIL import TiffImagePlugin TiffImagePlugin.DEBUG = True with open(image_path, 'rb') as f: TiffImagePlugin.TiffImageFile(f) which includes the output: tag: BitsPerSample (258) - type: short (3) Tag Location: 46 - Data Location: 218 - value: (32, 32, 32) (full debug output below) You can use the Python GDAL bindings to read this format. You can also use the gdal_translate command line utility to convert your files to a format that Pillow can handle; for multiband, you'd have to go down to 8 bits, or move to grayscale. For example, to translate your input file to PNG, you can use: gdal_translate -of PNG rgb_CGI.tiff rgb_CGI.png after which Pillow can open the PNG file. Full debug output from Pillow's TIFF plugin: &gt;&gt;&gt; from PIL import TiffImagePlugin &gt;&gt;&gt; TiffImagePlugin.DEBUG = True &gt;&gt;&gt; with open(image_path, 'rb') as f: ... TiffImagePlugin.TiffImageFile(f) ... *** TiffImageFile._open *** - __first: 8 - ifh: b'II*\x00\x08\x00\x00\x00' Seeking to frame 0, on frame -1, __next 8, location: 8 Loading tags, location: 8 tag: ImageWidth (256) - type: short (3) - value: 2924 tag: ImageLength (257) - type: short (3) - value: 2088 tag: BitsPerSample (258) - type: short (3) Tag Location: 46 - Data Location: 218 - value: (32, 32, 32) tag: Compression (259) - type: short (3) - value: 1 tag: PhotometricInterpretation (262) - type: …
has comment: http://stackoverflow.com/comment/88450846
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48944819
answers question: http://stackoverflow.com/q/48944819
has comment: http://stackoverflow.com/comment/88447776
score: 15
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/84680372
comment on: http://stackoverflow.com/q/48817972
has text: @questnofinterest I think what they have unclear and outdated docs. I stuck with that stuff 1-2 days before also. Yes, you need install pinax because only root project has template folder.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84641074
has text: Ok, done, see last paragraph of my answer to the linked question. I guess we can again close as dupe. Just mind that you have to set the aspect **after** drawing the `fill_between` curve, else you get that small line as shown in your last image here.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48818535

http://stackoverflow.com/q/48891679
score: 1
has body: We are currently trying to process user input and checking if user has entered a food item using elastic search. With elastic search we are able to get results for wide range of terms: Garlic , Garlic Extract etc... How should we handle use cases E.g. Blueberry Dish-washing soap Or Apple based liquid soap . How do we omit these searches ? As I search Blueberry Dish-washing soap I still get search results related to Blueberry
favorite count: 0
type: Question
tagged with: elasticsearch
accepted answer: http://stackoverflow.com/a/48898306
tagged with: python
tagged with: nlp
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48898306
has title: How to filter out elastic searches for invalid inputs
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/84691356
has text: @paddy, can you provide a reproducible data set?
type: AnswerComment
comment on: http://stackoverflow.com/a/48842891
score: 0
type: Comment

http://stackoverflow.com/q/48890397
type: UnansweredQuestion
tagged with: python
has title: How to replace first occurrence of character in a string?
duplicate of: http://stackoverflow.com/q/6005891
has answer: http://stackoverflow.com/a/48890422
score: 1
linked to: http://stackoverflow.com/q/6005891
has body: Given string as: s = "Python is programming language" In this, I want to replace 2nd occurrence of 'n' with any character, let's say 'o'. The expected string would be: "Python is programmiog language" How to do this in python? Can I do it using replace function only? or any other way to do that?
type: Question
upvote count: 3
downvote count: 2
answer count: 1
tagged with: string
favorite count: 0

http://stackoverflow.com/q/48946238
tagged with: dataframe
has title: Sorting pandas.DataFrame in python sorted() function manner
tagged with: pandas
answer count: 1
downvote count: 0
tagged with: sorting
favorite count: 0
linked to: http://stackoverflow.com/q/16486252
has answer: http://stackoverflow.com/a/48946845
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/17901218
score: 2
upvote count: 2
has body: Description Long story short, I need a way to sort a DataFrame by a specific column, given a specific function which is analagous to usage of "key" parameter in python built-in sorted() function. Yet there's no such "key" parameter in pd.DataFrame.sort_value() function. The approach used for now I have to create a new column to store the "scores" of a specific row, and delete it in the end. The problem of this approach is that the necessity to generate a column name which does not exists in the DataFrame, and it could be more troublesome when it comes to sorting by multiple columns. I wonder if there's a more suitable way for such purpose, in which there's no need to come up with a new column name, just like using a sorted() function and specifying parameter "key" in it. Update: I changed my implementation by using a new object instead of generating a new string beyond those in the columns to avoid collision, as shown in the code below. Code Here goes the example code. In this sample the DataFrame is needed to be sort according to the length of the data in row "snippet". Please don't make additional assumptions on the type of the objects in each rows of the specific column. The only thing given is the column itself and a function object/lambda expression (in this example: len) that takes each object in the column as input and produce a value, which is used for comparison. def sort_table_by_key(self, ascending=True, key=len): """ Sort the table inplace. """ # column_tmp = "".join(self._table.columns) column_tmp = object() # Create a new object to avoid column name collision. # Calculate the scores of the objects. self._table[column_tmp] = self._table["snippet"].apply(key) self._table.sort_values(by=column_tmp, ascending=ascending, inplace=True) del self._table[column_tmp]
type: Question
has comment: http://stackoverflow.com/comment/114099613

http://stackoverflow.com/a/48822043
score: 0
has comment: http://stackoverflow.com/comment/84651116
type: Answer
has comment: http://stackoverflow.com/comment/84648779
has comment: http://stackoverflow.com/comment/84650171
has body: As per the HTML you have provided to print the text General (8) you have to extract it from the &lt;div class="extend_clickable" tag, as the text is not within &lt;input&gt; tag and you can use the following code block using Python's splitlines() method as follows : all_text = driver.find_element_by_xpath("//li[@role='checkbox']/div[@class='extend_clickable']").get_attribute("innerHTML") myText = all_text.splitlines() print(myText[1]) Console Output : General (8) Update As per @Andersson's counter question/comment the following screenshot should address and answer all the queries.
has comment: http://stackoverflow.com/comment/84650466
has comment: http://stackoverflow.com/comment/84650040
has comment: http://stackoverflow.com/comment/84650807
answers question: http://stackoverflow.com/q/48820860
has comment: http://stackoverflow.com/comment/84650290
has comment: http://stackoverflow.com/comment/84650061
has comment: http://stackoverflow.com/comment/84650226
has comment: http://stackoverflow.com/comment/84649666
has comment: http://stackoverflow.com/comment/84650933
has comment: http://stackoverflow.com/comment/84648922

http://stackoverflow.com/a/48887502
has body: l[4:7] is a string of length 3. So suppose l is "1234POW", then l[4:7] is "POW". Your long string "ABCDEFGHIJKLMNOPQRSTUVWXYZ" does not contain the substring "POW". If you want to check that every one of a sequence of characters are in your long string, you can use the function all. if all(ch in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" for ch in l[4:7]): ... or even just if l[4:7].isupper(): You got away with l[0:4] in "1234567890" because "1234" is an exact substring of "1234567890". If you had different numbers, it would not have worked, for the same reason as above. Instead you could use: if l[:4].isdigit() and l[4:7].isupper(): On the other hand, your upper condition if l[0] and l[1] and l[2] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" is also wrong. Python understands this as if (l[0]) and (l[1]) and (l[2] in "ABCDEFGHIJKLMNOPQRSTUVWXYZ") i.e. if l[0] is not zero and l[1] is not zero and l[2] is in "ABCDEFGHIJKLMNOPQRSTUVWXYZ" So your upper condition should also be changed: e.g. if l[:3].isupper() and l[3:6].isdigit(): ...
downvote count: 0
has comment: http://stackoverflow.com/comment/84780191
type: Answer
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/48887424

http://stackoverflow.com/q/48853947
tagged with: unit-testing
has title: PyCharm "No tests were found"
tagged with: syntax
has comment: http://stackoverflow.com/comment/84711290
accepted answer: http://stackoverflow.com/a/48853990
score: 2
type: AnsweredQuestion
downvote count: 0
has body: This is my main code def return_first_name(first_name): return first_name This is the unit test code import unittest import profile class TestFunctionFirstName(unittest.TestCase): def first_name(self): answer = profile.return_first_name("jakub") self.assertEqual(answer, "jakub") I really don't understand why it is not finding any unit tests. I have been sitting here for hours messing with it.
favorite count: 0
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84711321
tagged with: pycharm
upvote count: 2
has answer: http://stackoverflow.com/a/48853990
answer count: 1

http://stackoverflow.com/comment/84727468
has text: Made some minor edits. Feel free to revert if unhappy.
comment on: http://stackoverflow.com/a/48861955
type: AnswerComment
type: Comment
score: 1

http://stackoverflow.com/q/48806728
tagged with: pascals-triangle
upvote count: 1
tagged with: python
tagged with: recursion
score: 1
has comment: http://stackoverflow.com/comment/84616177
has title: Pascal Triangles with Tuples in Recursion in Python
type: Question
has comment: http://stackoverflow.com/comment/84616547
downvote count: 0
has answer: http://stackoverflow.com/a/48806956
tagged with: tuples
has body: I am asked to write a recursion for Pascal's triangle, with tuples. This is my code: def pascal(n): if n == 1: return (1,) if n == 2: return ((1,),(1,1)) else: new_row = () for i in range(-1, n-1): if i == -1: new_row = new_row + (1,) elif i == n - 1: new_row = new_row + (1,) else: a = pascal(n-1)[n-2][i] + pascal(n-2)[n-1][i+1] new_row = new_row + (a,) return pascal(n-1), new_row I am getting an error that says tuple index out of range if I call pascal(3) or higher. This is the trace output: Traceback (most recent call last): File "tup.py", line 19, in <module> print pascal(3) File "tup.py", line 15, in pascal a = pascal(n-1)[n-2][i] + pascal(n-2)[n-1][i+1] IndexError: tuple index out of range How can I fix this error?
answer count: 1
has comment: http://stackoverflow.com/comment/84616324
has comment: http://stackoverflow.com/comment/84616233
favorite count: 0
has comment: http://stackoverflow.com/comment/84616217
type: UnansweredQuestion

http://stackoverflow.com/comment/84920630
type: Comment
type: QuestionComment
has text: over the first dimension
score: 0
comment on: http://stackoverflow.com/q/48955041

http://stackoverflow.com/comment/84631407
type: QuestionComment
has text: At first glance, you have parameters in `circuit` that are computed internally. These computed values override whatever you pass in. Post some data and your plot so far and someone may help you.
comment on: http://stackoverflow.com/q/48809610
score: 0
type: Comment

http://stackoverflow.com/q/48832024
has comment: http://stackoverflow.com/comment/84668552
score: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84668399
has comment: http://stackoverflow.com/comment/84668401
accepted answer: http://stackoverflow.com/a/48832511
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48832511
tagged with: python
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84668299
has title: python for loop changes type of list element
has body: I try to iterate over a list of objects (I called the class "Wort", the object has a position-attribute that matches the position in the temporary list in this case) and have a strange problem: When I access the second element, the class of the first element changes. At first I create the list like so: another_loop: w = Wort(zk, row.ts.index(zk), bibs.index(row.Bib)) templ.append(w) Then, when I iterate over the list "templ": print("templ is of type", type(templ)) for wobj in templ: if wobj.position &gt; 0: print("Element", wobj.position - 1, "of templ is of type", type(templ[wobj.position - 1])) else: print("Element", wobj.position, "of templ is of type", type(templ[wobj.position])) gives the following output: templ is of type &lt;class 'list'&gt; Element 0 of templ is of type &lt;class '__main__.Wort'&gt; Element 0 of templ is of type &lt;class 'method'&gt; So the first run of the for-loop is correct. The element at position 0 is of type &lt;class '__main__.Wort'&gt; But the second run shows a wrong type: &lt;class 'method'&gt; What am I doing wrong? Thanks for any hint!
has comment: http://stackoverflow.com/comment/84668490
has comment: http://stackoverflow.com/comment/84668452
type: Question
has comment: http://stackoverflow.com/comment/84668232
answer count: 1
has comment: http://stackoverflow.com/comment/84668260
has comment: http://stackoverflow.com/comment/84668868

http://stackoverflow.com/q/48941807
has answer: http://stackoverflow.com/a/48942043
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48941957
has answer: http://stackoverflow.com/a/48941957
accepted answer: http://stackoverflow.com/a/48942043
tagged with: numpy
tagged with: matplotlib
tagged with: pandas
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/23644020
has title: Converting Date to a number in python
has body: I have a date array date_array = array(['September 11, 2012', 'September 5, 2012']) I want to graph this date_array against a value, value_array =array([25,28]) using matplotlib So I want to convert the date_array to a number like date_as_number=array([20120812, 20120805]) so that I could plot the date_as_number as any other number against the value_array.
type: Question
has comment: http://stackoverflow.com/comment/84898417
tagged with: python

http://stackoverflow.com/a/48811916
has body: The problem is that you have created 2 Boards, and the one you see is the board that is under Screen and that has never been reset or linked with the keyboard, the solution is to create only one, reset and link with the keys in the constructor. *.kv #:set padding 20 &lt;Tile&gt;: canvas: Color: rgb: self.color BorderImage: pos: self.pos size: self.size source: 'cell.png' Label: pos: root.pos size: root.size bold: True color: root.number_color font_size: root.font_size text: str(root.number) &lt;Manager&gt;: id: screen_manager Screen: name: 'home' BoxLayout: orientation: 'vertical' Button: text: 'Play' halign: 'center' valign: 'middle' font_size: 100 text_size: self.size on_press: root.current = 'game' Button: text: 'Options' halign: 'center' valign: 'middle' font_size: 100 text_size: self.size Screen: name: 'game' Board: id: garme pos_hint: {'center_x': 0.5, 'center_y': 0.5} size_hint: (None, None) center: root.center size: [min(root.width, root.height) - 2 * padding] * 2 *.py [...] class Board(Widget): b = None moving = False def __init__(self, **kwargs): super(Board, self).__init__(**kwargs) self.resize() self.reset() Window.bind(on_key_down=self.on_key_down) [...] class GameApp(App): def build(self): return Manager(transition=WipeTransition()) if __name__ == '__main__': Window.clearcolor = get_color_from_hex('faf8ef') GameApp().run()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48810449
score: 0
accepted answer of: http://stackoverflow.com/q/48810449
type: Answer

http://stackoverflow.com/q/48958605
has comment: http://stackoverflow.com/comment/84943462
has comment: http://stackoverflow.com/comment/84943372
has body: I am trying to find the total depth of a BST in python(such that the root is at depth 1, its children depth 2, those children depth 3 etc) and the total is all of those depths added together. Ive been trying for about 5 hours straight now and cannot figure it out. Here is the code I have produced so far class BinaryTreeVertex: '''vertex controls for the BST''' def __init__(self, value): self.right = None self.left = None self.value = value ... def total_Depth(self): print ("val:", self.value) if self.left and self.right: return (self.left.total_Depth()) + 1 and (self.right.total_Depth()) + 1 elif self.left: return 1 + self.left.total_Depth() elif self.right: return 1 + self.right.total_Depth() else: return 1 ... tree = BinarySearchTree() arr = [6,10,20,8,3] for i in arr: tree.insert(i) tree.searchPath(20) print (tree.total_Depth()) #this calls the total_depth from vertex class The generated tree then looks like this. 6 # Depth 1 ___|___ 3 10 # Depth 2 ___|__ 8 20 # Depth 3 But when I run it it prints: val: 6 val: 3 val: 10 val: 8 val: 20 3 The 3 should actually be an 11 with this tree but I cannot figure out how to get it. Please help edit: To clarify, i am NOT looking for the max depth, I know how to find this. I need the total depth the way i explained, where the depth is the level of the tree. it would be 11 here as 6 would have depth 1, 3 and 10 depth 2, and 8 and 20 depth 3, where 1+2+2+3+3=11. I need it for a ratio regarding run times
has comment: http://stackoverflow.com/comment/84924107
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84925373
tagged with: binary-search-tree
has comment: http://stackoverflow.com/comment/84928519
has comment: http://stackoverflow.com/comment/84928570
has answer: http://stackoverflow.com/a/48959408
tagged with: python
has comment: http://stackoverflow.com/comment/84928589
tagged with: tree
has comment: http://stackoverflow.com/comment/84924228
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48959408
score: 1
has title: Total depth of a binary search tree in python
upvote count: 1
type: Question

http://stackoverflow.com/a/48945957
type: Answer
upvote count: 3
score: 3
accepted answer of: http://stackoverflow.com/q/48941388
has body: Links are good, but they have a tendency to break, so I'll try to include everything directly in the answer. We have a function like this (simplified): def make_key(args, kwds, kwd_mark = (object(),)): key = args if kwds: key += kwd_mark for item in kwds.items(): key += item ... return key The comment in there is rather descriptive: Make a cache key from &lt;...> positional and keyword arguments. The key is constructed in a way that is flat as possible rather than as a nested structure that would take more memory. Let's try a few sample runs: &gt;&gt;&gt; print(make_key((1, 2, 3), dict())) (1, 2, 3) &gt;&gt;&gt; print(make_key((1, 2, 3), dict(a='x', b='y'))) (1, 2, 3, &lt;object object at 0x7f6faf99d0c0&gt;, 'a', 'x', 'b', 'y') &gt;&gt;&gt; print(make_key((1, 2, 4), dict(b='y', a='x'))) (1, 2, 4, &lt;object object at 0x7f6faf99d0c0&gt;, 'b', 'y', 'a', 'x') The result is a hashable tuple that represents the parameters a user has called their user_function with. As you noted, kwd_mark is used as a sentinel value between args and kwargs, so that the following calls are cached separately: user_function(1, 2, 3, 'a', 'x') user_function(1, 2, 3, a='x') We could have used None as a delimiter, but what if someone calls a function with None as a parameter? While an object(), an object of the base class in Python, does not do much on its own, its unicity is useful. You cannot confuse a parameter with the delimiter if your delimiter is one-of-a-kind! And since this sentinel is created at the function definition time, it will stay the same through the run of a program (note that the results above refer to the same &lt;object object at 0x7f6faf99d0c0&gt;), so its hash will be the same. You might ask, why not make it kwd_mark=object()? I think the reason here is that it is only used to “append” it to a tuple, so otherwise you would have to make a new tuple every time (remember, tuples are immutable): def make_key(args, kwds, kwd_mark=object()): key = args if kwds: key += (kwd_mar…
answers question: http://stackoverflow.com/q/48941388
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48822211
downvote count: 0
has comment: http://stackoverflow.com/comment/112354377
accepted answer of: http://stackoverflow.com/q/48818716
has comment: http://stackoverflow.com/comment/112357187
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/112387437
answers question: http://stackoverflow.com/q/48818716
has body: You don't need threads to run multiple asyncio tasks - allowing multiple agents to share the same event loop is the strong suit of asyncio. You should be able to replace both thread-based classes with code like this: loop = asyncio.new_event_loop() loop.run_until_complete(websockets.serve(vlWebsocketServer, '192.168.1.3', 8777)) loop.run_until_complete(websockets.serve(irWebsocketServer, '192.168.1.3', 8555)) loop.run_forever() While it is not exactly wrong to mix threads and asyncio, doing so correctly requires care not to mix up the separate asyncio instances. The safe way to use threads for asyncio is with loop.run_in_executor(), which runs synchronous code in a separate thread without blocking the event loop, while returning an object awaitable from the loop. Note: the above code was written prior to the advent of asyncio.run() and manually spins the event loop. In Python 3.7 and later one would probably write something like: async def main(): server1 = await websockets.serve(vlWebsocketServer, '192.168.1.3', 8777) server2 = await websockets.serve(irWebsocketServer, '192.168.1.3', 8555) await asyncio.gather(server1.wait_closed(), server2.wait_closed()) asyncio.run(main())
has comment: http://stackoverflow.com/comment/112365397
type: Answer
has comment: http://stackoverflow.com/comment/112353570
upvote count: 10
has comment: http://stackoverflow.com/comment/112354064
score: 10

http://stackoverflow.com/comment/84849912
type: Comment
type: QuestionComment
has text: The condition of the loop `a==1` never becomes false because `a` never changes. If you want to end the loop, change `a`.
comment on: http://stackoverflow.com/q/48921736
score: 0

anagram
tags question: http://stackoverflow.com/q/48838729
tag name: anagram
type: Tag

http://stackoverflow.com/comment/84777808
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48886538
has text: Please state what error / issue your are getting specifically

http://stackoverflow.com/q/48896341
upvote count: 1
has comment: http://stackoverflow.com/comment/84798608
type: Question
has answer: http://stackoverflow.com/a/48896554
has comment: http://stackoverflow.com/comment/84798535
has comment: http://stackoverflow.com/comment/84798495
answer count: 2
has comment: http://stackoverflow.com/comment/84798421
has comment: http://stackoverflow.com/comment/84798385
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48914320
accepted answer: http://stackoverflow.com/a/48896554
has comment: http://stackoverflow.com/comment/84798369
tagged with: python
tagged with: bottle
has title: How to get the output into a json format?
possible better answer: http://stackoverflow.com/a/48914320
type: AnsweredQuestion
has body: Code::: from bottle import route, request, response, template,run import petl as etl @route('/loc') def abc(): response.headers['Access-Control-Allow-Origin']='*' response.headers['Content-type']='application/json' post = request.query.postcode locationTable = etl.fromcsv('clinic_locations.csv') abcd = etl.search(locationTable, 'Postcode', post) return template('{{postcode}}',postcode=abcd) Here is the csv File ,I want to get the result in json but i dont know to do i get it beacuse I am very new to petl and bottle framework When user enter the url on the browser e.g "localhost:8080/loc?postcode=4700" it will return the data regarding to that postal code but in csv format but i want to get the output in json format so i can user this data to find the address on the map Can any one help me to get the result Example: My desired ouput on browser after running localhost by bottle framework is: Updated But what I am getting is this:
score: 1
has comment: http://stackoverflow.com/comment/84798403
tagged with: http://stackoverflow.com/tag/json
has comment: http://stackoverflow.com/comment/84798498

matplotlib
tags question: http://stackoverflow.com/q/48948290
tags question: http://stackoverflow.com/q/48908828
tags question: http://stackoverflow.com/q/48937397
tags question: http://stackoverflow.com/q/48912258
tags question: http://stackoverflow.com/q/48819506
tags question: http://stackoverflow.com/q/48930008
tags question: http://stackoverflow.com/q/48826785
tags question: http://stackoverflow.com/q/48870161
tags question: http://stackoverflow.com/q/48888602
tags question: http://stackoverflow.com/q/48958216
tags question: http://stackoverflow.com/q/48947656
tags question: http://stackoverflow.com/q/48856030
tags question: http://stackoverflow.com/q/48886737
tags question: http://stackoverflow.com/q/48941807
tags question: http://stackoverflow.com/q/48824696
tags question: http://stackoverflow.com/q/48864668
tags question: http://stackoverflow.com/q/48884214
tags question: http://stackoverflow.com/q/48842143
tags question: http://stackoverflow.com/q/48872145
tags question: http://stackoverflow.com/q/48821940
tags question: http://stackoverflow.com/q/48847962
tag name: matplotlib
tags question: http://stackoverflow.com/q/48922328
tags question: http://stackoverflow.com/q/48846448
tags question: http://stackoverflow.com/q/48937176
tags question: http://stackoverflow.com/q/48873558
tags question: http://stackoverflow.com/q/48831890
tags question: http://stackoverflow.com/q/48860258
tags question: http://stackoverflow.com/q/48866770
tags question: http://stackoverflow.com/q/48884132
tags question: http://stackoverflow.com/q/48949864
tags question: http://stackoverflow.com/q/48853667
tags question: http://stackoverflow.com/q/48911643
tags question: http://stackoverflow.com/q/48884616
tags question: http://stackoverflow.com/q/48835854
tags question: http://stackoverflow.com/q/48876358
tags question: http://stackoverflow.com/q/48844600
tags question: http://stackoverflow.com/q/48913570
tags question: http://stackoverflow.com/q/48884280
tags question: http://stackoverflow.com/q/48833794
tags question: http://stackoverflow.com/q/48833850
tags question: http://stackoverflow.com/q/48849227
tags question: http://stackoverflow.com/q/48910557
tags question: http://stackoverflow.com/q/48958548
tags question: http://stackoverflow.com/q/48820958
tags question: http://stackoverflow.com/q/48814089
tags question: http://stackoverflow.com/q/48816711
tags question: http://stackoverflow.com/q/48962594
tags question: http://stackoverflow.com/q/48837476
tags question: http://stackoverflow.com/q/48842293
tags question: http://stackoverflow.com/q/48840360
tags question: http://stackoverflow.com/q/48917631
tags question: http://stackoverflow.com/q/48860428
tags question: http://stackoverflow.com/q/48951823
tags question: http://stackoverflow.com/q/48833211
tags question: http://stackoverflow.com/q/48855198
tags question: http://stackoverflow.com/q/48959754
tags question: http://stackoverflow.com/q/48846530
tags question: http://stackoverflow.com/q/48890525
tags question: http://stackoverflow.com/q/48808941
tags question: http://stackoverflow.com/q/48887134
tags question: http://stackoverflow.com/q/48832832
tags question: http://stackoverflow.com/q/48932345
tags question: http://stackoverflow.com/q/48830335
tags question: http://stackoverflow.com/q/48855752
tags question: http://stackoverflow.com/q/48868313
tags question: http://stackoverflow.com/q/48845686
tags question: http://stackoverflow.com/q/48910859
tags question: http://stackoverflow.com/q/48812041
tags question: http://stackoverflow.com/q/48911285
tags question: http://stackoverflow.com/q/48816785
tags question: http://stackoverflow.com/q/48898916
tags question: http://stackoverflow.com/q/48845981
tags question: http://stackoverflow.com/q/48897457
tags question: http://stackoverflow.com/q/48916579
tags question: http://stackoverflow.com/q/48851764
tags question: http://stackoverflow.com/q/48837841
tags question: http://stackoverflow.com/q/48813478
tags question: http://stackoverflow.com/q/48957501
tags question: http://stackoverflow.com/q/48922150

http://stackoverflow.com/comment/84727709
type: Comment
has text: such as ? @brunodesthuilliers
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48861909

http://stackoverflow.com/q/48861574
accepted answer: http://stackoverflow.com/a/48862058
type: Question
has comment: http://stackoverflow.com/comment/84726666
has body: I'm making an ASCII based python RPG for a project. The game features a grid system that allows for the players, enemies etc. to move around. Whenever the lines of code (below) are executed in the default python shell, the printed grid lines and cells can be altered by the user. Is there anyway that the looping and printing of the grid can be optimized so that the grid prints out instantly and the user cannot change the grid by typing on the keyboard? Code def gridPrint(): # print cell nums print("x 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ") length = len("x 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ") # access rows for x in grid: #print row nums print(str(x), end="") #print cells for y in grid[x]: for z in grid[x][y]: if (len(str(x)) == 1) and (y == 1): print(grid[x][y][z], end="") else: print(grid[x][y][z], end="") print("") print("*" * length) gridPrint() Also the project will be marked using the default python shell so no other shells or interpreters or IDEs will be used by the teacher. ¯(ツ)/¯ EDIT - This code is not quite what my grid looks like the actual project but it should help to illustrate my problem, which is the speed in which the grid prints out.
answer count: 1
tagged with: optimization
has comment: http://stackoverflow.com/comment/84726434
score: 0
has comment: http://stackoverflow.com/comment/84726688
tagged with: python
has comment: http://stackoverflow.com/comment/84726283
has comment: http://stackoverflow.com/comment/84726313
has title: When looping through a list and printing, user can type in the python shell
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48862058

http://stackoverflow.com/a/48962710
has body: I think I found my problem. My network shape was 3048, 40, 8, 4, 254. By necking down so small just prior to the output, it limited the decisions that could be described and the network just learned to ignore the input. I did have one successful training run with this shape so I suspect I was just lucky with the weight initialization in that instance. I changed the network to 3048, 40, 8, 40, 254 I was able to get useful training done again.
answers question: http://stackoverflow.com/q/48955231
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/comment/84718774
score: 0
has text: @Aran-Fey, Tried that but Instead of returning {yo:2,hello:2) its returning {} That's basically what I did alone and because I saw that nothing happens I used else and then it worked but its seems stupid to use else everything I want to check if something is false
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48857528

http://stackoverflow.com/q/48819828
has title: Numpy.NumpyArray has no attribute Read
answer count: 1
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
has body: I am trying to test a Convolution Neural Network with images that are stored in a folder within the root project directory. I have some code that is giving me an error and I am not sure why or where exactly the error is coming from. I will have the code and the full trace back of the error: the code(there are 6 jpg images in the folder) import os for testing_image in os.listdir('testing_images/'): full_detector('testing_images/' + testing_image) full error traceback --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) ~\Anaconda3\envs\deep_learning_1\lib\site-packages\PIL\Image.py in open(fp, mode) 2546 try: -&gt; 2547 fp.seek(0) 2548 except (AttributeError, io.UnsupportedOperation): AttributeError: 'numpy.ndarray' object has no attribute 'seek' During handling of the above exception, another exception occurred: AttributeError Traceback (most recent call last) &lt;ipython-input-123-68ab37d51b76&gt; in &lt;module&gt;() 4 import os 5 for testing_image in os.listdir('testing_images/'): ----&gt; 6 full_detector('testing_images/' + testing_image) &lt;ipython-input-119-a1a8a7870ff5&gt; in full_detector(image_path) 3 def full_detector(image_path): 4 pred_image = cv2.imread(image_path) ----&gt; 5 dog_breed = Resnet_Predict_Breed(pred_image) 6 if dog_detector(image_path): 7 print('this is dog with the breed : {}'.format(breed)) &lt;ipython-input-118-c02818bc5801&gt; in Resnet_Predict_Breed(img_path) 2 ### and returns the dog breed that is predicted by the model. 3 def Resnet_Predict_Breed(img_path): ----&gt; 4 bottleneck_feature = extract_Resnet50(path_to_tensor(img_path)) 5 predicted_vector = resnet_model.predict(bottleneck_feature) 6 return dog_names[np.argmax(predicted_vector)] &lt;ipython-input-18-3693dbe72dab&gt; in path_to_tensor(img_path) 4 def path_to_tensor(img_path): 5 # loads RGB image as PIL.Image.Image type ----&gt; 6 img = image.load_img(img_path, target_size=(224, 224)) 7 # convert PIL.Ima…
score: 1
tagged with: tensorflow
type: Question
downvote count: 0
tagged with: neural-network
tagged with: keras
has answer: http://stackoverflow.com/a/48819964

http://stackoverflow.com/comment/84876904
comment on: http://stackoverflow.com/q/48934830
has text: Floating point has 53 bits of significance, not 64 - the other bits are used for the exponent and sign.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48876953
upvote count: 3
type: Question
tagged with: distance
answer count: 2
tagged with: vector
has comment: http://stackoverflow.com/comment/84758000
accepted answer: http://stackoverflow.com/a/48876998
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/66231750
has comment: http://stackoverflow.com/comment/84758083
has comment: http://stackoverflow.com/comment/84758044
has answer: http://stackoverflow.com/a/66231750
has title: Supremum distance in Scipy python
tagged with: python
has comment: http://stackoverflow.com/comment/84758019
has body: I am trying to find all types of Minkowski distances between 2 vectors. I am using scipy distances to get these distances. The scipy function for Minkowski distance is: distance.minkowski(a, b, p=?) if p = 1, its called Manhattan Distance if p = 2, its called Euclidean Distance if p = infinite, its called Supremum Distance I want to know what value of 'p' should I put to get the supremum distance or there is any other formulae or library I can use?
has answer: http://stackoverflow.com/a/48876998
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/48826868
tagged with: python
has body: I am trying to build a simple REST API using the Python pyramid framework. I am having troubles getting a view callable executed when I have nested classes. (webkey class inside the auth class) I define my resources like this from __future__ import absolute_import from pyramid.traversal import find_root import logging log = logging.getLogger(__name__) class Resource(dict): def __init__(self, ref, parent): self.__name__ = ref self.__parent__ = parent def __repr__(self): # use standard object representation (not dict's) return object.__repr__(self) def add_child(self, ref, klass): resource = klass(ref=ref, parent=self) self[ref] = resource class Root(Resource): def __init__(self, request): Resource.__init__(self, ref='', parent=None) self.request = request self.add_child('auth', auth) self['auth'].add_child('webkey', webkey) class auth(Resource): def __init__(self, ref, parent): self.__name__ = ref self.__parent__ = parent def collection(self): root = find_root(self) request = root.request return request.db[self.collection_name] def retrieve(self): return [elem for elem in self.collection.find()] def create(self, document): object_id = self.collection.insert(document) return self.resource_name(ref=str(object_id), parent=self) def __getitem__(self, ref): return auth(ref, self) def getDesc(self): return 'Base authentication class' class webkey(Resource): def __init__(self, ref, parent): self.__name__ = ref self.__parent__ = parent def collection(self): root = find_root(self) request = root.request return request.db[self.collection_name] def retrieve(self): return [elem for elem in self.collection.find()] def create(self, document): object_id = self.collection.insert(document) return self.resource_name(ref=str(object_id), parent=self) def __getitem__(self, ref): return webkey(ref, self) def getDesc(self): return 'Web key authentication class' And my views as from pyramid.view import view_config from patientapi.resources.resources import Root, auth, webkey import logging …
has title: Building a REST API in Pyramid using traversal
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48867095
type: Question
has answer: http://stackoverflow.com/a/48867095
score: 0
answer count: 1
tagged with: pyramid

http://stackoverflow.com/q/48903408
has answer: http://stackoverflow.com/a/48904393
has title: Django: How to load file not in MEDIA_ROOT correctly | FileField?
answer count: 1
has comment: http://stackoverflow.com/comment/84814251
score: 0
tagged with: django-1.11
tagged with: python
accepted answer: http://stackoverflow.com/a/48904393
type: AnsweredQuestion
tagged with: django
type: Question
has body: In my Django project I have application in which I want to load files NOT in MEDIA_ROOT. I used storage attribute to change the place but it raise error. I used next code but it raise error when I try to load the file. How can I fix this problem? settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root') models.py: from django.core.files.storage import FileSystemStorage from os import environ PRODUCT_STORAGE = FileSystemStorage(location=environ.get('PRODUCT_STORAGE_PATH')) def product_file_upload_path(instance, filename): if instance.category=="1": path = '/category_1/' + '/%s' % filename return path elif instance.category=="2": path = '/category_2/' + '%s' % filename return path else: path = '%s' % filename return path class Product(models.Model): file = models.FileField( max_length=255, blank=True, null=True, validators=[validate_file_extension], storage=PRODUCT_STORAGE, upload_to=product_file_upload_path, ) ERROR: The joined path (/category_1/test.pdf) is located outside of the base path component (/other_folder)
tagged with: python-2.7

http://stackoverflow.com/comment/84904877
type: QuestionComment
comment on: http://stackoverflow.com/q/48949078
score: 0
has text: Possible duplicate of [scikit-image fails to install](https://stackoverflow.com/questions/48226362/scikit-image-fails-to-install)
type: Comment

http://stackoverflow.com/q/48843578
has title: How to implement 'And' function in perceptron in scikit-learn
has body: I am a newbie to machine learning and scikit-learn. I was trying to implement 'and' function in scikit-learn and written a small code as below: import pandas as pd from pandas import Series,DataFrame import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.model_selection import train_test_split df = DataFrame([[0,0,0],[0,1,0],[1,0,0],[1,1,1]],columns=list('abc')) X = df'a','b' y=df['c'] scalar_model = StandardScaler() train_test_split =X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=0) scalar_model = StandardScaler() scalar_model.fit(X_train) X_train_std = scalar_model.transform(X_train) X_test_std = scalar_model.transform(X_test) from sklearn.linear_model import Perceptron #perceptron initialization ppn = Perceptron(n_iter = 100,eta0=0.1,random_state=0) #fit the model with standardized data ppn.fit(X_train_std,y_train) #make predications y_pred = ppn.predict(X_test_std) from sklearn.metrics import accuracy_score accuracy = accuracy_score(y_test, y_pred) * 100 error = (1-accuracy_score(y_test, y_pred))*100 print("Accuracy: {} %".format(accuracy)) print("error: {} %".format(error)) After running the code I am getting the following results: Accuracy: 0.0 % error: 100.0 % Here are my questions : why is the perceptron not training after 100 iterations. I have read from the manual that if weights are not assigned to the features they are automatically assigned. If i want to assign the weights to the features randomly in the range of 0 and 1 How can I do that.
downvote count: 0
answer count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/48843731
favorite count: 0
upvote count: 2
tagged with: perceptron
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48843731
type: Question
tagged with: neural-network

http://stackoverflow.com/q/48916514
has comment: http://stackoverflow.com/comment/84839841
tagged with: beautifulsoup
has body: There's a link on our website that leads to a zip folder. The line in the HTML file for it is shown thus: Address Points (updated weekly) The zip folder's name will soon be changed using the current date so that it looks like this: WillCounty_AddressPoint_02212018.zip How do I change the corresponding line in the HTML? Using this answer I have a script. It runs with no errors but does not change anything in the HTML file. import bs4 from bs4 import BeautifulSoup import re import time data = r'\\gisfile\GISstaff\Jared\data.html' #html file location current_time = time.strftime("_%m%d%Y") #date #load the file with open(data) as inf: txt = inf.read() soup = bs4.BeautifulSoup(txt) #create new link new_link = soup.new_tag('link', href="Data/WillCounty_AddressPoint_%m%d%Y.zip") #insert it into the document soup.head.append(new_link) #save the file again with open (data, "w") as outf: outf.write(str(soup))
tagged with: python
answer count: 1
has title: python: change data hyperlink in HTML file
linked to: http://stackoverflow.com/q/35355225
score: 0
has comment: http://stackoverflow.com/comment/84839800
has answer: http://stackoverflow.com/a/48916686
type: AnsweredQuestion
tagged with: hyperlink
has comment: http://stackoverflow.com/comment/84839628
type: Question
tagged with: http://stackoverflow.com/tag/html
has comment: http://stackoverflow.com/comment/84868420
accepted answer: http://stackoverflow.com/a/48916686

http://stackoverflow.com/comment/84867586
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48929999
has text: This returns `sum_np(ten_million5000) = 2.49875050e+17` but `sum(ten_million[5000:]) = 4999998.750249899`
type: AnswerComment

http://stackoverflow.com/comment/84717252
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48856743
has text: without recursion it's quite easy: `sum(isinstance(x, float) for x in lst)`
score: 0

http://stackoverflow.com/comment/84921810
has text: Why is it like this only with classifiers ? The same code with SGDRegressor doesnot get this error. I feel like i hit dead end. I cant know data before and regressors dont serve my pupose of predicting the label. I cant use any algo that dont support partial_fit. I will just try with random forest warm_start and end my search.
score: 0
comment on: http://stackoverflow.com/a/48957375
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48874767
has body: I was trying to change the footers of my excel file then convert it to pdf with win32 package in Python3.6. It actually work with my home pc and at work pc only the pdf exporting part is giving me error. I am wondering if the MS Office version matters, since I have the newest at home and Excel 2007 at work. Here is mycode : import win32com.client as win32 excel = win32.gencache.EnsureDispatch('Excel.Application') file_path = r"C:\Mydir\DSexample\Myfile.xlsx" wb = excel.Workbooks.Open(file_path) ws = wb.ActiveSheet ws.PageSetup.CenterFooter = '&"Arial,Regular"&8new address' ws.PageSetup.LeftFooter = '&"Arial,Regular"&8new date' path_to_pdf = list() excel.Visible = True if ws.Cells(24,7).Value[-2]=="R": print(type(str(ws.Cells(24,7).Value[:-3]))) path_to_pdf.append("C:\\Mydir\\DSexample\\"+str(ws.Cells(24,7).Value[:-3]).strip()+".pdf") path_to_pdf.append("C:\\Mydir\\DSexample\\" + str(ws.Cells(24, 7).Value[:-3]).strip() + "R.pdf") wb.SaveAs(r"C:\Mydir\DSexample\new.xlsx") for i in range(0,len(path_to_pdf)): ws.ExportAsFixedFormat(0, path_to_pdf[i]) wb.Close() The Error I got is: Traceback (most recent call last): File "C:/Users/Guest/PycharmProjects/DScreator/DScreater.py", line 27, in ws.ExportAsFixedFormat(0, path_to_pdf[i],From = 1,To = 1,OpenAfterPublish=False) File "C:\Users\Guest\AppData\Local\Programs\Python\Python36\lib\site-packages\win32com\gen_py\00020813-0000-0000-C000-000000000046x0x1x6_Worksheet.py", line 115, in ExportAsFixedFormat , To, OpenAfterPublish, FixedFormatExtClassPtr) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024809), None)
answer count: 2
upvote count: 1
downvote count: 0
favorite count: 0
possible better answer: http://stackoverflow.com/a/79478992
tagged with: python
has title: win32 ExportAsFixedFormat
accepted answer: http://stackoverflow.com/a/48893711
has answer: http://stackoverflow.com/a/48893711
tagged with: excel
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/79478992
score: 1
type: Question

http://stackoverflow.com/a/48911970
accepted answer of: http://stackoverflow.com/q/48911602
score: 1
upvote count: 1
has body: From the error message, I get that you are running Python2 (works in Python3). Assuming that message is a string: Python 3 ([Python 3.Docs]: class bytes([source[, encoding[, errors]]])): byte_command = b"\x01" sock.send(byte_command + bytes(message, 'UTF-8')) Python 2 (where bytes and str are the same): byte_command = "\x01" sock.send(byte_command + message) I also renamed the socket to sock so it doesn't clash with the socket module itself. As everyone suggested, it's recommended / common to do the transformation using message.encode("utf8") (in Python 3 the argument is not even necessary, as utf8 is the default encoding). More on the differences (although question is in different area): [SO]: Passing utf-16 string to a Windows function (@CristiFati's answer).
has comment: http://stackoverflow.com/comment/84833066
has comment: http://stackoverflow.com/comment/84832001
answers question: http://stackoverflow.com/q/48911602
has comment: http://stackoverflow.com/comment/84834998
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84837539

performance
tags question: http://stackoverflow.com/q/48874745
tags question: http://stackoverflow.com/q/48938449
tags question: http://stackoverflow.com/q/48907216
tags question: http://stackoverflow.com/q/48815842
tags question: http://stackoverflow.com/q/48866978
tags question: http://stackoverflow.com/q/48894640
tags question: http://stackoverflow.com/q/48805035
tags question: http://stackoverflow.com/q/48928536
tags question: http://stackoverflow.com/q/48875318
tags question: http://stackoverflow.com/q/48804698
tag name: performance
tags question: http://stackoverflow.com/q/48849428
tags question: http://stackoverflow.com/q/48804934
type: Tag
tags question: http://stackoverflow.com/q/48839930
tags question: http://stackoverflow.com/q/48872800
tags question: http://stackoverflow.com/q/48942424

http://stackoverflow.com/comment/84905768
type: QuestionComment
has text: There are a lot of Lua JSON parsers. [One of them](https://github.com/Egor-Skriptunoff/json4lua), the code is `your_array = json.decode(your_string).sensordatavalues`
comment on: http://stackoverflow.com/q/48949526
score: 0
type: Comment

http://stackoverflow.com/comment/84883636
has text: The index method is exactly what I want. However when I use your code I get the following error:
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48938209

http://stackoverflow.com/comment/84874075
type: Comment
has text: Yes, scrapy alone is not able to get content that was render using javascript. Try to [disable the javascript](https://productforums.google.com/forum/#!msg/chrome/BYOQskiuGU0/5PRO2P-1WWwJ) in your browser and you will see how the page looks
comment on: http://stackoverflow.com/a/48931534
score: 0
type: AnswerComment

http://stackoverflow.com/a/48813371
answers question: http://stackoverflow.com/q/48813300
has body: You're including the newline in the string you read from the file. You want x = file.readline().strip()
has comment: http://stackoverflow.com/comment/84630497
has comment: http://stackoverflow.com/comment/84630289
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48813300
has comment: http://stackoverflow.com/comment/84630315
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84630326
score: 3
upvote count: 3

http://stackoverflow.com/a/65848466
has body: You can have a look also at Bayesian Optimization. In this github repository you can find the easy implementation. The difference is that Bayesian Optimization doesn't look into specific values that you input range, but it looks for values within the range. The example below is taken from their repository, so that you see how easy is the implementation! def black_box_function(x, y): """Function with unknown internals we wish to maximize. This is just serving as an example, for all intents and purposes think of the internals of this function, i.e.: the process which generates its output values, as unknown. """ return -x ** 2 - (y - 1) ** 2 + 1 from bayes_opt import BayesianOptimization # Bounded region of parameter space pbounds = {'x': (2, 4), 'y': (-3, 3)} optimizer = BayesianOptimization( f=black_box_function, pbounds=pbounds, random_state=1, ) optimizer.maximize( init_points=2, n_iter=3, ) print(optimizer.max) >>> {'target': -4.441293113411222, 'params': {'y': -0.005822117636089974, 'x': 2.104665051994087}}
has comment: http://stackoverflow.com/comment/125223612
answers question: http://stackoverflow.com/q/48859767
has comment: http://stackoverflow.com/comment/134300573
type: Answer
score: 1
upvote count: 2
downvote count: 1

http://stackoverflow.com/q/48947354
upvote count: 0
score: -4
type: Question
type: AnsweredQuestion
has title: Unable to convert image format in python
linked to: http://stackoverflow.com/q/2491222
has comment: http://stackoverflow.com/comment/84901104
has comment: http://stackoverflow.com/comment/84901233
has comment: http://stackoverflow.com/comment/84901122
has body: I am trying to convert all my images in a file into jpg format, defined as 'a' but I keep getting error as cannot convert. Any help? from PIL import Image import matplotlib.pyplot as plt import os #import imtools #path = imtools.get_imlist('.') a = 'K:\wq' for infile in os.listdir(a): outfile = os.path.splitext(infile)[0] + ".jpg" if infile != outfile: try: Image.open(infile).save(outfile) except OSError as error: print ("cannot convert", infile) error log: cannot convert manojcasual.png Process finished with exit code 0
answer count: 1
has answer: http://stackoverflow.com/a/48948830
accepted answer: http://stackoverflow.com/a/48948830
favorite count: 0
has comment: http://stackoverflow.com/comment/84901005
linked to: http://stackoverflow.com/q/18299949
tagged with: python
has comment: http://stackoverflow.com/comment/84901107
downvote count: 4
has comment: http://stackoverflow.com/comment/84901007
tagged with: python-3.x

http://stackoverflow.com/comment/84817961
comment on: http://stackoverflow.com/q/48889465
type: QuestionComment
has text: @matisetorm in my mbox file are X-thousand emails. I have 25 Keywords to look for and write it in csv. Linenumbers was the wrong word.
score: 0
type: Comment

http://stackoverflow.com/comment/84921218
type: Comment
type: QuestionComment
score: 0
has text: Use the csv module.
comment on: http://stackoverflow.com/q/48957099

http://stackoverflow.com/a/48824709
upvote count: 1
answers question: http://stackoverflow.com/q/48824396
downvote count: 1
score: 0
type: Answer
has body: Since you want to modify the input list, we can modify directly the elements: magicians=['feka','kuka','szuka'] def make_great(mages): for i, name in enumerate(mages): mages[i] = name + " the Great" return mages

http://stackoverflow.com/q/48902370
has answer: http://stackoverflow.com/a/48902578
type: UnansweredQuestion
tagged with: python
has body: I'm trying to print a list in a csv file. The code as is prints the list in the console but when I push it to print in a csv, it prints it in a clustered array. Here is the code: for pred in y_pred1: resultsFile = open('results.csv', 'w') print(y_pred1, end='\n', file = resultsFile) resultsFile.close() For that segment it outputs the file, but the output looks like this: [0. 0.02466293 0.04371493 0.07445887 0.10470171 0.1899941 0. 0.02395268 0.04299739 0.07386746 0.11551061 0.32383927 0. 0.02564607 0.04576736 0.07179424 0.10852157 0.18824359 0. 0.02395268 0.04299739 0.07386746 0.11551061 0.15899986 0. 0.02655989 0.05173249 0.08852134 0.02564607 0.04576736 0.07179424 0.10852157 0.02564607 0.04576736 0.07179424 0.10852157 0.15423326 0. 0.02395268 0.04299739 0.07386746 0.11551061 0. 0.02564607 0.04576736 0.07179424 0.10852157 0.15423326 0. 0.02395268 0.03308567 0.05735641 0.12299032 0. 0.02679364 0.03308567 0.05735641 0.12299032 0.16938186 0.25925685 0. 0. 0. 0. 0. 0. 0. ] I want it to output as a list with each result in a new cell like so: result 1 result 2 result 3 result 4...etc If I run the same code without outputting it to a file, it produces the list in the console exactly how I want it. As soon as I specify that I want it in a file, it becomes a cluster. Help!
type: Question
has title: Print results in a list in output file in python
score: 0
tagged with: spyder
answer count: 1

http://stackoverflow.com/a/48933556
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48933407
answers question: http://stackoverflow.com/q/48933407
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84873901
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84874092
has comment: http://stackoverflow.com/comment/84873801
has body: That's not a tuple - just parentheses. You have to add a comma before ')' to make it a tuple.

http://stackoverflow.com/a/48977705
has comment: http://stackoverflow.com/comment/85157369
has body: Try this(Python3 and Python2): import ibm_db as db2 def make_connexion(server, port, database, username, password, timeout): return db2.connect('DATABASE={0};'.format(database) + 'HOSTNAME={0};'.format(server) + 'PORT={0};'.format(str(port)) + 'PROTOCOL=TCPIP;' + 'UID={0};'.format(username) + 'PWD={0};'.format(password) + 'ConnectTimeout={0};'.format(str(timeout)) , '', '') # sample connexion object connexion = make_connexion('localhost', '50000', 'database', 'username', 'password', '30')
has comment: http://stackoverflow.com/comment/85118823
has comment: http://stackoverflow.com/comment/103999976
has comment: http://stackoverflow.com/comment/85075747
has comment: http://stackoverflow.com/comment/85044743
has comment: http://stackoverflow.com/comment/85075818
score: 0
answers question: http://stackoverflow.com/q/48954519
has comment: http://stackoverflow.com/comment/85119153
has comment: http://stackoverflow.com/comment/85044650
type: Answer

http://stackoverflow.com/a/48807470
has comment: http://stackoverflow.com/comment/84646594
downvote count: 3
has comment: http://stackoverflow.com/comment/84647276
upvote count: 0
has comment: http://stackoverflow.com/comment/84618328
answers question: http://stackoverflow.com/q/48806401
has body: you can use flask_mail library for sending mail.Here is just quick review.. ' from flask_mail import Mail, Message app.config['SECRET_KEY'] = 'your secretkey' app.config['MAIL_SERVER'] = 'smtp.gmail.com' app.config['MAIL_PORT'] = 465 app.config['MAIL_USE_TLS'] = False app.config['MAIL_USE_SSL'] = True app.config['MAIL_USERNAME'] = 'your gmail id' app.config['MAIL_PASSWORD'] = 'and its password' mail = Mail(app) msg = Message(subject=subject, sender=(master().user(), app.config['MAIL_USERNAME']), recipients=[recipients]) msg.body = "%s %s" % (body, msg.sender) if html is not None: msg.html = str(html) mail.connect() mail.send(msg) ' ***Note :- do not forget to turn off 2-step verification and also turn on Allow less secure apps from sign-in &amp; security > device activity &amp; security events
score: -3
type: Answer
has comment: http://stackoverflow.com/comment/84652050

http://stackoverflow.com/a/48853746
answers question: http://stackoverflow.com/q/48853667
has comment: http://stackoverflow.com/comment/84711236
accepted answer of: http://stackoverflow.com/q/48853667
type: AcceptedAnswer
downvote count: 0
has body: You need to use the bins argument to adjust which bins are used. import numpy as np from matplotlib import pyplot as plt population = 100 possible_answers = 4 scores = np.random.choice(range(possible_answers),population) plt.hist(scores, bins=range(possible_answers+1), ec="k") plt.show() Or, if you want to shift the bins plt.hist(scores, bins=np.arange(possible_answers+1)-0.5, ec="k")
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/84711265
has comment: http://stackoverflow.com/comment/84711366
upvote count: 3

http://stackoverflow.com/comment/84815335
comment on: http://stackoverflow.com/q/48904574
score: 0
type: Comment
type: QuestionComment
has text: Before claiming, I thought to ask here. I went through documentation, but didn't find any relevant info.

http://stackoverflow.com/a/48835887
answers question: http://stackoverflow.com/q/48835809
upvote count: 1
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/84677077
has comment: http://stackoverflow.com/comment/84676894
has comment: http://stackoverflow.com/comment/84677126
has comment: http://stackoverflow.com/comment/84676800
has comment: http://stackoverflow.com/comment/84676771
has comment: http://stackoverflow.com/comment/84676665
has comment: http://stackoverflow.com/comment/84676928
has comment: http://stackoverflow.com/comment/84676726
has comment: http://stackoverflow.com/comment/84677218
score: 1
has body: Hopefully this works for you: list(filter(lambda x: len(x[0]) &gt;= 3, filter(lambda x: '&lt;=X' in x[0], lst))) or, combining both conditions: list(filter(lambda x: len(x[0]) &gt;= 3 and '&lt;=X' in x[0], lst)) Also, notice that del in your loops really do not do what (I think) you want them to accomplish: In [175]: data = [1, 2, 3, 4] In [176]: for k in data: ...: del k ...: In [177]: data Out[177]: [1, 2, 3, 4] Moreover, modifying a list while looping over it is a bad idea. EXAMPLE: In [183]: lst = [(('5', 'Generous', '&lt;=X'), 0.33333333333333), ...:(('Generous', '&lt;=X'), 0.33333333333333)] In [184]: list(filter(lambda x: len(x[0]) &lt; 3, filter(lambda x: '&lt;=X' in x[0], lst))) Out[184]: [(('Generous', '&lt;=X'), 0.33333333333333)]
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48835809

http://stackoverflow.com/comment/84923111
comment on: http://stackoverflow.com/a/48957781
type: AnswerComment
score: 0
has text: Furthermore if there columns names will be not increased by 1 and in valid order, there also will be a problem. Check this case: df = pd.DataFrame({10: [2, 5, 2], 2: [0, 3, 2], 4: [1, 4, 2], }). Valid solution is here https://stackoverflow.com/a/48957782/3601806
type: Comment

http://stackoverflow.com/comment/84758945
has text: You have to open generate_actions.py in a text editor (e.g. Notepad or Wordpad) and change that line, then save it and run that command again.
score: 1
comment on: http://stackoverflow.com/q/48877266
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48886072
has title: How to access a method in one class from other classes
answer count: 1
accepted answer: http://stackoverflow.com/a/48886189
tagged with: python
score: -3
type: AnsweredQuestion
downvote count: 3
has comment: http://stackoverflow.com/comment/84776832
type: Question
has body: I'm trying to write a code that will parse some data in one class and then the parsed data will be inserted into sqlite DB ( and additional tasks) in other class. I've created a sqlite class: class DB_MNG(object): def db_conn(self): self.conn = sqlite3.connect('db.sqlite') self.cur = self.conn.cursor() self.cur.execute( 'CREATE TABLE IF NOT EXISTS hosts(ip TEXT PRIMARY KEY UNIQUE, port INTEGER, details' ' TEXT, details2 INTEGER)') def db_operator(self, ip, port, details, details2): self.ip = ip self.details = details self.port = port self.details2 = details2 self.cur.execute('SELECT ip FROM hosts WHERE ip = ? ', (self.ip,)) self.raw = self.cur.fetchone() self.conn.commit() class data_parser(DB_MNG): def __init__(self): DB_MNG.__init__(self) ???????? some parsed data that I need to pass to the DB_MNG.db_opertaor and update the table accordingly...
upvote count: 0
has answer: http://stackoverflow.com/a/48886189
favorite count: 0

http://stackoverflow.com/q/48885465
duplicate of: http://stackoverflow.com/q/38399927
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84777233
type: Question
has comment: http://stackoverflow.com/comment/84778140
has comment: http://stackoverflow.com/comment/84775482
has comment: http://stackoverflow.com/comment/84777205
tagged with: pandas
has body: pd.tz_convert() only accepts strings and pytz.timezone objects. If I try putting a mask on the conversion, to select each group of timezones, it just creates a copy of the dataframe instead of changing those values inplace. How can I do it? This is the rough idea on the code: mail_events['datetime_delivery'] = pd.DatetimeIndex(mail_events['datetime_delivery']).tz_convert(mail_events['timezone']) data sample: datetime_delivery datetime_open \ 0 2018-01-24 16:01:10.153029+00:00 2018-01-24 16:37:44.877778+00:00 1 2018-01-24 16:01:10.153029+00:00 2018-01-24 19:36:35.485069+00:00 2 2018-01-24 16:01:10.153029+00:00 2018-01-31 14:28:44.796184+00:00 10 2018-01-24 16:01:10.124305+00:00 2018-01-25 00:46:52.078911+00:00 11 2018-01-24 16:01:10.124305+00:00 2018-01-25 15:59:05.280755+00:00 distance timezone 0 0 days 00:36:34.724749 America/Sao_Paulo 1 0 days 03:35:25.332040 America/Sao_Paulo 2 6 days 22:27:34.643155 America/Sao_Paulo 10 0 days 08:45:41.954606 America/Sao_Paulo 11 0 days 23:57:55.156450 America/Sao_Paulo expected output (changes to datetime_delivery): datetime_delivery datetime_open \ 0 2018-01-24 14:01:10.153029-02:00 2018-01-24 16:37:44.877778+00:00 1 2018-01-24 14:01:10.153029-02:00 2018-01-24 19:36:35.485069+00:00 2 2018-01-24 14:01:10.153029-02:00 2018-01-31 14:28:44.796184+00:00 10 2018-01-24 14:01:10.124305-02:00 2018-01-25 00:46:52.078911+00:00 11 2018-01-24 14:01:10.124305-02:00 2018-01-25 15:59:05.280755+00:00 distance timezone 0 0 days 00:36:34.724749 America/Sao_Paulo 1 0 days 03:35:25.332040 America/Sao_Paulo 2 6 days 22:27:34.643155 America/Sao_Paulo 10 0 days 08:45:41.954606 America/Sao_Paulo 11 0 days 23:57:55.156450 America/Sao_Paulo
downvote count: 0
has comment: http://stackoverflow.com/comment/84778073
favorite count: 0
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/38399927
has title: How do you convert a (really big) pandas series datetime where each row has to be converted to a different timezone?
answer count: 0

http://stackoverflow.com/q/48914481
accepted answer: http://stackoverflow.com/a/48914582
has answer: http://stackoverflow.com/a/48914602
type: Question
tagged with: os.walk
has answer: http://stackoverflow.com/a/48914582
has body: I'm trying to search a series of folder/subfolders using filters, and then write the results out. It works if results are written to the same array, but can't figure out how to direct matches to specific arrays. Thanks for any suggestions. matchlist = [ ['*.csv'], ['*.txt'], ['*.jpg'], ['*.png'] ] filearray = [ [],[],[],[] ] for root, dirs, files in os.walk(folderpath): for file in files: for entry in matchlist: if file.endswith(entry): filearray[TheAppropriateSubArray].append(os.path.join(root, file))
tagged with: arrays
has title: Writing results from os.walk and endswith to specific array location
tagged with: ends-with
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84835916
possible better answer: http://stackoverflow.com/a/48914602
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84777350
type: Comment
score: 1
has text: Depends on what you want to count, really. `Counter` is great when you have different things to count, in this case it's just plain overkill.
type: AnswerComment
comment on: http://stackoverflow.com/a/48886166

http://stackoverflow.com/comment/84801896
type: QuestionComment
has text: this is my text input file. 94;93,1100,41,10,44,100,700,all_rows,force;[81.64, 75.53, 3.67, 24.62, 223766016.0];[0.005, -0.026, 0.008, 0.013, -0.2];[0.003, 0.002, 0.011, 0.072, -0.028] 95;94,1500,81,0,16,700,1300,all_rows,force;[81.81, 74.41, 3.7, 24.19, 216762368.0];[0.003, -0.011, 0.0, 0.031, -0.174];[-0.002, 0.015, -0.008, 0.018, 0.032]
comment on: http://stackoverflow.com/q/48898216
score: 0
type: Comment

http://stackoverflow.com/comment/85064811
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48916402
type: Comment
has text: Hello Lohmar, I solved the issue and I posted like answer. Thanks a lot for your time and help!

http://stackoverflow.com/a/48832382
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48832327
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/84670518
score: 6
has comment: http://stackoverflow.com/comment/84668980
has comment: http://stackoverflow.com/comment/84670443
has body: For the first example, you need to call the save method on the object, e.g. foo.save() instead of just save(): foo = FooModel() foo.save() Your second example looks ok. Make sure you are calling create() (all lowercase): bar = BarModel.objects.create() The message ... no attribute 'Create'. suggests you are calling BarModel.objects.Create(), which is incorrect. If that still doesn't work, then update your question with the actual code and full traceback. Using made up names like FooModel makes it harder to see the problem.
accepted answer of: http://stackoverflow.com/q/48832327

http://stackoverflow.com/a/48831716
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84668414
has comment: http://stackoverflow.com/comment/84669542
type: Answer
upvote count: 11
answers question: http://stackoverflow.com/q/48831661
score: 11
accepted answer of: http://stackoverflow.com/q/48831661
has comment: http://stackoverflow.com/comment/84668964
has comment: http://stackoverflow.com/comment/84668640
has body: You can transpose the list using zip, sort the transpose, and then transpose that list back into one of the correct dimensions. listOfLists = [ ['m', 'e', 'l', 't', 's'], ['g', 'p', 's', 'k', 't'], ['y', 'q', 'd', 'h', 's'] ] print(list(zip(*sorted(zip(*listOfLists))))) # [('e', 'l', 'm', 's', 't'), ('p', 's', 'g', 't', 'k'), ('q', 'd', 'y', 's', 'h')] Edit: As @StevenRumbalski points out in the comments, the above will completely sort the vertical slices (by first letter, then second letter, etc), instead of sorting them stably by first letter (sorting by first letter, then by relative order in the input). I'll reproduce his solution here for visibility: from operator import itemgetter list(map(list, zip(*sorted(zip(*listOfLists), key=itemgetter(0)))))

http://stackoverflow.com/comment/84636234
comment on: http://stackoverflow.com/q/48815849
has text: Function cv2.cvtColor only returns ONE argument. In your case it is RGB image. `Too many` means you expect more than function returns. Please refer to [documentation](https://docs.opencv.org/3.4.0/d7/d1b/group__imgproc__misc.html#ga397ae87e1288a81d2363b61574eb8cab) before writing code and asking on stackoverflow
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/48832218
has comment: http://stackoverflow.com/comment/84672533
score: 4
answers question: http://stackoverflow.com/q/48831802
has comment: http://stackoverflow.com/comment/84673257
has comment: http://stackoverflow.com/comment/84674466
has body: You can use the following approach, splitting the items of your Series object (that I called s) into lists and converting those a list of those lists into a DataFrame object (that I called df): df = pd.DataFrame([[s.index[i]] + s.str.split(' ')[i] for i in range(0, len(s))]) The [s.index[i]] + s.str.split(' ')[i] part is responsible for concatenation of the index at the beginning of the movie ids lists, and this is done for all rows available in the series. After that, you could just dump the DataFrame to a .txt file using a space as separator: df.to_csv('output.txt', sep=' ', index=False) You could also name your columns before dumping it, as suggested earlier.
type: Answer
upvote count: 4
downvote count: 0

http://stackoverflow.com/q/48824650
has answer: http://stackoverflow.com/a/48826360
downvote count: 4
upvote count: 1
has title: How can I create a personal for each account in django ? Note: not in admin site
has body: I am a beginner and still learning Django. I am wondering how can I build a personal site for each account like Facebook , Instagram, etc.Thank you very much. English is not my first language.
answer count: 1
tagged with: web
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python
tagged with: django
type: Question

http://stackoverflow.com/comment/84911933
has text: please can you link me to site which explain this `e1_search.trace("w"` in know i can any alphabet for this see error when i change `_tkinter.TclError: bad operations "q": should be one or more of rwua`
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48952075

http://stackoverflow.com/q/48811652
favorite count: 0
has comment: http://stackoverflow.com/comment/84627166
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/20109391
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48811813
type: Question
has body: I have 2 columns and i want diff column as an output.I tried with loops iteration.if i am passing array of values and i want diff column array. l h diff 100.87 100.87 max(h-l) 99.800778 100.87 max ((h-l),diff[0]) 101.1281283 101.1281283 max ((h-l),diff[1]) 106.4575807 106.4575807 max ((h-l),diff[2]) 109.3212896 109.3212896 ..... 107.7907916 109.3212896 105.128359 109.3212896 103.8668187 109.3212896 108.9978396 109.3212896 110.0006197 110.0006197 Can someone help me out.
score: 0
tagged with: pandas
answer count: 1
has title: return dynamic value from newly generated column value

http://stackoverflow.com/q/48835072
type: UnansweredQuestion
tagged with: python
tagged with: anaconda
answer count: 0
downvote count: 0
score: 1
type: Question
has comment: http://stackoverflow.com/comment/84675567
has title: Clean up Conda/Jupyter error messages accumulated cruft
tagged with: conda
upvote count: 1
has comment: http://stackoverflow.com/comment/84675389
has comment: http://stackoverflow.com/comment/84675466
has body: I have a bunch of accumulated cruft I'd like to clean up.. any help appreciated! When I start Jupyter Notebook I get: server_extensions is deprecated, use nbserver_extensions It seems I have nbserver extensions, How to get rid of the extraneous message? Is there a config file I can modify? Further: When clicking on the "conda" tab I get an error on the tab it displays: An error occurred while retrieving package information. Not Found and no packages or env's are displayed And the terminal shows [W 14:46:41.354 NotebookApp] 404 GET /conda/environments?_=1518813972634 (127.0.0.1) 8.62ms referer=http://localhost:8888/tree/Documents [W 14:46:41.356 NotebookApp] 404 GET /conda/packages/available?_=1518813972635 (127.0.0.1) 1.69ms referer=http://localhost:8888/tree/Documents Yet when I go to "change kernels" on the Notebook tab, all proper kernels display. Similarly if I use Anaconda-navigator, all my environments show up. I have updated Anaconda to 5.1 on Linux 16.04 when I run: jupyter kernelspec list Available kernels: python3 /home/tom/.local/share/jupyter/kernels/python3 tf4 /home/tom/.local/share/jupyter/kernels/tf4 clojure /home/tom/anaconda3/share/jupyter/kernels/clojure groovy /home/tom/anaconda3/share/jupyter/kernels/groovy java /home/tom/anaconda3/share/jupyter/kernels/java kotlin /home/tom/anaconda3/share/jupyter/kernels/kotlin scala /home/tom/anaconda3/share/jupyter/kernels/scala sql /home/tom/anaconda3/share/jupyter/kernels/sql xonsh /home/tom/anaconda3/share/jupyter/kernels/xonsh The above entries are not my main kernels.. the two 1st entries are ones I created for Nteract using the Ipython kernels command. I did experiance errors initially updating notebook on its own (pre the Anaconda update to 5.1) and got some help from the package maintainer but lost the entries on the conda tab When running a basic notebook I get the following further errors yet thinks seem to run ok but I'd like to get stuff cleaned up: [W 15:04:30.580 NotebookApp] 404 GET /nbextensi…
has comment: http://stackoverflow.com/comment/84675490
favorite count: 0
tagged with: jupyter-notebook

http://stackoverflow.com/a/48843835
accepted answer of: http://stackoverflow.com/q/48842320
upvote count: 8
answers question: http://stackoverflow.com/q/48842320
type: AcceptedAnswer
score: 8
type: Answer
has body: You may filter the image by the radius by creating a matrix of radii R and calculating image[(R &gt;= r-.5) &amp; (R &lt; r+.5)].mean() where r is the radius you are interested in. import numpy as np import matplotlib.pyplot as plt from skimage import data # get some image image = data.coins() image = image[:,0:303] # create array of radii x,y = np.meshgrid(np.arange(image.shape[1]),np.arange(image.shape[0])) R = np.sqrt(x**2+y**2) # calculate the mean f = lambda r : image[(R &gt;= r-.5) &amp; (R &lt; r+.5)].mean() r = np.linspace(1,302,num=302) mean = np.vectorize(f)(r) # plot it fig,ax=plt.subplots() ax.plot(r,mean) plt.show()
has comment: http://stackoverflow.com/comment/84737423
has comment: http://stackoverflow.com/comment/84737715
downvote count: 0

http://stackoverflow.com/a/48885641
downvote count: 0
upvote count: 13
has comment: http://stackoverflow.com/comment/84786386
has comment: http://stackoverflow.com/comment/121492433
type: Answer
has comment: http://stackoverflow.com/comment/128774288
score: 13
accepted answer of: http://stackoverflow.com/q/48870489
has body: If you need to create the object, here is how I did it: # Mixin that allows to create multiple objects from lists. class CreateListModelMixin(object): def get_serializer(self, *args, **kwargs): """ if an array is passed, set serializer to many """ if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super(CreateListModelMixin, self).get_serializer(*args, **kwargs) And then in the view that you would like to use it in just do: class PropertyCreateView(CreateListModelMixin, generics.CreateAPIView): serializer_class = PropertySerializer permission_classes = (IsAuthenticated, ) And that's already it (make sure to put in the mixin as an argument BEFORE the view; like I did it). Now the body of your postrequest would look like this: { [ { "name": "&lt;some_name&gt;" "value": "&lt;some_value&gt;" "unit": "&lt;some_unit&gt;" }, { "name": "&lt;some_name&gt;" "value": "&lt;some_value&gt;" "unit": "&lt;some_unit&gt;" }, { "name": "&lt;some_name&gt;" "value": "&lt;some_value&gt;" "unit": "&lt;some_unit&gt;" }, ... ] } The cool thing about it, this way you can also just post a single object like this: { "name": "&lt;some_name&gt;" "value": "&lt;some_value&gt;" "unit": "&lt;some_unit&gt;" } I hope this helps! :)
answers question: http://stackoverflow.com/q/48870489
has comment: http://stackoverflow.com/comment/84779274
type: AcceptedAnswer

http://stackoverflow.com/comment/116792691
type: Comment
score: 0
has text: Because you have a non-unique index! Your index has duplicates `['B']*3 + ['A']*3`.
comment on: http://stackoverflow.com/q/48888843
type: QuestionComment

http://stackoverflow.com/comment/84649574
type: Comment
comment on: http://stackoverflow.com/a/48823076
type: AnswerComment
score: 0
has text: TypeError: type str doesn't define __round__ method for the 1st suggestion

http://stackoverflow.com/comment/84899181
has text: @ler with the code I have now posted I get the reported output. I do not know why you would get something else
type: Comment
comment on: http://stackoverflow.com/a/48945773
score: 0
type: AnswerComment

http://stackoverflow.com/q/48919166
tagged with: python
has answer: http://stackoverflow.com/a/48920932
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48920932
downvote count: 3
upvote count: 1
type: Question
score: -2
has title: How can I use is_authenticated() in django to redirect user to their own page?
answer count: 1
has body: I am a beginner in django framework. I would to make my website to redirect users to the personal page if they already logged at the time they request the homepage like many websites.
favorite count: 0
tagged with: django

http://stackoverflow.com/q/48881297
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84768343
has comment: http://stackoverflow.com/comment/84767606
has title: Finding common list sequences
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48881972
has comment: http://stackoverflow.com/comment/84771267
has comment: http://stackoverflow.com/comment/84766953
downvote count: 0
possible better answer: http://stackoverflow.com/a/48881655
has answer: http://stackoverflow.com/a/48881655
favorite count: 0
has body: I have a dictionary of lists. Each list is a sequence of numbers. No two lists are equal but two or more lists may start with the same sequence of numbers (see my example input below). What I want to do is find these common sequences and make them a new element in the dictionary. Sample input: sequences = { 18: [1, 3, 5, 6, 8, 12, 15, 17, 18], 19: [1, 3, 5, 6, 9, 13, 14, 16, 19], 25: [1, 3, 5, 6, 9, 13, 14, 20, 25], 11: [0, 2, 4, 7, 11], 20: [0, 2, 4, 10, 20], 26: [21, 23, 26], } Sample output: expected_output = { 6: [1, 3, 5, 6], 18: [8, 12, 15, 17, 18], 14: [9, 13, 14], 19: [16, 19], 25: [20, 25], 4: [0, 2, 4], 11: [7, 11], 20: [10, 20], 26: [21, 23, 26], } The key of each list is its last element. Order doesn't matter. I have a working code. However, it's very messy. Could somebody suggest a simpler/cleaner solution? from collections import Counter def split_lists(sequences): # get first elem from each sequence firsts = list(map(lambda s: s[0], sequences)) # get non-duplicate first elements not_duplicates = list(map(lambda c: c[0], filter(lambda c: c[1] == 1, Counter(firsts).items()))) # start the new_sequences with the non-duplicate lists new_sequences = dict(map(lambda s: (s[-1], s), filter(lambda s: s[0] in not_duplicates, sequences))) # get duplicate first elements duplicates = list(map(lambda c: c[0], filter(lambda c: c[1] &gt; 1, Counter(firsts).items()))) for duplicate in duplicates: # get all lists that start with the duplicate element duplicate_lists = list(filter(lambda s: s[0] == duplicate, sequences)) # get the common elements from the duplicate lists and make it a new # list to add to our new_sequences dict repeated_sequence = sorted(list(set.intersection(*list(map(set, duplicate_lists))))) new_sequences[repeated_sequence[-1]] = repeated_sequence # get lists from where I left of i = len(repeated_sequence) sub_lists = list(filter(lambda s: len(s) &gt; 0, map(lambda s: s[i:], duplicate_lists))) # recursively split them and store them in new_sequences n…
has comment: http://stackoverflow.com/comment/84766790
score: 6
has comment: http://stackoverflow.com/comment/84766861
has comment: http://stackoverflow.com/comment/84766945
tagged with: python
has answer: http://stackoverflow.com/a/48881972
has comment: http://stackoverflow.com/comment/84768146
upvote count: 6

http://stackoverflow.com/q/48931155
upvote count: 2
type: UnansweredQuestion
type: Question
tagged with: popen
tagged with: pipe
tagged with: stdout
downvote count: 0
favorite count: 0
has body: To prove a concept to myself I wrote this code: from subprocess import Popen, PIPE import json queue = [] command1 = ['python', 'C:\Desktop\testing_popen\time_delay.py'] command2 = ['python', 'C:\Desktop\testing_popen\no_time_delay.py'] queue.append(Popen(command1, stdout=PIPE)) queue.append(Popen(command2, stdout=PIPE)) while len(queue) &gt; 0: while queue[0].poll() is None: queue.append(queue.pop(0)) print json.loads(queue.pop(0).communicate()[0]) output from no_time_delay.py output from time_delay.py This works exactly as I wish so that elements further down the queue aren't held up but elements closer to the front that take longer to process. I'm using the queue as a way of throttling the process so that I don't use up all the CPU but I always want the maximum number of processes running. I then wanted to implement this is in a project I have to process 200 records but I only want 10 scripts running at a time as not to overload the CPU. Each script can only handle 10 records. So.. I create a queue and while len(scripts_to_be_processed) &gt; 0: if len(queue) &lt; 10: queue.append(Popen(command,stdout=PIPE,stderr=PIPE)) else: while queue[0].poll() is None: queue.append(queue.pop(0)) function_to_process_out(queue.pop(0).communicate()[0]) and then process the scripts remaining in the queue outside of this loop.. The process involves ingestion of an xlsx file, I can see from my task manager that the processes have finished but the main script coordinating the instances only receives None back from the polling. I have updated the script to write the output to a file at the end of a run. The file will be written to before the std.out.write but not after so it is my theory that the constant polling might be blocking the script from outputting. Any help would be greatly appreciated, Cheers Edit Update: My issue lay in using the PIPE as my stdout. The buffer file filled up and caused a deadlock. I fixed this by writing each individual record to stdout with a newline delim…
tagged with: python
has title: Popen polling blocking my stdout
score: 2
answer count: 0
tagged with: subprocess

http://stackoverflow.com/comment/84818384
type: Comment
comment on: http://stackoverflow.com/a/48903362
has text: @ikac I remove the global variable, but now wholeimage can't be saved
type: AnswerComment
score: 0

http://stackoverflow.com/a/48932875
has comment: http://stackoverflow.com/comment/84873102
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48932816
upvote count: 1
has body: According to the strftime documentation: from datetime import datetime mydate = '1/21/2015 01:30:22 AM' print datetime.strptime(mydate, '%m/%d/%Y %I:%M:%S %p')
type: Answer

http://stackoverflow.com/q/48902224
tagged with: python
has title: How do you replace certain values from row to row in python pandas based on data in other columns?
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84809895
has body: Right now I am working with python pandas and cannot find the solution to this issue: I have a dataframe df and I want to copy certain data from one row to another row (replacing) based on on a tag in another colomn of the same dataset. An example is the best way to show it I think: Kind Type V1 V2 V3 AAA AAA 7 8 4 BBB AAA 4 8 1 CCC AAA 3 1 7 AAA BBB 2 5 3 BBB BBB 11 9 8 CCC BBB 7 7 10 AAA CCC 5 8 2 BBB CCC 2 3 7 CCC CCC 4 10 6 What I want is replacing kind AAA with kind BBB for each Type but only for row Value3(V3). So that the result will be: Kind Type V1 V2 V3 AAA AAA 7 8 1 BBB AAA 4 8 1 CCC AAA 3 1 7 AAA BBB 2 5 8 BBB BBB 11 9 8 CCC BBB 7 7 10 AAA CCC 5 8 7 BBB CCC 2 3 7 CCC CCC 4 10 6 As you can see, these 3 number were replaced now, with values from kind BBB. With df.loc[df['Kind']=='AAA','V3'] = x # x is numeric I can only replace each V3 number in combination with kind AAA with number x, but this is not what I want. As the numbers are all different. Can someone help me here? Thanks!
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48902718
tagged with: dataframe
has answer: http://stackoverflow.com/a/48902463
tagged with: replace
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48902463
has comment: http://stackoverflow.com/comment/84809988
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48902718

numpydoc
tag name: numpydoc
type: Tag
tags question: http://stackoverflow.com/q/48864008

http://stackoverflow.com/q/48822715
favorite count: 0
has comment: http://stackoverflow.com/comment/84654369
tagged with: python
has body: (related to this answer) Given a df, I was expecting to get the results of df.expanding() and to perform some multivariate operations on this (operations involving several columns of df simultaneously over an expanding window of rows) using .apply(). It turns out this is not possible. So, much as in the answer linked above, I need to use numpy.as_strides of df. Except, in contrast to the question linked above, using strides to get an expanding views of my df, instead of rolling ones (an expanding window has a fixed left side and the right side moves to the right incrementally). consider this df: import numpy import pandas df = pandas.DataFrame(numpy.random.normal(0, 1, [100, 2]), columns=['size_A', 'size_B']).cumsum(axis=0) consider this code to extract a rolling window of W rows of that df (this comes from the answer above): def get_sliding_window(df, W): a = df.values s0,s1 = a.strides m,n = a.shape return numpy.lib.stride_tricks\ .as_strided(a,shape=(m-W+1,W,n),strides=(s0,s0,s1)) roll_window = get_sliding_window(df, W = 3) roll_window[2] Now I want to modify get_sliding_window to get it to return an expanding window of a df (instead of a rolling one): def get_expanding_window(df): a = df.values s0,s1 = a.strides m,n = a.shape out = numpy.lib.stride_tricks\ .as_strided(a, shape=(m,m,n),strides=(s0,s0,s1)) return out expg_window = get_expanding_window(df) expg_window[2] But I'm not using the arguments of as_strided correctly: I can't seem to be getting the right matrices --that would be something like: [df.iloc[0:1].values ,df.iloc[0:2].values, df.iloc[0:3].values,...] Edit: In a comment @ThomasKühn proposes to use list comprehension. This would solve the problem, but too slowly. What is the cost? One a vector valued function, we can compare the cost of list comprehension with .expand(). It ain't small: numpy.random.seed(123) df = pandas.DataFrame((numpy.random.normal(0, 1, 10000)), columns=['Value']) %timeit method_1 = numpy.array([df.Value.iloc[range(j + 1)].sum…
linked to: http://stackoverflow.com/q/48817828
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84694222
score: 3
has comment: http://stackoverflow.com/comment/84653585
has comment: http://stackoverflow.com/comment/84649122
type: Question
has comment: http://stackoverflow.com/comment/84654600
has answer: http://stackoverflow.com/a/48866728
accepted answer: http://stackoverflow.com/a/48866728
has comment: http://stackoverflow.com/comment/84672148
has comment: http://stackoverflow.com/comment/84653248
tagged with: numpy
upvote count: 3
tagged with: pandas
linked to: http://stackoverflow.com/q/37447347
has comment: http://stackoverflow.com/comment/84652539
answer count: 1
downvote count: 0
has title: extracting an expanding window (numpy strided) of a DataFrame

cuda
tags question: http://stackoverflow.com/q/48847980
tag name: cuda
type: Tag

http://stackoverflow.com/comment/84689920
comment on: http://stackoverflow.com/a/48842793
type: AnswerComment
has text: On most platforms, you should not muck with `/usr/bin` directly. If you are on Debian, the system `python` always refers to Python 2, and breaking that policy will have unpleasant consequences.
type: Comment
score: 2

http://stackoverflow.com/q/48862244
has answer: http://stackoverflow.com/a/48862301
tagged with: python
has answer: http://stackoverflow.com/a/48862524
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48862301
score: 1
possible better answer: http://stackoverflow.com/a/48862524
type: Question
tagged with: numpy
answer count: 2
tagged with: arrays
has body: I have the following placeholder array: placeholder = np.zeros(10) A contains the values that I want to go in to the placeholder A = np.array([25, 40, 65,50]) idx has the indices of the placeholder ( note that this has the same shape as A) idx = np.array([0, 5, 6, 8]) Question: I want placeholder to be populated with the elements of A. The amount to which an element in A to be repeated is defined by the length of the intervals of the idx array. For example, 25 is repeated 5 times because the corresponding index range is [0, 5). 65 is repeated twice because the corresponding index range is [6,8) Expected output: np.array([25, 25, 25, 25, 25, 40, 65, 65, 50, 50])
favorite count: 0
has title: Repeating numpy array elements according to another index array
upvote count: 2

http://stackoverflow.com/a/48899278
upvote count: 5
has comment: http://stackoverflow.com/comment/84805230
has body: The error says it all : Traceback (most recent call last): File "playDivya.py", line 4, in &lt;module&gt; from selenium import webdriver . ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload/array.so, 2): Symbol not found: __PySlice_AdjustIndices Reasons and Solution This issue can arise when you install a new version of python. In those cases you may need to run hash -r python to tell bash to reset the cached location to the python executable. If hash -r python says too many args then you can use rehash command. As per the discussion Symbol not found: __PyCodecInfo_GetIncrementalDecoder the issue occurs when Python is updated from Python 2.7.10 to 2.7.11. If you are using conda package you need to run conda install python=2.7.10 which will solve this problem. Even downgrading Python to 2.7.10 will also work. The best solution would be Re-Installing Selenium.
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/98516136
answers question: http://stackoverflow.com/q/48897137
score: 5
accepted answer of: http://stackoverflow.com/q/48897137

http://stackoverflow.com/q/48827414
answer count: 0
tagged with: machine-learning
has body: I am using Spacy 2.0.6 with an italian NER model. I would like to add samples to that model to improve accuracy. What is the correct way? At the beginning i have trained the model with this code: with nlp.disable_pipes(*other_pipes): # only train NER optimizer = nlp.begin_training() for itn in range(epochs): random.shuffle(train) losses = {} for batch in minibatch(train, size=32): docs, golds = zip(*batch) nlp.update(docs, golds, drop=.3, sgd=optimizer, losses=losses) Unfortunately, It does not work for new samples. I get an error on the optimizer = nlp.begin_training() line. optimizer = nlp.begin_training() File "/home/damiano/lavoro/python/parser/.env/lib/python3.5/site-packages/spacy/language.py", line 456, in begin_training sgd=self._optimizer) File "nn_parser.pyx", line 843, in spacy.syntax.nn_parser.Parser.begin_training KeyError: 'token_vector_width' How can i "resume" the training of a NER model?
type: Question
has comment: http://stackoverflow.com/comment/97623684
score: 2
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: nlp
has title: How to resume the NER training?
tagged with: spacy

http://stackoverflow.com/comment/84676894
score: 1
comment on: http://stackoverflow.com/a/48835887
type: AnswerComment
type: Comment
has text: @DeliriousLettuce I have improved compatibility in my latest edit

http://stackoverflow.com/q/48838247
type: AnsweredQuestion
upvote count: 31
type: Question
score: 31
accepted answer: http://stackoverflow.com/a/48838347
has answer: http://stackoverflow.com/a/70532206
tagged with: pandas
downvote count: 0
favorite count: 0
has title: How to check every pandas series value is unique
has answer: http://stackoverflow.com/a/48838370
has answer: http://stackoverflow.com/a/48838347
tagged with: python
has answer: http://stackoverflow.com/a/59043839
answer count: 4
possible better answer: http://stackoverflow.com/a/48838370
has body: I know how to count the number of unique values in pandas series (one column in pandas dataframe). pandas.Series.value_counts But how do I check if they are all unique? Should I just compare value_counts with its length?

http://stackoverflow.com/comment/85061456
score: 0
type: Comment
type: QuestionComment
has text: @dragon951, did one of the below solutions help? if so, feel free to accept (tick on left).
comment on: http://stackoverflow.com/q/48895370

http://stackoverflow.com/q/48939214
has answer: http://stackoverflow.com/a/48953730
accepted answer: http://stackoverflow.com/a/48953730
has title: Why can parameter substitution not be used with tables in sqlite3?
upvote count: 3
tagged with: sqlite
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
type: Question
score: 3
linked to: http://stackoverflow.com/q/3247183
has body: After trying for a long time to get this Python code to work: #!/usr/bin/python3 import sqlite3 conn = sqlite3.connect("testdb.sqlite") cur = conn.cursor() #This doesn't work cur.execute("DROP TABLE IF EXISTS :table_name", {"table_name": "Table1"}) I came across this and other posts that simply say parameter substitution cannot be used with tables. However, I haven't been able to find any explanations or details (nothing is mentioned in the relevant documentation either). So my question is: is there a fundamental reason for this exception? If it's arbitrary, are tables the only exception? (This is so that we know what we can and cannot use.)

http://stackoverflow.com/comment/84731804
type: Comment
has text: I'm trying to train a deep learning architecture and I want to pass into the net every two images together
comment on: http://stackoverflow.com/q/48855788
score: 0
type: QuestionComment

http://stackoverflow.com/a/48887599
accepted answer of: http://stackoverflow.com/q/48887439
answers question: http://stackoverflow.com/q/48887439
has body: I figured it out. I need to specify the range parameter as otherwise things get truncated as outliers. so use as: jh2 = np.histogram2d(np.trunc(img.ravel(order='K')).astype(np.int32), np.trunc(img.ravel(order='K')).astype(np.int32), bins=(bins, bins), range=[[0, bins], [0, bins]])[0]
type: AcceptedAnswer
downvote count: 0
score: 1
type: Answer
upvote count: 1

http://stackoverflow.com/q/48888302
type: Question
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48888523
has body: I have a Pandas DataFrame with customer refund reasons. It contains these example data rows: **case_type** **claim_type** 1 service service 2 service service 3 chargeback service 4 chargeback local_charges 5 service supplier_service 6 chargeback service 7 chargeback service 8 chargeback service 9 chargeback service 10 chargeback service 11 service service_not_used 12 service service_not_used I would like to compare the customer's reason with some sort of labeled reason. This is no problem, but I would also like to see the total number of records in a specific group (customer reason). case_claim_type = df"case_type", "claim_type" case_claim_type.groupby(by=("case_type", "claim_type"))["case_type"].count() Which gives me this output, for example: **case_type** **claim_type** service service 2 supplier_service 1 service_not_used 2 chargeback service 6 local_charges 1 I would also like to have have the sum of the output per case_type. Something like: **case_type** **claim_type** service service 2 supplier_service 1 service_not_used 2 total: 5 chargeback service 6 local_charges 1 total: 7 It doesn't necessarily has to be in this last output format, a column with the (aggregated) totals per case_type is also fine.
has title: Pandas groupby and sum total of group
tagged with: pandas-groupby
tagged with: pandas
possible better answer: http://stackoverflow.com/a/48888523
has comment: http://stackoverflow.com/comment/84781674
accepted answer: http://stackoverflow.com/a/48888940
tagged with: python
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84782317
score: 6
upvote count: 6
type: AnsweredQuestion
tagged with: dataframe
has answer: http://stackoverflow.com/a/48888940

http://stackoverflow.com/comment/84846931
has text: when I save the output and run it is showing the len of the output as 1 so can you say me how to fix it
comment on: http://stackoverflow.com/a/48920137
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84844972
has text: Your answer is also useful. Thank you:)
type: AnswerComment
comment on: http://stackoverflow.com/a/48885944
score: 0
type: Comment

http://stackoverflow.com/comment/84752129
type: Comment
has text: I don't see how this is relevant to the question. What are you planning to do with that `expand` method?
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48874126

http://stackoverflow.com/a/48848213
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48847508
answers question: http://stackoverflow.com/q/48847508
has comment: http://stackoverflow.com/comment/84709203
type: Answer
has comment: http://stackoverflow.com/comment/84709223
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84709786
has body: I am using transform min as new key df.assign(New=df.groupby(['col1','col3']).col2.transform('min')).sort_values(['col1','New'])

http://stackoverflow.com/comment/84661270
type: Comment
score: 0
has text: I do not have any attributes defined on the scope of the class (on the same level as __init__) (neither in the considered class, nor in the base class).
type: AnswerComment
comment on: http://stackoverflow.com/a/48827966

http://stackoverflow.com/q/48876387
has comment: http://stackoverflow.com/comment/84757445
tagged with: pyspark
has answer: http://stackoverflow.com/a/55164251
type: UnansweredQuestion
score: 2
has title: Pyspark replace strings in Spark dataframe column by using values in another column
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84756847
linked to: http://stackoverflow.com/q/37038014
answer count: 1
tagged with: apache-spark-sql
has body: I'd like to replace a value present in a column with by creating search string from another column before id address st 1 2.PA1234.la 1234 2 10.PA125.la 125 3 2.PA156.ln 156 After id address st 1 2.PA9999.la 1234 2 10.PA9999.la 125 3 2.PA9999.ln 156 I tried df.withColumn("address", regexp_replace("address","PA"+st,"PA9999")) df.withColumn("address",regexp_replace("address","PA"+df.st,"PA9999") both seam to fail with TypeError: 'Column' object is not callable could be similar to Pyspark replace strings in Spark dataframe column

http://stackoverflow.com/comment/85531771
has text: I don't know the solution, but I was able to reproduce your exact same problem with PyQt5 and glut on Py 3 (so, it's probably something related to that toolchain).
comment on: http://stackoverflow.com/q/48892375
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48864420
score: 0
tagged with: python
type: UnansweredQuestion
has title: Unable debug python helloworld in vscode
has comment: http://stackoverflow.com/comment/84758340
type: Question
tagged with: visual-studio-code
answer count: 1
has answer: http://stackoverflow.com/a/48934778
has body: I am trying python first time in VSCode. I am successfully able to run python file, but not able debug it. I am following steps given in this tutorial. When I debug, I am getting following error in Debug console: Traceback (most recent call last): File "/home/digitate/.vscode/extensions/ms-python.python-2018.1.0/pythonFiles/PythonTools/visualstudio_py_launcher.py", line 91, in &lt;module&gt; vspd.debug(filename, port_num, debug_id, debug_options, currentPid, run_as)

http://stackoverflow.com/comment/84794884
comment on: http://stackoverflow.com/a/48894339
score: 0
type: Comment
has text: I am now getting the error that says "File "H:/College Fourth Year/Development Project/Final Year Project 2018/All_Data_Report.py", line 17, in <module> PdfFileMerger.append(path + files) TypeError: append() missing 1 required positional argument: 'fileobj'"
type: AnswerComment

http://stackoverflow.com/q/48835397
favorite count: 0
has body: I have a list of other lists I am using to represent a map of my workspace. Here is a simplified version: areaMap = [[00,00,00,00,00],[00,00,01,11,01]] Now, when i print this onto the screen using: for x in range(len(areaMap)): print(areaMap[x]) the leading zero will be chopped off: [0,0,0,0,0], [0,0,1,11,1] I need these numbers to have 2 digits so they are visually appealing when printed. I tried using: for y in areaMap: [str(item).zfill(6) for item in areaMap[y]] but this creates unneeded quotation marks and spaces.
score: 0
has answer: http://stackoverflow.com/a/48835474
upvote count: 1
tagged with: python
downvote count: 1
type: AnsweredQuestion
tagged with: list
has title: initialize a list with 2 digit numbers
type: Question
accepted answer: http://stackoverflow.com/a/48835474
has comment: http://stackoverflow.com/comment/84675574
has comment: http://stackoverflow.com/comment/84675620
answer count: 1

http://stackoverflow.com/comment/84641257
type: Comment
has text: It's ALWAYS a missing parenthesis on the line before.
score: 1
comment on: http://stackoverflow.com/q/48818676
type: QuestionComment

http://stackoverflow.com/comment/84758687
comment on: http://stackoverflow.com/q/48874920
type: Comment
type: QuestionComment
has text: @hpaulj - I would, but the problem is I'm trying to save an array produced by someone else's code. It basically has the form of the variable I'm testing for saving/reading
score: 0

http://stackoverflow.com/comment/84641658
has text: urllib.parse is a feature only available in python 3.x, so the Flask app is designed for 3.x, you should run the app under python 3.5 instead of python 2.7.
score: 0
comment on: http://stackoverflow.com/q/48818824
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48866683
has answer: http://stackoverflow.com/a/48866766
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Can you copy the text of an input?
linked to: http://stackoverflow.com/q/25580569
has comment: http://stackoverflow.com/comment/84736700
downvote count: 2
has body: Is it possible to copy the text of an input? If there was an input with "text" in it can you get selenium/python to copy it in your clipboard? &lt;input type="text" style="cursor:text;background:none;" class="form-control input-sm" onmousemove="this.select()" value="This is a Text" readonly=""&gt;
has comment: http://stackoverflow.com/comment/84737214
tagged with: selenium
has comment: http://stackoverflow.com/comment/84736496
tagged with: dom
type: Question
score: -2
tagged with: copy
upvote count: 0
answer count: 1

http://stackoverflow.com/a/48990141
accepted answer of: http://stackoverflow.com/q/48812483
score: 0
type: AcceptedAnswer
has body: Solved issue Well it seems that this issue was solve already in the master branch. So I am testing it with the version 0.12.14+25.g675aacf72 built from the master and it is working well. The version 0.12.15dev1 was released as well, I am sure this is fixed in that version as well. Previous Solution I found a workaround before this was solve on the master branch. I have created a new circle glyph plotting the whole ColumnDataSource at the top of the rest of the glyphs from bokeh.models import Button, ColumnDataSource, Circle, CDSView, IndexFilter from bokeh.models.tools import LassoSelectTool from bokeh.models.glyphs import MultiLine, Line from bokeh.palettes import Reds3 from bokeh.layouts import column from bokeh.plotting import curdoc, figure import numpy as np plot_1 = figure( width=400, height=400, tools="pan,box_zoom,box_select,wheel_zoom,tap,save,reset,crosshair", ) x = list(range(0,200)) y = np.random.random_integers(200, size=(200)) source = ColumnDataSource(data=dict(x=x, y=y)) selection = list(np.random.random_integers(100, size=(20))) view = CDSView( source=source, filters=[IndexFilter(x[100:])] ) circle = plot_1.circle( x='x', y='y', size=5, fill_alpha=1, fill_color='orange', line_color=None, selection_color=Reds3[0], source=source, view=view, legend='FLAG 1', ) circle.selection_glyph = Circle( fill_alpha=1.0, # transparent line_color=None, fill_color='orange', ) circle.nonselection_glyph = Circle( fill_alpha=1.0, line_color=None, fill_color='orange', ) view = CDSView( source=source, filters=[IndexFilter( x[:100] )] ) circle_2 = plot_1.circle( x='x', y='y', size=5, fill_alpha=1, fill_color='blue', line_color=None, selection_color=Reds3[0], source=source, view=view, legend='FLAG 2', ) circle_2.selection_glyph = Circle( fill_alpha=1.0, # transparente line_color=None, fill_color='blue', ) circle_2.nonselection_glyph = Circle( fill_alpha=1.0, line_color=None, fill_color='blue', ) plot_1.legend.location = "top_left" plot_1.legend.click_policy="hide" circle_al…
type: Answer
answers question: http://stackoverflow.com/q/48812483

http://stackoverflow.com/q/48851749
tagged with: python
has answer: http://stackoverflow.com/a/48851784
favorite count: 0
has answer: http://stackoverflow.com/a/48851763
upvote count: 2
possible better answer: http://stackoverflow.com/a/48851784
has title: Searching for string in all columns of dataframe in Python
type: AnsweredQuestion
score: 2
has body: I am trying to find a string in all columns of a dataframe. import pandas as pd df = pd.DataFrame([['a', 'b'], ['c', 'd'], ['e', 'a']], columns=["A", "B"]) for col in df: df[col].str.contains('a') 0 True 1 False 2 False Name: A, dtype: bool 0 False 1 False 2 True Name: B, dtype: bool However, the code above returns only the booleans and not the format that I want (displays the rows and columns in table form), which can be achieved when searching in a specific column: df[df.A == 'a'] A B 0 a b Can anyone help?
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48851763
type: Question
answer count: 2
downvote count: 0
tagged with: pandas

http://stackoverflow.com/a/48919325
has comment: http://stackoverflow.com/comment/84908251
has comment: http://stackoverflow.com/comment/84846233
type: Answer
answers question: http://stackoverflow.com/q/48919263
upvote count: 2
score: 1
downvote count: 1
has body: Strip only removes leading and trailing whitespace. If you want to remove all whitespace (including all kinds of whitesapce like tabs, newlines, spaces, etc), the following will work import string def remove_whitespace(x): table = {ord(char): None for char in string.whitespace} return x.translate(table) data.rename(columns=remove_whitespace, inplace=True) As Brad mentions, the following can be used to the same effect. df.columns.str.replace(r'\s+', '')
has comment: http://stackoverflow.com/comment/84867307
has comment: http://stackoverflow.com/comment/84845238

http://stackoverflow.com/a/48952026
answers question: http://stackoverflow.com/q/48951939
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84912360
has comment: http://stackoverflow.com/comment/84914551
downvote count: 0
has body: try: subprocess.run(["lp", "-d", "HL-L2360D", "shopping.txt"]) flags and their values need to be different list items for subprocess calls.

http://stackoverflow.com/q/48940054
tagged with: ajax
score: 0
has title: How to upload file in react?
has body: I was trying to upload file in react, but failed because there was bad request. Here are some codes. uploadDoc = (e) =&gt; { e.preventDefault(); let file = e.target.files[0]; const url = 'https://api.agentcloud.com/api/leadfile/'; const formData = new FormData(); formData.append('lead', this.props.match.params.id); formData.append('file',file); const config = { headers: { 'content-type': 'multipart/form-data', 'Authorization': 'Token 90406829e9d311b117bb7e1484a81e7b7f9f4551' } } return post(url, formData, config); }
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84888944
tagged with: python
has answer: http://stackoverflow.com/a/48940132
type: Question
tagged with: reactjs
tagged with: javascript

http://stackoverflow.com/comment/84882923
score: 0
has text: `glob.glob('*_patients.dat')` ?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48937966

http://stackoverflow.com/q/48932940
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84873284
has comment: http://stackoverflow.com/comment/84873695
has title: Linked List Insert at Start Head Becomes Node, not Pointer? (Python)
score: 0
has comment: http://stackoverflow.com/comment/84873136
has comment: http://stackoverflow.com/comment/84873588
tagged with: data-structures
has comment: http://stackoverflow.com/comment/84873483
tagged with: logic
has comment: http://stackoverflow.com/comment/84873947
tagged with: python
tagged with: singly-linked-list
has body: I have seen several implementations for inserting a node at the start of a linked list. Most go something like this (Python): class Node: def __init__(data, next_node): self.__data = data self.__node = node def next(self): return self.__next def data(self): return self.__data class LinkedList: def __init__(head): self.__head = head def insert_beginning(self, new_data): new_node = Node(data, self.__head) self.__head = new_node Rephrased for clarify: The code is simplified for clarity so there are some methods missing, but my question is: the head of the link list is a pointer to the first node only (no data and therefore not an actual node) - so we assign this pointer value to the next variable of our new node, so that now new_node points to the previously first node. But from what I understand of the above code - when head is reassigned the value of new_node - it isn't pointing to that node, it contains that node. Does that make sense? Or have I some basic misunderstanding of how pointers work?
tagged with: linked-list
has comment: http://stackoverflow.com/comment/84872798
answer count: 0

http://stackoverflow.com/q/48818561
answer count: 1
has comment: http://stackoverflow.com/comment/84642680
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Python Error Number 22 for Certain Filenames (?)
has comment: http://stackoverflow.com/comment/84658862
has comment: http://stackoverflow.com/comment/84658829
downvote count: 1
has body: So I am using a library called Newspaper3k (documentation - https://newspaper.readthedocs.io/en/latest/), and have created the following glitchy program. It basically takes the newspaper articles and then proceeds to download and parse them (which takes place without error). In the next part of the program, it saves each article as a text file with a specific name. However, this program tends to "glitch" - while it will work for most articles, sometimes it will give me an "Error number 22". &gt;&gt;&gt; import newspaper &gt;&gt;&gt; bbc = newspaper.build('http://www.bbc.com/news') &gt;&gt;&gt; for x in bbc.articles: x.download() x.parse() content = x.text name = x.title authors = x.authors f = open ('%s,written by following: \n %s.txt' % (name,authors), 'w+') f.write(content) f.close() 32 142 135 146 126 138 137 175 13 164 133 177 Traceback (most recent call last): File "&lt;pyshell#47&gt;", line 7, in &lt;module&gt; f = open ('%s,written by following: \n %s.txt' % (name,authors), 'w+') OSError: [Errno 22] Invalid argument: 'BBC World News: 24 hour news TV channel,written by following: \n [].txt' The output, although fine at first, ends up glitching. Could someone please help me? I'm an amateur. Thanks.
type: Question
has comment: http://stackoverflow.com/comment/84641021
has comment: http://stackoverflow.com/comment/84648655
has comment: http://stackoverflow.com/comment/84642676
score: -1
has comment: http://stackoverflow.com/comment/84678663
has comment: http://stackoverflow.com/comment/84678673
has comment: http://stackoverflow.com/comment/84679229
upvote count: 0
has answer: http://stackoverflow.com/a/48827736

http://stackoverflow.com/comment/84906580
has text: You probably need to install with `pip3`.
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48949894

http://stackoverflow.com/comment/84688677
comment on: http://stackoverflow.com/a/48842072
score: 0
type: Comment
has text: I'm sorry I don't get your question... There is no dataframe as of yet...
type: AnswerComment

http://stackoverflow.com/comment/84876542
type: Comment
has text: After doing read_csv print the dataframe and post the output here - it's hard to say without seeing it
type: AnswerComment
comment on: http://stackoverflow.com/a/48932552
score: 0

http://stackoverflow.com/comment/103861099
comment on: http://stackoverflow.com/a/51115771
type: Comment
has text: Since you are using data augmentation the training set is theoretically of infinite size. I typically use steps_per_epoch = len(trainining_data)/batch_size in order to have a number of samples equal to the original size of the training set. The same applies to validation_steps whose value is set to use the entire validation set. Unfortunately if you use the validation split the data augmentation is applied also to the validation data.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48816785
score: 2
tagged with: anaconda
answer count: 0
has body: I have just updated my Anaconda environment on a 64 bit Linux server running Debian. I am now using version 2.1.2 of matplotlib. Now, whenever I want to import pyplot on python, python terminates and I get this error message: Python 3.5.4 |Anaconda, Inc.| (default, Nov 3 2017, 20:01:27) [GCC 7.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. readline: /etc/inputrc: line 18: term: unknown variable name readline: /etc/inputrc: line 18: term: unknown variable name &gt;&gt;&gt; import matplotlib &gt;&gt;&gt; from matplotlib import pyplot Inconsistency detected by ld.so: dl-open.c: 583: _dl_open: Assertion `_dl_debug_initialize (0, args.nsid)-&gt;r_state == RT_CONSISTENT' failed! Apparently there is some mix up in the libraries - but I do not really know how to get more information/solve this issue. What shall I do now? Edit: I was able to narrow down the source of this exception to the Qt interface of pyplot. When I force matplotlib to use pdf or Agg as the renderer, this error does not occur.
tagged with: matplotlib
type: Question
downvote count: 0
tagged with: linux
tagged with: shared-libraries
favorite count: 0
has title: Importing pyplot causes Inconsistency/Exception
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/q/48807942
downvote count: 0
has comment: http://stackoverflow.com/comment/84619663
has answer: http://stackoverflow.com/a/48809833
answer count: 1
favorite count: 0
tagged with: attributes
upvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/4075190
type: AnsweredQuestion
score: 2
tagged with: oop
accepted answer: http://stackoverflow.com/a/48809833
linked to: http://stackoverflow.com/q/6321940
tagged with: selenium
has title: Redirect unknown attributes
type: Question
has body: I'm building a custom class to add feautures to selenium.webdriver.Chrome on Python 3.6.2. from selenium import webdriver class MyChrome: def __init__(self): self.mydriver = webdriver.Chrome() So far, beside some custom methods I made myself, I used to overridden some selenium.webdriver.Chrome very standard methods like this: def get(self, url): self.mydriver.get(url) Since I don't want to waste time rewriting like that methods like get, find_element_by_xpath, etc... that already works fine for me I tried the following, as suggested here and here def __getattr__(self, name, *args, **kwargs): return getattr(self.mydriver, name)(*args, **kwargs) But when I run the following code from selenium import webdriver class MyChrome: def __init__(self): self.mydriver = webdriver.Chrome() def __getattr__(self, name, *args, **kwargs): return getattr(self.mydriver, name)(*args, **kwargs) chrome = MyChrome() chrome.get('https://stackoverflow.com/') I encounter the error Traceback (most recent call last): File "MyChrome.py", line 11, in &lt;module&gt; chrome.get('https://stackoverflow.com/') File "MyChrome.py", line 8, in __getattr__ return getattr(self.mydriver, name)(*args, **kwargs) TypeError: get() missing 1 required positional argument: 'url' How do I redirect calls to unknown methods called on my object chrome to it's instance variable self.driver?

http://stackoverflow.com/comment/84738431
score: 0
type: Comment
has text: Do you know if PostgreSQL does the same?
type: AnswerComment
comment on: http://stackoverflow.com/a/48867407

http://stackoverflow.com/q/48850940
type: Question
has body: I have a list where I need to extract index number of all elements based on given unique value. If I apply: test3 = ["P3","P35","P35","P3","P2"] actual_state = "P3" indexes = [n for n, x in enumerate(test3) if actual_state in x] this returns: [0, 1, 2, ,3] But output should be: [0, 3] P3 exists in P35 as well, renaming P35 won't help since I have nested list with thousands of inputs, any advice how can I extract this in desired way ? Thanks.
answer count: 2
upvote count: 2
has answer: http://stackoverflow.com/a/48850961
accepted answer: http://stackoverflow.com/a/48850961
has answer: http://stackoverflow.com/a/48851044
favorite count: 0
tagged with: python
tagged with: indices
tagged with: enumerate
score: 2
type: AnsweredQuestion
downvote count: 0
has title: Returning unique indices for given value in python
possible better answer: http://stackoverflow.com/a/48851044

http://stackoverflow.com/comment/84788700
type: QuestionComment
has text: `vstack` can't reorder the blocks. `stack` might be able to.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48891382

http://stackoverflow.com/a/48810959
score: 1
has body: You can use operator.itemgetter which allows you to fetch different combinations from you existing data-structure For example to fetch first element of each tuple use: &gt;&gt;&gt; from operator import itemgetter &gt;&gt;&gt; temp = [(1, 0, 1, 0, 2), (1, 0, 1, 0, 5), (1, 0, 2, 0, 2), (1, 0, 2, 0, 5)] &gt;&gt;&gt; list(map(itemgetter(0),temp)) &gt;&gt;&gt; [1, 1, 1, 1] To fetch second element &gt;&gt;&gt; list(map(itemgetter(1),temp)) &gt;&gt;&gt; [0, 0, 0, 0] To fetch first and second &gt;&gt;&gt; list(map(itemgetter(0,1),temp)) &gt;&gt;&gt; [(1, 0), (1, 0), (1, 0), (1, 0)]
answers question: http://stackoverflow.com/q/48810496
upvote count: 1
downvote count: 0
type: Answer

http://stackoverflow.com/q/48817008
has comment: http://stackoverflow.com/comment/84647534
tagged with: python-multithreading
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84700854
has title: How do I use threads on a generator (multiple threads per item) while keeping the order?
tagged with: python
tagged with: multithreading
upvote count: 1
has comment: http://stackoverflow.com/comment/84638166
has body: I have a code that is mimicking a REST API call (see below). For every key in the item of the generator, it needs to run a REST call. So in my example, a record could be {"a": 2, "b": 36, "c": 77} I need to run a REST call for every key (a, b, and c) individually, then output the results (which just negates the number): {"a": 2, "a_neg": -2, "b": 36, "b_neg": -36, "c": 77, "c_neg": -77} Right now my current code works for one key, but with multiple keys, it will repeat the items (so I'm getting triple the results for 3 keys). Also there is some funky race condition that occurs as well. I guess I could only keep the last record, but I'm not good with threads and concerned about thread safety or other advanced stuff. Here is an example output: {'a': 89, 'a_neg': -89, 'b': 69, 'c': 38} {'a': 89, 'a_neg': -89, 'b': 69, 'c': 38, 'c_neg': -38} {'a': 89, 'a_neg': -89, 'b': 69, 'b_neg': -69, 'c': 38, 'c_neg': -38} {'a': 90, 'a_neg': -90, 'b': 43, 'c': 16} {'a': 90, 'a_neg': -90, 'b': 43, 'c': 16, 'c_neg': -16} {'a': 90, 'a_neg': -90, 'b': 43, 'b_neg': -43, 'c': 16, 'c_neg': -16} {'a': 91, 'a_neg': -91, 'b': 49, 'b_neg': -49, 'c': 77, 'c_neg': -77} {'a': 91, 'a_neg': -91, 'b': 49, 'b_neg': -49, 'c': 77, 'c_neg': -77} {'a': 91, 'a_neg': -91, 'b': 49, 'b_neg': -49, 'c': 77, 'c_neg': -77} Finally here is my source code (you can run it yourself): #!/usr/bin/env python from concurrent.futures import ThreadPoolExecutor from time import sleep from pprint import pprint import random def records(): # simulates records generator for i in range(100): yield {"a": i, "b": random.randint(0,100), "c": random.randint(0,100)} def stream(records): threads = 8 pool = ThreadPoolExecutor(threads) def rest_api_lookup(record_dict): # simulates REST call :) sleep(0.1) key = record_dict["key"] record = record_dict["record"] record[key + "_neg"] = -record[key] return record def thread(records): chunk = [] for record in records: for key in record: chunk.append(pool.submit(rest_api_lookup, {"record": r…
type: Question
score: 1
has comment: http://stackoverflow.com/comment/84646741
has comment: http://stackoverflow.com/comment/84638203
has comment: http://stackoverflow.com/comment/84638233
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84638381
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84641561
has answer: http://stackoverflow.com/a/48821285
favorite count: 0
has comment: http://stackoverflow.com/comment/84645949

http://stackoverflow.com/q/48870758
tagged with: python
has comment: http://stackoverflow.com/comment/84752198
has comment: http://stackoverflow.com/comment/84751101
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/6068361
has comment: http://stackoverflow.com/comment/84751543
tagged with: multiprocessing
type: Question
linked to: http://stackoverflow.com/q/2196999
has answer: http://stackoverflow.com/a/48874737
accepted answer: http://stackoverflow.com/a/48874737
has comment: http://stackoverflow.com/comment/84746107
has comment: http://stackoverflow.com/comment/84751427
has title: Timeouts for multiprocessing?
tagged with: timeout
has comment: http://stackoverflow.com/comment/84747887
has comment: http://stackoverflow.com/comment/84751179
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84752841
linked to: http://stackoverflow.com/q/644073
answer count: 1
has comment: http://stackoverflow.com/comment/84746859
has body: I've searched StackOverflow and although I've found many questions on this, I haven't found an answer that fits for my situation/not a strong python programmer to adapt their answer to fit my need. I've looked here to no avail: kill a function after a certain time in windows Python: kill or terminate subprocess when timeout signal.alarm replacement in Windows [Python] I am using multiprocessing to run multiple SAP windows at once to pull reports. The is set up to run on a schedule every 5 minutes. Every once in a while, one of the reports gets stalled due to the GUI interface and never ends. I don't get an error or exception, it just stalls forever. What I would like is to have a timeout function that during this part of the code that is executed in SAP, if it takes longer than 4 minutes, it times out, closes SAP, skips the rest of the code, and waits for next scheduled report time. I am using Windows Python 2.7 import multiprocessing from multiprocessing import Manager, Process import time import datetime ### OPEN SAP ### def start_SAP(): print 'opening SAP program' ### REPORTS IN SAP ### def report_1(q, lock): while True: # logic to get shared queue if not q.empty(): lock.acquire() k = q.get() time.sleep(1) lock.release() break else: time.sleep(1) print 'running report 1' def report_2(q, lock): while True: # logic to get shared queue if not q.empty(): lock.acquire() k = q.get() time.sleep(1) lock.release() break else: time.sleep(1) print 'running report 2' def report_3(q, lock): while True: # logic to get shared queue if not q.empty(): lock.acquire() k = q.get() time.sleep(1) lock.release() break else: time.sleep(1) time.sleep(60000) #mimicking the stall for report 3 that takes longer than allotted time print 'running report 3' def report_N(q, lock): while True: # logic to get shared queue if not q.empty(): lock.acquire() k = q.get() time.sleep(1) lock.release() break else: time.sleep(1) print 'running report N' ### CLOSES SAP ### def close_SAP(): print 'closes SA…
has comment: http://stackoverflow.com/comment/84750611
linked to: http://stackoverflow.com/q/4158502
tagged with: windows

http://stackoverflow.com/comment/84737250
comment on: http://stackoverflow.com/a/48867031
score: 1
has text: Use a context manager so that the files is closed whatever happens. Also, I think the OP is thinking big files (see question comments) so loading the whole file might not be an option.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48821684
tagged with: average
tagged with: numpy
has answer: http://stackoverflow.com/a/48822047
tagged with: counter
type: UnansweredQuestion
downvote count: 0
score: 1
favorite count: 0
tagged with: multidimensional-array
type: Question
answer count: 2
has title: In Python. I have a list of ND arrays and I want to count duplicate arrays in order to calculate an Average for each Duplicate array value
linked to: http://stackoverflow.com/q/16970982
has answer: http://stackoverflow.com/a/48822070
upvote count: 1
tagged with: python
has body: I have a list of ND arrays(vectors), each vector has a (1,300) shape. My goal is to find duplicate vectors inside a list, to sum them and then divide them by the size of a list, the result value(a vector) will replace the duplicate vector. For example, a is a list of ND arrays, a = [[2,3,1],[5,65,-1],[2,3,1]], then the first and the last element are duplicates. their sum would be :[4,6,2], which will be divided by the size of a list of vectors, size = 3. Output: a = [[4/3,6/3,2/3],[5,65,-1],[4/3,6/3,2/3]] I have tried to use a Counter but it doesn't work for ndarrays. What is the Numpy way? Thanks.

http://stackoverflow.com/q/48929072
linked to: http://stackoverflow.com/q/31428581
linked to: http://stackoverflow.com/q/44334950
has answer: http://stackoverflow.com/a/48930131
accepted answer: http://stackoverflow.com/a/48930131
has title: IncrementalPCA & partial_fit - number of components
tagged with: machine-learning
has body: I work with python and about 4000 images of watches (examples: watch_1, watch_2). The images are rgb and their resolution is 450x450. My aim is to find the most similar watches among them. For this reason I am using IncrementalPCA and partial_fit of scikit_learn to handle these big data with my 26GB RAM (see also: SO_Link_1, SO_Link_2). My source code is the following: import cv2 import numpy as np import os from glob import glob from sklearn.decomposition import IncrementalPCA from sklearn import neighbors from sklearn import preprocessing data = [] # Read images from file # for filename in glob('Watches/*.jpg'): img = cv2.imread(filename) height, width = img.shape[:2] img = np.array(img) # Check that all my images are of the same resolution if height == 450 and width == 450: # Reshape each image so that it is stored in one line img = np.concatenate(img, axis=0) img = np.concatenate(img, axis=0) data.append(img) # Normalise data # data = np.array(data) Norm = preprocessing.Normalizer() Norm.fit(data) data = Norm.transform(data) # IncrementalPCA model # ipca = IncrementalPCA(n_components=6) length = len(data) chunk_size = 4 pca_data = np.zeros(shape=(length, ipca.n_components)) for i in range(0, length // chunk_size): ipca.partial_fit(data[i*chunk_size : (i+1)*chunk_size]) pca_data[i * chunk_size: (i + 1) * chunk_size] = ipca.transform(data[i*chunk_size : (i+1)*chunk_size]) # K-Nearest neighbours # knn = neighbors.NearestNeighbors(n_neighbors=4, algorithm='ball_tree', metric='minkowski').fit(data) distances, indices = knn.kneighbors(data) print(indices) However when I run this program for start with 40 images of watches I get the following error when i = 1: ValueError: Number of input features has changed from 4 to 6 between calls to partial_fit! Try setting n_components to a fixed value. However, it is obvious that I set n_components to 6 when coding ipca = IncrementalPCA(n_components=6) but for some reason ipca considers chunk_size = 4 as the number of components …
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
type: Question
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0

http://stackoverflow.com/a/48861931
downvote count: 0
answers question: http://stackoverflow.com/q/48861286
score: 4
type: Answer
has body: What you need is template engine such as Jinja2. from flask import Flask, render_template app = Flask(__name__) number = "7" @app.route('/') def index(): return render_template('index.html', number=number) if __name__ == '__main__': app.run(debug=True) and then create a folder named templates in the same folder in which this script is present. Create your own template under templates and then render them in your app. # templates/index.html Welcome to Python Flask Web Server, your lucky number is: {{ number }}! Steve Wigmore Trained me! Cash me ousside How bou dat? <img style='margin: 0 auto; display: block;' src='https://www.maxim.com/.image/t_share/MTQ3MzM2ODA3NjExMTE0OTU4/cash-me-outside-promo.jpg' For more information about templates in Flask, see https://www.tutorialspoint.com/flask/flask_templates.htm
upvote count: 4

http://stackoverflow.com/comment/84638306
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48816693
has text: @Aura I was going to help out a bit but now I see there are two answers that give you something to continue with.
score: 0

http://stackoverflow.com/a/48948636
answers question: http://stackoverflow.com/q/48948539
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84903819
has body: call group only if there is a match. res = re.search(r"&lt;i&gt;(.*?)&lt;/i&gt;", str(englishWord)) # if there is a match if res: englishWord = res.group(1) As pointed out in the comments, re.search returns None when no match is found. Link : https://docs.python.org/3/library/re.html#re.search
has comment: http://stackoverflow.com/comment/84904741
downvote count: 0
has comment: http://stackoverflow.com/comment/84904764
score: 1
accepted answer of: http://stackoverflow.com/q/48948539

http://stackoverflow.com/q/48857123
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48857225
has comment: http://stackoverflow.com/comment/84717869
type: UnansweredQuestion
downvote count: 1
type: Question
has title: Fixing issue with program that calculates grade average with option of dropping lowest grade
score: -1
has answer: http://stackoverflow.com/a/48857222
answer count: 2
upvote count: 0
has body: I need to create a program that calculates grade averages and provides the option of dropping the lowest grade. The program must allow the user to enter the number of students and number of grades per student. I keep getting "'int' object is not iterable" with respect to the "lowest" component. Please help. def main(): num_students=eval(input("Please enter the number of students you will have grades for: ")) num_grades=eval(input("Please enter the number of grades per student: ")) gcounter=0 scounter=1 drop=input("Do you wish to drop the lowest grade? Type yes or no: ") if drop=="no" or drop=="No" or drop=="n" or drop=="N": while scounter&lt;=num_students: name=input("Please enter the student's name: ") grades_total=0 while gcounter&lt;num_grades: getgrade=eval(input("Enter grade: ")) grades_total=grades_total+getgrade gcounter=gcounter+1 print("The average grade for ", name, "is ", grades_total/gcounter) num_students=num_students-1 scounter=scounter+1 gcounter=0 elif drop=="yes" or drop=="Yes" or drop=="y" or drop=="Y": while scounter&lt;=num_students: name=input("Please enter the student's name: ") grades_total=0 while gcounter&lt;num_grades: getgrade=eval(input("Enter grade, including the lowest: ")) lowest = min(getgrade) grades_total=grades_total+(getgrade-lowest) gcounter=gcounter+1 print("The average grade for ", name, "is ", grades_total/(gcounter-1)) num_students=num_students-1 scounter=scounter+1 gcounter=0 main()

http://stackoverflow.com/q/48945739
downvote count: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48946836
tagged with: python
has title: Python import iteration, sys.path
has answer: http://stackoverflow.com/a/48946836
score: 2
type: AnsweredQuestion
tagged with: python-3.x
upvote count: 2
tagged with: sys
type: Question
has body: So I was wondering, at this point in time I'm reading a book about Python. The book explains the following: The import algorithm To truly understand namespace packages, we have to look under the hood to see how the import operation works in 3.3. During imports, Python still iterates over each directory in the module search path, sys.path, just as in 3.2 and earlier. My question is: How is python able to iterate through sys.path when sys is not imported. Also if python is able to see sys without import to iterate through sys.path why do we need to import sys in our code? &gt;&gt;&gt; sys NameError: name 'sys' is not defined. &gt;&gt;&gt; import sys &gt;&gt;&gt; sys &lt;module 'sys' (built-in)&gt;
tagged with: import

http://stackoverflow.com/q/48899234
tagged with: encoder-decoder
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48899306
tagged with: recurrent-neural-network
upvote count: 1
answer count: 1
tagged with: tensorflow
tagged with: sequence-to-sequence
has body: I know how to build an encoder using dynamic rnn in Tensorflow, but my question is how can we use it for decoder? Because in decoder at each time step we should feed the prediction of previous time step. Thanks in advance!
accepted answer: http://stackoverflow.com/a/48899306
has title: How to build a decoder using dynamic rnn in Tensorflow?

http://stackoverflow.com/a/48935912
downvote count: 0
has comment: http://stackoverflow.com/comment/84878591
has comment: http://stackoverflow.com/comment/84878672
has comment: http://stackoverflow.com/comment/84879971
answers question: http://stackoverflow.com/q/48935775
has body: You must install liblzo2-dev in debian base image and install lzo-devel in centos base image.
type: Answer
has comment: http://stackoverflow.com/comment/84879508
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/122491082
has comment: http://stackoverflow.com/comment/84878659

http://stackoverflow.com/q/48830946
has answer: http://stackoverflow.com/a/58310832
has answer: http://stackoverflow.com/a/73444348
has answer: http://stackoverflow.com/a/78957897
answer count: 7
favorite count: 0
has title: how to nest multiple python function to create a sort of pipeline?
has answer: http://stackoverflow.com/a/48831100
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/78358675
tagged with: python
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/48831052
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48831043
has body: Hello i have 3 functions f1(), f2() and f3(). The output of the previous is the input of the next. meaning output = f3(f2(f1(data))). instead of writing def outp(data): o1 = f1(data) o2= f2(o1) o3 = f3(02) return o3 output=outp(data) is there a way to this by simply providing a list of functions to some other general function and let it handle the chaining together?

http://stackoverflow.com/q/48820510
upvote count: 3
tagged with: google-api-python-client
possible better answer: http://stackoverflow.com/a/62439425
favorite count: 0
tagged with: google-drive-api
has answer: http://stackoverflow.com/a/62439425
tagged with: google-api
has title: Empty Google Drive Trash with Python
tagged with: python
type: AnsweredQuestion
score: 3
downvote count: 0
accepted answer: http://stackoverflow.com/a/48820702
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48820702
has body: I am trying to empty my google drive trash bin with the API, but with no luck. I have tried using the requests library, and the script runs through without errors, but the drive trash is not deleted. I have been able to get files via the API, but not delete or empty the trash. Seems I should be able to just send an http request, but this is proving far more difficult for me than it seems it should be. Any advice would be greatly appreciated. Here is what I have. I am not even getting a json response. from __future__ import print_function import httplib2 import os import requests from apiclient import discovery from oauth2client import client from oauth2client import tools from oauth2client.file import Storage try: import argparse flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args() except ImportError: flags = None SCOPES = 'https://www.googleapis.com/auth/drive' CLIENT_SECRET_FILE = 'C:\Scripts\Link Expiration\client_secret.json' APPLICATION_NAME = 'Drive API Delete Trash' def get_credentials(): """Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential. """ home_dir = os.path.expanduser('~') credential_dir = os.path.join(home_dir, '.credentials') if not os.path.exists(credential_dir): os.makedirs(credential_dir) credential_path = os.path.join(credential_dir, 'drive-python-quickstart.json') store = Storage(credential_path) credentials = store.get() if not credentials or credentials.invalid: flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES) flow.user_agent = APPLICATION_NAME if flags: credentials = tools.run_flow(flow, store, flags) else: # Needed only for compatibility with Python 2.6 credentials = tools.run(flow, store) print('Storing credentials to ' + credential_path) return credentials def main(): credentials = get_credentials() http = credentials.authorize(httplib2.Ht…

http://stackoverflow.com/comment/84666641
type: Comment
type: QuestionComment
has text: @wwii that question is more related to a student task. This one, imo, is pretty common with plots, for example I you want to reduce the indexes to a certain range.
comment on: http://stackoverflow.com/q/48831175
score: 0

http://stackoverflow.com/comment/84764121
type: AnswerComment
has text: @now I see.. the re.findall returns each subgroup wrapped in ( ).. and moreover, the each ? question-marks are important which makes the expression non-greedy.. which abridges the part expressed in [\W]. if I didn't use ? at each subgroup, it returns only one tuple
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48879038

http://stackoverflow.com/comment/84881865
score: 2
comment on: http://stackoverflow.com/q/48937457
type: Comment
type: QuestionComment
has text: You aren't using PEDMAS. Integer division is still division.

http://stackoverflow.com/comment/84858614
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48926182
score: 0
has text: Not sure if understand, `N=3` is for shift 3 days.

http://stackoverflow.com/a/61296104
answers question: http://stackoverflow.com/q/48897873
has body: Following this hint, one can use searchsorted to find an index of the element, that is close (lower) to a percentile/quantile value. See example below: import numpy as np def find_index_left(xs, v): return np.searchsorted(xs, v, side='left') - 1 def find_index_quantile(xs, q): v = np.quantile(xs, q) return find_index_left(xs, v) xs = [5, 10, 11, 15, 20] assert np.quantile(xs, 0.9) == 18.0 assert find_index_left(xs, 18) == 3 # zero-based index for forth element assert find_index_quantile(xs, 0.9) == 3 Note xs has to be sorted.
type: Answer
score: 0

http://stackoverflow.com/comment/84819004
has text: Please read the wiki pages, there is no relationship between the code you typed and what you want. If you are going to send data without connecting, you should use a lower-level socket connection. The methods you specify cannot be broadcast!
comment on: http://stackoverflow.com/q/48906516
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84761787
type: QuestionComment
type: Comment
has text: @eryksun what if there will be a quotation in generated_password value?How do I put generated_password and password_to_set values into row string?
comment on: http://stackoverflow.com/q/48878287
score: 0

http://stackoverflow.com/a/48934275
answers question: http://stackoverflow.com/q/48908775
has body: sudo chown -R $(whoami) /usr/local This will give permission to create the symlinks, hence solving the issue with linking.
has comment: http://stackoverflow.com/comment/88827446
has comment: http://stackoverflow.com/comment/90183585
upvote count: 5
has comment: http://stackoverflow.com/comment/90183706
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48908775
type: Answer

http://stackoverflow.com/comment/84632055
type: Comment
type: QuestionComment
score: 2
has text: Show us your attempt at solving this yourself.
comment on: http://stackoverflow.com/q/48814204

http://stackoverflow.com/q/48852696
type: Question
answer count: 2
has body: I'm using Jupyter Notebook and I'm trying to import tensorflow. Here's the error I get: --------------------------------------------------------------------------- ModuleNotFoundError Traceback (most recent call last) <ipython-input-15-64156d691fe5> in <module>() ----> 1 import tensorflow as tf ModuleNotFoundError: No module named 'tensorflow' I'm hosting the notebook by typing jupyter notebook in my virtual environment: (labs) Sahands-MBP:part1 sahandzarrinkoub$ jupyter notebook tensorflow is definitely installed in the virtual environment: (labs) Sahands-MBP:part1 sahandzarrinkoub$ python Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33) [GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import tensorflow >>> So why isn't it found? Where does jupyter look for packages? I've even installed tensorflow outside of my virtualenv.
upvote count: 3
linked to: http://stackoverflow.com/q/47824131
has answer: http://stackoverflow.com/a/51484234
tagged with: jupyter
accepted answer: http://stackoverflow.com/a/48867036
tagged with: jupyter-notebook
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48867036
type: AnsweredQuestion
score: 3
has title: Cannot import tensorflow in Jupyter Notebook
downvote count: 0
possible better answer: http://stackoverflow.com/a/51484234
tagged with: tensorflow

http://stackoverflow.com/comment/129454769
has text: worked for me even by adding only "C:\Program Files\Git\bin\bash.exe"
comment on: http://stackoverflow.com/a/66523735
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84627933
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48811056
has text: @AlexW sorry mis-copied from terminal: `for val, count in counter.items(): ...`
type: AnswerComment

http://stackoverflow.com/comment/84929551
type: AnswerComment
has text: Save the collection once in a more permanent manner (e.g. using list(g) once first and storing it)
type: Comment
comment on: http://stackoverflow.com/a/48961732
score: 1

http://stackoverflow.com/comment/84713043
score: 0
type: Comment
type: QuestionComment
has text: x is just a variable i used. The data is just the following: {"Wireless Internet","Air conditioning",Kitchen,Heating,"Family/kid friendly",Essentials,"Hair dryer",Iron,"translation missing: en.hosting_amenity_50"}
comment on: http://stackoverflow.com/q/48854669

http://stackoverflow.com/q/48887096
has answer: http://stackoverflow.com/a/48887821
has title: ROC curve for discrete classifier using scikit learn
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: scikit-learn
favorite count: 0
tagged with: roc
type: Question
accepted answer: http://stackoverflow.com/a/48887821
tagged with: python
upvote count: 3
tagged with: classification
answer count: 1
has body: I'm having a little trouble conceptually understanding how the ROC function in scikit learn generates the true positive and false positive rates. I used the BC scikit learn data and built a decision tree around 2 random features. from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn import tree import numpy as np data = load_breast_cancer() X = data.data[:, [1,3]] y = data.target # Splitting data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33,random_state=0) # Training tree bc_tree = tree.DecisionTreeClassifier(criterion="entropy").fit(X_train, y_train) # Predictions bc_pred = bc_tree.predict(X_test) # Score bc_tree.score(X_test, y_test) # Confusion matrix from sklearn.metrics import confusion_matrix metrics.confusion_matrix(y_test, bc_pred) # True positive = 0.83 # ROC curve fpr_tree, tpr_tree, thresholds_tree = metrics.roc_curve(y_test, bc_pred) # True positive rate ROC tpr_tree # 0.91 The confusion matrix is looks like this: [[ 55, 12] [ 11, 110]] According to my calculations, the true positive rate is: 55/(55+11) = .83 According to the ROC curve implemented by scikit learn, the true positive rate is 0.92. How did it calculate this number, and why aren't my calculations matching up? What am I missing?

http://stackoverflow.com/a/48929505
score: 0
answers question: http://stackoverflow.com/q/48929153
has body: I think you don't need more than the main mysite, BUT, at the django documents, have a session that says: If your background is in plain old PHP (with no use of modern frameworks), you’re probably used to putting code under the Web server’s document root (in a place such as /var/www). With Django, you don’t do that. It’s not a good idea to put any of this Python code within your Web server’s document root, because it risks the possibility that people may be able to view your code over the Web. That’s not good for security. Put your code in some directory outside of the document root, such as /home/mycode. This model may have been designed with focus on safety. Some files in mysite could be used to control things in another apps, so i think that is a 'best pratice' to follow this model. Font
type: Answer

http://stackoverflow.com/q/48832107
has answer: http://stackoverflow.com/a/48832329
accepted answer: http://stackoverflow.com/a/48832329
has title: How to delete record from dbf file using python dbf module?
has answer: http://stackoverflow.com/a/69852385
tagged with: python
linked to: http://stackoverflow.com/q/48839421
type: AnsweredQuestion
tagged with: visual-foxpro
type: Question
possible better answer: http://stackoverflow.com/a/69852385
tagged with: dbf
score: 0
answer count: 2
has body: I'm trying to write/delete records in a visual foxpro 6 dbf file, using python 2.7 and the dbf package: import dbf tbl = dbf.Table('test.dbf') tbl.open() rec = tbl[0] print(rec.__class__) rec.delete_record() Result: &lt;class 'dbf.ver_2.Record'&gt; Traceback (most recent call last): File "C:/Python/Projects/test/test.py", line 11, in &lt;module&gt; rec.delete_record() File "C:\Python\Projects\test\venv\lib\site-packages\dbf\ver_2.py", line 2503, in __getattr__ raise FieldMissingError(name) dbf.ver_2.FieldMissingError: 'delete_record: no such field in table' Here is the documentation for that package: http://pythonhosted.org/dbf/ The record object really does not have this method, but it is documented. The table is opened in read-write mode. (But it is also true that the Table() constructor should return an opened table, but it returns a closed table instead.) What am I doing wrong? The biggest problem is that there are no other options. The only other package I know of is "dbfpy" but that does not handle vfoxpro 6 tables, and it does not handle different character encodings.

http://stackoverflow.com/a/48869389
score: 2
answers question: http://stackoverflow.com/q/48853183
downvote count: 0
upvote count: 2
has body: Add below to your vimrc let g:ycm_autoclose_preview_window_after_completion = 0 or Default. The optional g:ycm_autoclose_preview_window_after_completion is 0 by default.
has comment: http://stackoverflow.com/comment/84749068
type: Answer

http://stackoverflow.com/a/48912284
accepted answer of: http://stackoverflow.com/q/48912253
has comment: http://stackoverflow.com/comment/84830958
answers question: http://stackoverflow.com/q/48912253
upvote count: 81
type: Answer
has comment: http://stackoverflow.com/comment/87818187
has comment: http://stackoverflow.com/comment/84830884
score: 77
has body: requests library doesn't come by default in lambda. It looks like you are trying to import it in your function / library somewhere. To import it, you need the following line: from botocore.vendored import requests Alternatively, you would need to zip the requests library in the root of your zip file. EDIT: There may be a dependency in one of your libraries that may need this. To overcome this, install requests in your application zip. To do this, run the following command in the root directory of your application: pip install requests -t ./. A better way would be to create a file called requirements.txt and add all the dependencies in there. Use virtualenv to install all the packages defined in the requirements.txt using: pip install -r requirements.txt -t ./ UPDATE: Starting 10/21/19, the vendored version of the requests library in botocore will be removed. Refer this blog post for more details.
has comment: http://stackoverflow.com/comment/87911161
has comment: http://stackoverflow.com/comment/99519341
has comment: http://stackoverflow.com/comment/104655710
has comment: http://stackoverflow.com/comment/89301093
has comment: http://stackoverflow.com/comment/84833508
downvote count: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/84788022
type: QuestionComment
comment on: http://stackoverflow.com/q/48891298
score: 1
has text: Dictionaries **have no order** in Python, I am afraid you'll have to sort it once creating a list or something of that approach...
type: Comment

http://stackoverflow.com/comment/84784149
score: 0
comment on: http://stackoverflow.com/q/48887664
type: Comment
type: QuestionComment
has text: I run it again on visual studio with python2.6.9 and nothing turns out , thanks anyway, sorry again for my stupid question failing to express my purpose, I just expect to get this code fixed and could see the result as dealing with it by myself is too hard, and I will try to find a new book and explore more about pygame .Thanks a lot !

http://stackoverflow.com/a/49070276
has comment: http://stackoverflow.com/comment/136255545
has body: Update (April / 2021): It's possible to write formulas in Colab just putting them between $ symbols, with no need to import libraries: $F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx$ Old answer As an alternative, the following description should work on text cell on Colab. \begin{equation} F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx \end{equation}
type: Answer
answers question: http://stackoverflow.com/q/48856683
score: 10
upvote count: 11
has comment: http://stackoverflow.com/comment/94455931
downvote count: 1
has comment: http://stackoverflow.com/comment/102882428
has comment: http://stackoverflow.com/comment/108615030

http://stackoverflow.com/comment/84822891
type: QuestionComment
comment on: http://stackoverflow.com/q/48908406
score: 0
has text: So you're saying `o` is of type `DerivedClass`, yet `o.__class__.__name__` is `BaseClass`? I don't think that's possible. Show us some code.
type: Comment

http://stackoverflow.com/comment/84875241
type: AnswerComment
score: 0
type: Comment
has text: ok, let's try with some refactoring: after `else`, `edycja_pracownika = CudzoziemiecForm(instance=link_pracownik)` do not need `request.user` there unless you have a good reason for that. `link_pracownik = edycja_pracownika.save(commit=False)` can omit commit and remove the `link_pracownik.save()` (save will work if we arrive there). After that, instead of `return render([..])` I will do `return HttpResponseRedirect(reverse('szczegoly_pracownik', args=(link_pracownik.id))` because we want to show the detail page in his proper url. Don't forget the imports for HttpResponseRedirect and reverse.
comment on: http://stackoverflow.com/a/48933841

http://stackoverflow.com/a/48855548
has comment: http://stackoverflow.com/comment/84714905
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84714774
has comment: http://stackoverflow.com/comment/84714798
upvote count: 1
has comment: http://stackoverflow.com/comment/84714553
downvote count: 1
has comment: http://stackoverflow.com/comment/84716476
has comment: http://stackoverflow.com/comment/84714574
answers question: http://stackoverflow.com/q/48855492
has body: The problem you are expressing is a Directed Graph. You can use the networkx library to work with these like: Code: def sort_nodes(node_list): import networkx as nx graph = nx.DiGraph(node_list) sorted_nodes = [y[1] for y in sorted( (len(neighbors), node) for node, neighbors in graph.pred.items())] return sorted_nodes Test Code: test_data = ( dict( input=[[70, 62], [31, 62], [62, 71], [70, 31], [70, 71], [31, 71]], desired_result=[70, 31, 62, 71]), dict( input=[[48, 33], [56, 33], [56, 48]], desired_result=[56, 48, 33]), ) import networkx as nx for test in test_data: nodes = sort_nodes(test['input']) print(nodes) assert nodes == test['desired_result'] Results: [70, 31, 62, 71] [56, 48, 33]

http://stackoverflow.com/q/48874733
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84754020
score: 6
tagged with: curve-fitting
tagged with: python
downvote count: 0
linked to: http://stackoverflow.com/q/48894235
has comment: http://stackoverflow.com/comment/84754532
type: Question
tagged with: gaussian
upvote count: 6
has answer: http://stackoverflow.com/a/48989884
has title: fit (triple-) gauss to data python
answer count: 2
has body: The short version of my problem is the following: I have a histogram of some data (density of planets) which seems to have 3 peeks. Now I want to fit 3 gaussians to this histogram. I am expecting this outcome. I used different methods to fit my gauss: curve_fit, least square and GaussianMixture from sklearn.mixture. With Curve_fit I get a pretty good fit but it isn't good enough if you compare it to my expected outcome. With least square I get a "good fit" but my gaussians are nonsense, and with GaussianMixture I don't get anywhere, because I can't really adept the codes I've seen in Examples to my problem. At this point I have three questions: Most important: How can I get a better fit for my third gaussian? I already tried to adjust the initial values for p0, but then the gaussian becomes even worst or it doesn't find the parameters at all. What is wrong with my least-square Code? Why does it give me such strange gaussians? And is there a way to fix this? My Guess: Is it because least-square does everything to minimize the error between fit and actual data? How would I do the whole thing with GaussianMixture? I found this post but couldn't adapt it to my problem. I really want to understand how to make fits properly, since I will have to do them a lot in the future. The problem is that I am not very good in statistics and just started programming in python. Here are my three different codes: Curvefit import numpy as np import math import matplotlib.pyplot as plt from scipy.optimize import curve_fit hist, bin_edges = np.histogram(Density, bins=np.logspace(np.log10(MIN), np.log10(MAX), 32)) bin_centres = (bin_edges[:-1] + bin_edges[1:])/2 # Define model function to be used to fit to the data above: def triple_gaussian( x,*p ): (c1, mu1, sigma1, c2, mu2, sigma2, c3, mu3, sigma3) = p res = np.divide(1,x)*c1 * np.exp( - (np.log(x) - mu1)**2.0 / (2.0 * sigma1**2.0) ) \ + np.divide(1,x)*c2 * np.exp( - (np.log(x) - mu2)**2.0 / (2.0 * sigma2**2.0) ) \ + np.divide(1,x)*c3 *…
favorite count: 0
has answer: http://stackoverflow.com/a/48877215
linked to: http://stackoverflow.com/q/41631161

http://stackoverflow.com/q/48956036
type: Question
accepted answer: http://stackoverflow.com/a/48969245
answer count: 1
downvote count: 0
favorite count: 0
has title: How do I edit CodeMirror with Selenium in Python?
has answer: http://stackoverflow.com/a/48969245
tagged with: python
tagged with: codemirror
type: AnsweredQuestion
score: 3
has body: I keep getting the error message below every time I try to insert text into CodeMirror on my webpage. Does anyone know how to successfully edit codemirror with selenium? WebDriverException: Message: unknown error: Cannot read property 'setValue' of undefined This is my Selenium-Python code def click_component_script_editor(self): driver = self.driver line18Edit = self.driver.find_element(By.XPATH, "//html//div[@class='CodeMirror-line']//div[18]/pre[1]") driver.execute_script("arguments[0].CodeMirror.setValue(arguments[1]);", line18Edit, "foo.bar")
upvote count: 3
tagged with: selenium

http://stackoverflow.com/comment/84755788
comment on: http://stackoverflow.com/q/48875501
score: 0
type: Comment
type: QuestionComment
has text: So I don't see any problems in this case - you can create a corresponding dictionary from this file or read it into Pandas Series (with corresponding index) or a DataFrame. 200Mb text should easily fit into memory. Accessing dictionary values by keys is has `O(1)` complexity - si it will be pretty fast...

http://stackoverflow.com/comment/84842560
type: QuestionComment
comment on: http://stackoverflow.com/q/48917967
has text: I am not so sure but I think the line "mboa = content.replace(vaga2,vaga,1)" is causing the error because it replacing stuff in mboa. So it takes out everything but the last line ??
score: 0
type: Comment

http://stackoverflow.com/a/53602906
score: 0
has body: Try the following python code. =) flag = True lst=[] while(flag): num = float(raw_input("Enter a number. ")) lst+=[num] if(num==-88.0): flag = False print "Average of numbers: ", round( (sum(lst[:-1])/len(lst[:-1])) , 2)
type: Answer
answers question: http://stackoverflow.com/q/48898729

http://stackoverflow.com/a/48858482
type: Answer
score: 0
has body: Do not use eval in this way, it poses a security risk. There are at least 2 viable options: Use df.query, as explained by @jezrael. Use a 3rd party library like pandasql, which will let you apply SQL-like queries, e.g. pysqldf("SELECT * FROM df WHERE Counterparty &lt;&gt; 'bank';")
answers question: http://stackoverflow.com/q/48850322

http://stackoverflow.com/comment/84860456
comment on: http://stackoverflow.com/q/48921619
type: Comment
type: QuestionComment
has text: Possible duplicate [here](https://stackoverflow.com/questions/3024153/how-to-expire-session-due-to-inactivity-in-django) and [here](https://stackoverflow.com/questions/14830669/how-to-expire-django-session-in-5minutes).
score: 0

http://stackoverflow.com/q/48903633
upvote count: 1
has comment: http://stackoverflow.com/comment/84812631
type: Question
has comment: http://stackoverflow.com/comment/84817009
tagged with: int
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x
has title: Pythonic integer multiplication and addition
has body: I am finding problems in when I should use *= or be explicit in using my code. I'm trying to do simple integer multiplication and addition in Python. So to take a number, multiply it by 3 and add 1. Is there a specific situation where I should use: number *= 3 number += 1 Or number = (number * 3) + 1 Is there a difference between the two, or is this a matter of personal preference?
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48906245
score: 1
tagged with: multiplication

http://stackoverflow.com/comment/90905304
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48819346
score: 0
has text: Historical note: the initial motivation for scikit-cuda was to facilitate the use of certain GPU-based functions provided by CULA that were not available in other libraries at the time (e.g., svd) but were in the academic edition of CULA. Although CULA is still commercially available, EM Photonics no longer distributes an academic edition.

http://stackoverflow.com/a/48897921
downvote count: 0
has comment: http://stackoverflow.com/comment/84801341
score: 5
has comment: http://stackoverflow.com/comment/84801388
has comment: http://stackoverflow.com/comment/84801355
has comment: http://stackoverflow.com/comment/84801336
upvote count: 5
has comment: http://stackoverflow.com/comment/84801376
type: Answer
has body: The constants True and False are unique, as the specification guarantees they are the only instances of bool. That is, if you have two variables which were both initialized with True or a true boolean expression such as 1 == 1,* then they will compare identical with is. The same is true for False. However, True == 1 and True is not 1. This is because booleans are a subclass of int. Boolean values will never compare identical to "regular" integers with is, but the type difference is ignored for comparison with integers, floating point values, and other numeric types, as is standard behavior for the numeric hierarchy. * Be careful with more elaborate boolean expressions. In particular, and and or always return one of their operands, and do not coerce to boolean (unless their operands are already booleans). (Incidentally, Python contains exactly two other singletons in addition to True, False, and None, namely Ellipsis and NotImplemented. Each type object is also more or less unique; if you write x = int; y = int, then x and y will compare identical with is, because there is only one object which represents the int type. This can be used if you are creating your own type hierarchy and want to avoid having objects compare equal to their subclasses like booleans do with integers. In other cases, it is of marginal benefit compared to isinstance() or issubclass(), which better respect the Liskov substitution principle.)
answers question: http://stackoverflow.com/q/48897561

http://stackoverflow.com/q/48924730
has answer: http://stackoverflow.com/a/48924775
type: Question
has title: Python/ Pandas CSV Parsing / search for value
possible better answer: http://stackoverflow.com/a/48924817
score: 0
has answer: http://stackoverflow.com/a/48925020
tagged with: pandas
upvote count: 1
tagged with: http://stackoverflow.com/tag/csv
downvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48924965
answer count: 4
favorite count: 0
has body: I am using pandas to parse a CSV File. The CSV file contains a value for each day of the last 10 years. The CSV looks like this: production,day,year 5.0,50,2015 80.0,51,2015 190.0,52,2015 10.0,53,2015 . . . 2.0,50,2016 2.0,51,2016 40.0,52,2016 20.0,53,2016 . . i use the following code: def calcAverageFirstYears(productionCSV): myFile = pd.read_csv(productionCSV) result = myFile[myFile['day']==52] print(result) So I get this reslut: production day year 2 190.0 52.0 2015.0 9 40.0 52.0 2016.0 16 60.0 52.0 2017.0 23 6.0 52.0 2018.0 How can I calculte the average of these values? How can I calculte the average of the 2015 and 2016? Thank you for your help
has answer: http://stackoverflow.com/a/48924817
accepted answer: http://stackoverflow.com/a/48924775
type: AnsweredQuestion

http://stackoverflow.com/q/48935271
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48935854
has answer: http://stackoverflow.com/a/48935391
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/48935343
has answer: http://stackoverflow.com/a/48935343
tagged with: nameerror
has title: Fixing a NameError
upvote count: 0
accepted answer: http://stackoverflow.com/a/48935391
favorite count: 0
has answer: http://stackoverflow.com/a/48935348
tagged with: python
answer count: 4
has body: I am writing a program to play tic tac toe with two players. I have gotten the base code done (albeit quite innefficiently), but I keep getting an error saying player2 is not defined. I have tried many things to fix the error but was wondering if yall had any ideas. It is getting caught on the first player1 == player2 condition. Here is the code: def main(): board1 = [" "," "," "] board2 = [" "," "," "] board3 = [" "," "," "] game(board1,board2,board3) def play1(): global player1 player1 = int(input("Player 1, where would you like to move? ")) return player1 def play2(): global player2 player2 = int(input("Player 2, where would you like to move? ")) return player2 def game(brd1,brd2,brd3): isvalid = False while(not(isvalid)): play1() try: if player1 == player2: print("You can't both go to the same spot!") except NameError: if player1 == 0: brd1.pop(0) brd1.insert(0,"x") print(brd1) print(brd2) print(brd3) elif player1 == 1: brd1.pop(1) brd1.insert(1,"x") print(brd1) print(brd2) print(brd3) elif player1 == 2: brd1.pop(2) brd1.insert(2,"x") print(brd1) print(brd2) print(brd3) elif player1 == 3: brd2.pop(0) brd2.insert(0,"x") print(brd1) print(brd2) print(brd3) elif player1 == 4: brd2.pop(1) brd2.insert(1,"x") print(brd1) print(brd2) print(brd3) elif player1 == 5: brd2.pop(2) brd2.insert(2,"x") print(brd1) print(brd2) print(brd3) elif player1 == 6: brd3.pop(0) brd3.insert(0,"x") print(brd1) print(brd2) print(brd3) elif player1 == 7: brd3.pop(1) brd3.insert(1,"x") print(brd1) print(brd2) print(brd3) elif player1 == 8: brd3.pop(2) brd3.insert(2,"x") print(brd1) print(brd2) print(brd3) play2() if player2 == player1: print("You can't both go to the same spot!") elif player2 == 0: brd1.pop(0) brd1.insert(0,"o") print(brd1) print(brd2) print(brd3) elif player2 == 1: brd1.pop(1) brd1.insert(1,"o") print(brd1) print(brd2) print(brd3) elif player2 == 2: brd1.pop(2) brd1.insert(2,"o") print(brd1) print(brd2) print(brd3) elif player2 == 3: brd2.pop(0) brd2.insert(0,"o") print(brd…
score: -1

http://stackoverflow.com/a/48889401
has comment: http://stackoverflow.com/comment/84794685
downvote count: 0
score: 3
accepted answer of: http://stackoverflow.com/q/48889296
answers question: http://stackoverflow.com/q/48889296
has body: path and re_path both are different modules in django.urls. You are importing re_path and using path change code to from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), ] If you want to use path and re_path both, import both. from django.urls import include, path, re_path
upvote count: 3
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84784417
type: Answer

http://stackoverflow.com/q/48845596
score: 1
downvote count: 0
favorite count: 0
has body: I'm looking at tracking extra data around my celery tasks. By default it has a task_id, status, results, date completed. I was hoping to track which exact task type and variables used (i.e. image_rendering img_id:2, image_resizing img_id:5). Is there a way to add to the existing table or am I better off creating a second table that references the task_id and create that entry when the task is created? FYI using postgresql as a backend.
tagged with: python
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: celery
type: Question
has title: Tracking extra information for Celery results

http://stackoverflow.com/comment/84831140
comment on: http://stackoverflow.com/q/48912403
has text: That's `__init__()` of `Warren` being called with three params (+ `self`)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48933774
has answer: http://stackoverflow.com/a/48936653
upvote count: 2
linked to: http://stackoverflow.com/q/34649793
answer count: 2
favorite count: 0
tagged with: python
has title: Xlsxwriter count/sum function
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48936818
type: UnansweredQuestion
tagged with: excel
type: Question
linked to: http://stackoverflow.com/q/32205927
has body: Hi i've been using xlsxwriter to scrap some data. I've been identifying data via xpaths -> text. As shown in the code below. I've been trying to use xlsxwriter to perform some average across some cells. However the output excel file I get "#DIV/0!" in cell G2 but when I double click on each individual cell twice, that cells then gets averaged, I have to do this for all the cells I'm averaging. Any idea how I can over come this issue? for elem in driver.find_elements_by_xpath('//*[@id="financials_table_ratio"]/tbody/tr[45]/td[2]'): PER1=(elem.text) for elem in driver.find_elements_by_xpath('//*[@id="financials_table_ratio"]/tbody/tr[45]/td[3]'): PER2=(elem.text) for elem in driver.find_elements_by_xpath('//*[@id="financials_table_ratio"]/tbody/tr[45]/td[4]'): PER3=(elem.text) for elem in driver.find_elements_by_xpath('//*[@id="financials_table_ratio"]/tbody/tr[45]/td[5]'): PER4=(elem.text) worksheet.write('B2',PER) worksheet.write('C2',PER1) worksheet.write('D2',PER2) worksheet.write('E2',PER3) worksheet.write('F2',PER4) worksheet.write_formula('G2', '=average(C2:F2)')

http://stackoverflow.com/comment/84859468
comment on: http://stackoverflow.com/a/48925892
score: 0
type: Comment
has text: You need to import the module first: `import openpyxl; print(openpyxl.__version__)`
type: AnswerComment

http://stackoverflow.com/comment/84707827
type: Comment
comment on: http://stackoverflow.com/a/48852013
type: AnswerComment
has text: Sure, I will ! It is the first time for me to use this website , so it took me several minutes to Bing out(google is banned) how to accept answer on stackoverflow,haha,thanks again !
score: 0

http://stackoverflow.com/a/48956672
type: Answer
answers question: http://stackoverflow.com/q/48955521
has body: I found a solution to the problem in case anyone else is struggling with a similar issue: grouped1 = df1.groupby('Person', as_index=False) grouped2 = df2.groupby('Person', as_index=False) john1 = grouped1.get_group('John').reset_index() john2 = grouped2.get_group('John').reset_index() ax = john1['Pts'].expanding().mean().plot() john2['Pts'].expanding().mean().plot(ax=ax) plt.show()
score: 0

http://stackoverflow.com/a/48917570
upvote count: 1
has comment: http://stackoverflow.com/comment/84849975
answers question: http://stackoverflow.com/q/48917312
has body: You need some sort of locking mechanism. The best way to achieve an atomic lock from bash is to use mkdir and check the result code to know if you acquired the lock or not. Here's a more in depth explanation: http://wiki.bash-hackers.org/howto/mutex Of course you could always go for dirtier methods like a grep on process names or stuff like that. You could also have a lock in scrapy itself, add a simple middleware check for a shared resource... Plenty of ways to do it :)
type: Answer
has comment: http://stackoverflow.com/comment/84842132
downvote count: 0
score: 1

http://stackoverflow.com/q/48900923
has answer: http://stackoverflow.com/a/48901240
has title: How to fetch postgres table in parallel using python
answer count: 1
has comment: http://stackoverflow.com/comment/84807659
tagged with: postgresql
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/84807872
tagged with: parallel-processing
has body: I have a table named "order_lines" since it is has almost 7 million rows it takes me around 30 minutes to pull it and dump into a csv. I was hoping if I can pull it in parallel so as to reduce load time using python. My end objective is to replicate it in redshift. Can someone please suggests methods to pull this table in python ? Thanks in advance !
score: 0
tagged with: multiprocessing
type: Question

http://stackoverflow.com/q/48816703
has comment: http://stackoverflow.com/comment/84637875
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48818513
has comment: http://stackoverflow.com/comment/84638268
accepted answer: http://stackoverflow.com/a/48818513
tagged with: image
has title: OpenCV - Turn Transparent Part of PNG white
has comment: http://stackoverflow.com/comment/84637568
has comment: http://stackoverflow.com/comment/84637432
answer count: 1
downvote count: 0
has body: I am new to OpenCV so please bear with me if my qustion seems silly to you. I have a set of images that all have a transparent border on the left and right like you can see below: I want to erase these borders so I thought about edge detection which would be easy to do if I could transform these transparent borders to a white color. In the Docs I found that you can do this: img = cv2.imread("./Green/image-000.png", 1) cv2.imwrite('../image-000.png', img) This erases the alpha channel of the png image but turns it into black. Is there something similar that turns the borders white? Or is there even a simpler method of erasing these borders? You would make me really happy if you could help me! PS: I use Python 2.7 and OpenCV 3.4
favorite count: 0
has comment: http://stackoverflow.com/comment/84637693
tagged with: python
tagged with: http://stackoverflow.com/tag/png
tagged with: opencv

http://stackoverflow.com/q/48810449
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48811916
has comment: http://stackoverflow.com/comment/84625418
has body: i'm a beginner and i'm trying to do this program with a Menu screen, where the play button run the 2048 game code. The problem is that it doesn't bind with the class for playing the game. It only appears the kivy file part. Obviously here the menu must be implemented, it's just a test with two buttons. main.py from __future__ import division import random from kivy.animation import Animation from kivy.app import App from kivy.uix.screenmanager import ScreenManager, Screen, WipeTransition from kivy.core.window import Window, Keyboard from kivy.graphics import Color, BorderImage from kivy.properties import ListProperty, NumericProperty, ObjectProperty, ReferenceListProperty from kivy.uix.widget import Widget from kivy.utils import get_color_from_hex from kivy.vector import Vector from kivy.clock import Clock from kivy.uix.popup import Popup from kivy.uix.label import Label spacing = 15 colors = ( 'eee4da', 'ede0c8', 'f2b179', 'f59563', 'f67c5f', 'f65e3b', 'edcf72', 'edcc61', 'edc850', 'edc53f', 'edc22e') tile_colors = {2 ** i: color for i, color in enumerate(colors, start=1)} key_vectors = { Keyboard.keycodes['up']: (0, 1), Keyboard.keycodes['right']: (1, 0), Keyboard.keycodes['down']: (0, -1), Keyboard.keycodes['left']: (-1, 0), } class Tile(Widget): font_size = NumericProperty(24) number = NumericProperty(2) color = ListProperty(get_color_from_hex(tile_colors[2])) number_color = ListProperty(get_color_from_hex('776e65')) def __init__(self, number=2, **kwargs): super(Tile, self).__init__(**kwargs) self.font_size = 0.5 * self.width self.number = number self.update_colors() def update_colors(self): self.color = get_color_from_hex(tile_colors[self.number]) if self.number &gt; 4: self.number_color = get_color_from_hex('f9f6f2') def resize(self, pos, size): self.pos = pos self.size = size self.font_size = 0.5 * self.width def all_cells(flip_x=False, flip_y=False): for x in (reversed(range(4)) if flip_x else range(4)): for y in (reversed(range(4)) if flip_y else range(4)):…
type: Question
has comment: http://stackoverflow.com/comment/84625530
answer count: 1
score: 0
has title: Screen Manager in kivy doesn't work
has answer: http://stackoverflow.com/a/48811916
has comment: http://stackoverflow.com/comment/84626449
tagged with: kivy
tagged with: kivy-language

http://stackoverflow.com/a/48888065
type: Answer
answers question: http://stackoverflow.com/q/48887788
has body: Can anyone tell me how this can work? Ask what is the difference between the two types of loop: A for loop iterates through a sequence A while loop tests for the truthfulness of a condition Therefore they are used for different purposes. Personally I would (do) teach while before for. You can use a while loop, but you have to do the iteration yourself: i = 0 total = 0 while i &lt; len(my_list): total += my_list[i] i += 1 average = total / len(my_list) Note that the calculation of average is outside the loop. Query: why are you teaching the old python 2.7?
has comment: http://stackoverflow.com/comment/84781387
score: 0

http://stackoverflow.com/q/48955999
has answer: http://stackoverflow.com/a/48956137
favorite count: 0
score: 8
has comment: http://stackoverflow.com/comment/128742897
has answer: http://stackoverflow.com/a/76339367
upvote count: 8
tagged with: python
linked to: http://stackoverflow.com/q/33068055
possible better answer: http://stackoverflow.com/a/76339367
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48956137
type: Question
tagged with: aws-ssm
tagged with: boto3
tagged with: amazon-web-services
has body: I am using a simple boto3 script to retrieve a parameter from SSM param store in my aws account. The python script looks like below: client = get_boto3_client('ssm', 'us-east-1') try: response = client.get_parameter(Name='my_param_name',WithDecryption=True) except Exception as e: logging.error("retrieve param error: {0}".format(e)) raise e return response If the given parameter is not available, I get a generic error in the response like below: An error occurred (ParameterNotFound) when calling the GetParameter operation: Parameter my_param_name not found. I have verified method signature from boto3 ssm docs. Related AWS API Docs confirms to return a 400 response when parameter does not exist in the param store. My question is that how do I verify if the exception caught in the response is actually a 400 status code so that I can handle it accordingly.
has title: Boto3 AWS API error responses for SSM
answer count: 3
has answer: http://stackoverflow.com/a/48956246
downvote count: 0

http://stackoverflow.com/a/48862952
has body: In openpyxl this is very straightforward: ws1 is your source worksheet ws2 is your target worksheet for row in ws1['A':'B']: ws2.append((c.value for c in row)) for row in ws1['C':'D']: ws2.append((c.value for c in row)) Adjust the columns as you need them
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48838859
type: Answer
upvote count: 2

http://stackoverflow.com/comment/84915274
has text: What output is it giving you?
comment on: http://stackoverflow.com/a/48954197
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84787989
comment on: http://stackoverflow.com/q/48891247
has text: distinct() method can work properly if you're using Postgresql Database because Django provide distinct method with many options.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84692587
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48839447
has text: Oh, you're right! I haven't realized it's also used for exception handling :) Thanks, Mikhail
type: AnswerComment

http://stackoverflow.com/q/48849047
has answer: http://stackoverflow.com/a/48849088
score: 22
answer count: 1
favorite count: 0
tagged with: c++
accepted answer: http://stackoverflow.com/a/48849088
tagged with: python
type: AnsweredQuestion
has body: TLDR; PyString_FromString doesn't work in Python3.5 so I need an alternative. I am following an example for including python 3 within a C++ project from this python documentation: https://docs.python.org/3/extending/embedding.html Everything is working fine but now I want to change the line that reads: pValue = PyLong_FromLong(atoi(argv[i + 3])); to the following (I also no longer use i, that was from a loop): pValue = PyString_FromString("A string instead of a number"); It seems the PyString_FromString function is no longer an option Python3.5 and I get the following error when I compile the code with g++: main.cpp:559:60: error: ‘PyString_FromString’ was not declared in this scope pValue = PyString_FromString("A string instead of a number");` Any idea on how I get around this? No matter what I look for I can't seem to find a solution that doesn't throw an error. I need to pass a string to my Python file and I have a string to start with already.
type: Question
has title: Replacing PyString_FromString method in python 3
upvote count: 22
downvote count: 0

http://stackoverflow.com/comment/92946839
has text: I would still be curious to understand how Python was interpreting the code examples in the OP's question... I would expect this behavior to be a "high level" bug, not just a typo in the code.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48862900

http://stackoverflow.com/comment/84645062
has text: @Podo another thing that could cause it, something like this: `for x in range(10):` with no `pass` or for-loop body.
score: 0
comment on: http://stackoverflow.com/a/48818469
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48898614
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/87146715
score: 1
has body: This worked for me with Python 3.6.1 from pandas_datareader import data import fix_yahoo_finance as yf yf.pdr_override() symbol = 'AMZN' data_source='google' start_date = '2010-01-01' end_date = '2016-01-01' df = data.get_data_yahoo(symbol, start_date, end_date) print(df) df.head() This worked for me as well. from urllib.request import urlopen from bs4 import BeautifulSoup as bs def get_historical_data(name, number_of_days): data = [] url = "https://finance.yahoo.com/quote/" + name + "/history/" rows = bs(urlopen(url).read()).findAll('table')[0].tbody.findAll('tr') for each_row in rows: divs = each_row.findAll('td') if divs[1].span.text != 'Dividend': #Ignore this row in the table #I'm only interested in 'Open' price; For other values, play with divs[1 - 5] data.append({'Date': divs[0].span.text, 'Open': float(divs[1].span.text.replace(',',''))}) return data[:number_of_days] #Test for i in get_historical_data('googl', 25): print(i)
downvote count: 0
answers question: http://stackoverflow.com/q/48895501
has comment: http://stackoverflow.com/comment/87125559

http://stackoverflow.com/a/48876866
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84767985
has body: open (file_path, 'rb') Try opening with rb, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files. --Edit-- One more change was needed image_bytes_b64=base64.b64encode(content).decode(). Thanks for pointing it out. To support native Python 2 strings, older Django versions had to accept both bytestrings and unicode strings. Now that Python 2 support is dropped, bytestrings should only be encountered around input/output boundaries (handling of binary fields or HTTP streams, for example). For bytestrings, this creates a string with an undesired b prefix as well as additional quotes (str(b'foo') is "b'foo'"). To adapt, call decode() on the bytestring before passing it.
accepted answer of: http://stackoverflow.com/q/48876790
answers question: http://stackoverflow.com/q/48876790
has comment: http://stackoverflow.com/comment/84758088
upvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48858835
favorite count: 0
has body: I have a csv file named master.csv, which has the following columns link, name And another csv file called details.csv, which has the following columns link, name, price, desc I want to match master.csv against details.csv and delete the rows from master.csv which already have details in details.csv. link column is the unique column that matches both. Currently am able to read CSV file line by line. filename = "src/master.csv" filename2 = "src/details.csv" file = open(filename2) #loop through details for line in file: #code to get column link from details.csv using regex prog = re.compile('xxxxx') link = prog.match(data) remove_from_master(link) How the remove_from_master() function should be written is where am stuck. Both CSVs are not in same order, hence if iterate master.csv and check for link in each line per item in details.csv, it will take alot of time. Is there any other quick way to do this?
tagged with: python
tagged with: text
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48877199
upvote count: 1
has comment: http://stackoverflow.com/comment/84721033
downvote count: 1
type: Question
has title: Remove lines from CSV based on another CSV in Python
has comment: http://stackoverflow.com/comment/84721060
accepted answer: http://stackoverflow.com/a/48877199
score: 0
has comment: http://stackoverflow.com/comment/84721891
tagged with: http://stackoverflow.com/tag/csv
answer count: 1

http://stackoverflow.com/a/48905271
has comment: http://stackoverflow.com/comment/84816127
has comment: http://stackoverflow.com/comment/84816315
downvote count: 0
has body: Make sure you have upgraded django-extensions (which contains shell_plus) at the same time as Django, so that you have a compatible version installed. At the time of writing, the latest release django-extensions 1.9.9 appears to support Django 1.8. However in future you may find that the latest version does not support Django 1.8 after it goes end of life in April 2018.
answers question: http://stackoverflow.com/q/48904801
type: Answer
has comment: http://stackoverflow.com/comment/84817326
has comment: http://stackoverflow.com/comment/84816463
score: 1
upvote count: 1

http://stackoverflow.com/a/48837633
downvote count: 0
has comment: http://stackoverflow.com/comment/84679980
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48837582
accepted answer of: http://stackoverflow.com/q/48837582
has comment: http://stackoverflow.com/comment/84679987
has body: The actual pattern is pretty simple to specify. But, you'll also need to specify a look-behind to handle the second term appropriately. &gt;&gt;&gt; re.findall(r'(?:(?&lt;=\s)|(?&lt;=^))[^:]\S+\?', string1) ['HI:MYDLKJL:ajkld?', 'app?'] The regex means "any expression that does not start with a colon but ends with a question mark". (?: # lookbehind (?&lt;=\s) # space | # OR (?&lt;=^) # start-of-line metachar ) [^:] # anything that is not a colon \S+ # one or more characters that are not a space \? # literal question mark A simple word boundary does not work because \b will also match the boundary between : and JKLJBLKJD... no bueno, hence the lookbehind.
type: AcceptedAnswer

http://stackoverflow.com/q/48847881
type: Question
tagged with: mechanize
tagged with: http://stackoverflow.com/tag/html
tagged with: python
upvote count: 2
tagged with: selenium
has answer: http://stackoverflow.com/a/48849134
tagged with: python-requests
answer count: 1
has title: Python 3, filling out a form with request (library) returns same page HTML without inputting parameters
accepted answer: http://stackoverflow.com/a/48849134
type: AnsweredQuestion
score: 2
has body: I am trying to use requests to fill out a form on https://www.doleta.gov/tradeact/taa/taa_search_form.cfm and return the HTML of the new page that this opens and extract information from the new page. Here is the relevant HTML Petition number : Here is the python code I am trying to use. url = 'https://www.doleta.gov/tradeact/taa/taa_search.cfm' payload = {'number_search':'11111'} r = requests.get(url, params=payload) with open("requests_results1.html", "wb") as f: f.write(r.content) When you perform the query manually, this page opens https://www.doleta.gov/tradeact/taa/taa_search.cfm. However, when I use the above Python code, it returns the HTML of https://www.doleta.gov/tradeact/taa/taa_search_form.cfm (the first page) and nothing is different. I cannot perform similar code on https://www.doleta.gov/tradeact/taa/taa_search.cfm because it redirects to the first URL and thus, running the code returns the HTML of the first URL. Because of the permissions setup of my computer, I cannot redirect the path of my PC (which means Selenium is off the table) and I cannot install Python 2 (which means mechanize is off the table). I am open to using urllib but do not know the library very well. I need to perform this action ~10,000 times to scrap the information. I can build the iteration part myself, but I cannot figure out how to get the base function to work properly.
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48902586
downvote count: 0
answer count: 1
favorite count: 0
has body: I want to create a map for my cluster result (this kind of map).For example, this is the result that I generate using SOM. Example of my input (based on DNA sequence motif): motif 1 = 0.19,0.95,0.01,0,0.76,0,1.04,0,0,0.05,0,1,0,0,1,0 motif 2 =0,0,0,0,0,0,1,0.3,0.05,0.15,0.7,0.6,0.05,1.15,0.2,0.8 motif 3 =0.9,0,0,1.1,0,0,0,0.45,0.035,0,0.015,0.15,1.665,0,0.335,1.35 motif 4 =1,0,0,1.16,0.036,0,0.0032,0.4,0.294,0,0.025,0.04,1.5888,0.04,0.371,1.04 Output (run using SOM in python): Cluster for training input: motif 1 = Cluster 1 motif 2 = Cluster 2 motif 3 = Cluster 1 motif 4 = Cluster 1 weight for node 1: 1.366,0.951,0.819,0.919,0.812,0.688,0.802,0.622,0.999,0.574,0.618,0.803,0.880,0.721,0.741,0.963 weight for node 2: 1.366,0.951,0.819,0.919,0.812,0.688,0.802,0.622,0.999,0.574,0.618,0.803,0.880,0.721,0.741,0.963
tagged with: visualization
tagged with: python
tagged with: som
upvote count: 2
type: UnansweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/103968131
tagged with: self-organizing-maps
has answer: http://stackoverflow.com/a/52809840
type: Question
has title: how to visualize/plot SOM in python?

http://stackoverflow.com/q/48822903
has answer: http://stackoverflow.com/a/50216704
type: AnsweredQuestion
score: 7
tagged with: ubuntu-16.04
possible better answer: http://stackoverflow.com/a/48823028
tagged with: selenium
has title: How to run the Python program in the background in Ubuntu server
type: Question
has answer: http://stackoverflow.com/a/48822950
tagged with: server
downvote count: 0
answer count: 3
favorite count: 0
accepted answer: http://stackoverflow.com/a/48822950
tagged with: nohup
has body: I have a python script. Script have selenium with Chrome and go to a website, take data and put in CSV file. This is a very long work. I put the script on the server. And run. All work. But I need script work in the background. chmod +x createdb.py nohup python ./createdb.py &amp; And I see (env)$ nohup ./createdb.py &amp; [1] 32257 (env)$ nohup: ignoring input and appending output to 'nohup.out' Press Enter. (env)$ nohup ./createdb.py &amp; [1] 32257 (env)$ nohup: ignoring input and appending output to 'nohup.out' [1]+ Exit 1 nohup ./createdb.py Then it runs and immediately writes errors to the file, that Chrome did not start or there was no click. I want to remind you that if you start without nohup, then everything will work. What am I doing wrong? How to run a script? Thank you very much.
tagged with: python
upvote count: 7
has answer: http://stackoverflow.com/a/48823028

http://stackoverflow.com/q/48870598
tagged with: theano
tagged with: neural-network
has comment: http://stackoverflow.com/comment/84753843
has body: The TL;DR is that my G(z) (z is normal distributed noise) is way out of the expected range. Picture - see comparison of real against generated data. (It's also a terrible model, being just a few dense layers - but I can sort that later!) I've thrown s**t at the wall for the past week to see what sticks and now it's time to ask for an informed opinion! :) Has anyone else encountered this problem before? Suggested fixes? What is your generic loss function for your regressive Generator (with a categorical discriminator)? As it's a regression problem (with target data normalised between 0 &amp; 1) my G output has a linear activation. However, I'm trying to follow Soumith's GAN Hacks to get it working, where we're conflicting over the activation - he says it should be tanh. One could assume with my expected target range I could choose sigmoid, but as I say, I infer this should be linear as a regressive problem to solve. Opinions? Plus there isn't much clarity on the loss function. He Says:- In GAN papers, the loss function to optimize G is min (log 1-D), but in practice folks practically use max log D Does this mean one should aim to minimise the error log(1-D), or pick the minimum of log(1-D)? Similarly with max log(D). (I'm using class definitions of true/false, so a maximum and minimum from the can be chosen from the two classes.) In the Goodfellow et. al 2014 paper on GANs, I can see how some of the loss function for the Discriminator resolves to 0 when applied to the Generator. However, I'm obviously missing something, as the equation states I should take log(D(x)) which will sooner or later hit a NaN. Clarification about my confused state is thanked many times in advance. Update: This tutorial on O'Reilly says Take a look at the last line of our discriminator: there's no softmax or sigmoid layer at the end. GANs can fail if their discriminators "saturate," or become confident enough to return exactly 0 when they're given a generated image; that leaves the discrimin…
score: 0
has comment: http://stackoverflow.com/comment/84757454
tagged with: keras
has comment: http://stackoverflow.com/comment/84753678
has comment: http://stackoverflow.com/comment/84820405
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84828855
answer count: 0
has comment: http://stackoverflow.com/comment/84820782
tagged with: tensorflow
type: Question
has title: GAN Generator output layer is [way] out of target range - potentially due to loss func

http://stackoverflow.com/comment/84778024
type: QuestionComment
comment on: http://stackoverflow.com/q/48886648
has text: Create a columnwise histogram and then return any elements whose counts are 1. Here's a starting point: https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.count_nonzero.html
score: 0
type: Comment

http://stackoverflow.com/comment/84854019
has text: No, it does not.
comment on: http://stackoverflow.com/a/48921410
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48812195
tagged with: pyqt
downvote count: 0
has body: I'm been trying to install PyQt and I can't get past the below error. I've read a few posts suggesting that I should upgrade PIP, setup_tools, and ez_install. I've tried all of that with no luck. Any tips? c:\Python27&gt;pip install PyQt5_gpl-5.10.tar.gz Processing c:\python27\pyqt5_gpl-5.10.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "c:\program files (x86)\python36-32\lib\tokenize.py", line 452, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\JAME~1.KRK\\AppData\\Local\\Temp\\pip-0u8uht47-build\\setup.py' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\JAME~1.KRK\AppData\Local\Temp\pip-0u8uht47-build\ Same thing in 3.6: c:\Program Files (x86)\Python36-32&gt;pip install PyQt5_gpl-5.10.tar.gz Processing c:\program files (x86)\python36-32\pyqt5_gpl-5.10.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "&lt;string&gt;", line 1, in &lt;module&gt; File "c:\program files (x86)\python36-32\lib\tokenize.py", line 452, in open buffer = _builtin_open(filename, 'rb') FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\JAME~1.KRK\\AppData\\Local\\Temp\\pip-f9s0_6sp-build\\setup.py' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\JAM~1.KRK\AppData\Local\Temp\pip-f9s0_6sp-build\
favorite count: 0
has answer: http://stackoverflow.com/a/48812400
has title: FileNotFoundError Installing PyQt5
answer count: 5
type: UnansweredQuestion
tagged with: windows
tagged with: python
has comment: http://stackoverflow.com/comment/105462288
has answer: http://stackoverflow.com/a/48826953
tagged with: installation
has answer: http://stackoverflow.com/a/73150313
has answer: http://stackoverflow.com/a/48812368
score: 7
upvote count: 7
type: Question
has answer: http://stackoverflow.com/a/65730892

supervised-learning
type: Tag
tag name: supervised-learning
tags question: http://stackoverflow.com/q/48956602

http://stackoverflow.com/comment/84914873
score: 0
has text: Perhaps it's because your app doesn't have a window to get (and therefore there's no window text to get either). What would you expect to get if the `GetForegroundWindow()` worked?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48939350

http://stackoverflow.com/a/48839554
accepted answer of: http://stackoverflow.com/q/48836215
answers question: http://stackoverflow.com/q/48836215
upvote count: 2
has body: You were pretty close in doing what you want. I made a few changes. This will give what you want: html = ''' One Text1 Text2 Text3 dummy Two ''' soup = BeautifulSoup(html, 'lxml') texts = [] links = [] for tag in soup.find('h2', text='One').find_next_siblings(): if tag.name == 'h2': break a = tag.find('a', itemprop='affiliation', href=True, text=True) if a: texts.append(a.text) links.append(a['href']) print(texts, links, sep='\n') Output: ['Text1', 'Text2', 'Text3'] ['../../snapshot.asp?carId=1230559', '../../snapshot.asp?carId=1648920', '../../snapshot.asp?carId=1207230'] I've added a dummy tag with no child tag to show that the code won't fail for any other cases. If the HTML doesn't have any tags with itemprop="affiliation" apart from the ones you want, you can directly use this: texts = [x.text for x in soup.find_all('a', itemprop='affiliation', text=True)] links = [x['href'] for x in soup.find_all('a', itemprop='affiliation', href=True)]
type: AcceptedAnswer
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/comment/84918874
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48919073
type: Comment
has text: @Mr.Jibz There are multiple ways to do that, `df.plot` would work, or you can use `plt.bar` or `seaborn` library.

http://stackoverflow.com/a/48960224
has body: You could also use: str.splitlines() method. You'll end up with something like this: array.append(file.readline().splitlines())
answers question: http://stackoverflow.com/q/48960118
score: 0
type: Answer

http://stackoverflow.com/comment/84679009
comment on: http://stackoverflow.com/q/48836940
score: 0
type: QuestionComment
has text: you CAN create a packet with mostly whatever data you want, but some values cannot be changed no matter how hard you try, like length fields... why do you want it in packet form? to send it? depending on the type of packet it might literally be impossible for the os to send it
type: Comment

http://stackoverflow.com/comment/84715223
score: 0
has text: Thanks for your comment. I (hopefully) made the question clearer.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48855752

http://stackoverflow.com/a/48869573
downvote count: 0
has comment: http://stackoverflow.com/comment/84746019
has comment: http://stackoverflow.com/comment/84744709
type: Answer
has comment: http://stackoverflow.com/comment/84745740
has body: RandomForestClassifier.decision_path method returns a tuple of (indicator, n_nodes_ptr). see the documentation : here So your variable node_indicator is a tuple and not what you think it is. A tuple object has no attribute 'indices' that's why you get the error when you do : node_index = node_indicator.indices[node_indicator.indptr[sample_id]: node_indicator.indptr[sample_id + 1]] try : (node_indicator, _) = rf.decision_path(X_train) You can also plot the decision tree of each tree of the forest for a single sample id : X_train = X_train.values sample_id = 0 for j, tree in enumerate(rf.estimators_): n_nodes = tree.tree_.node_count children_left = tree.tree_.children_left children_right = tree.tree_.children_right feature = tree.tree_.feature threshold = tree.tree_.threshold print("Decision path for DecisionTree {0}".format(j)) node_indicator = tree.decision_path(X_train) leave_id = tree.apply(X_train) node_index = node_indicator.indices[node_indicator.indptr[sample_id]: node_indicator.indptr[sample_id + 1]] print('Rules used to predict sample %s: ' % sample_id) for node_id in node_index: if leave_id[sample_id] != node_id: continue if (X_train[sample_id, feature[node_id]] &lt;= threshold[node_id]): threshold_sign = "&lt;=" else: threshold_sign = "&gt;" print("decision id node %s : (X_train[%s, %s] (= %s) %s %s)" % (node_id, sample_id, feature[node_id], X_train[sample_id, feature[node_id]], threshold_sign, threshold[node_id])) Note that in your case, you have 50 estimators so it might be a bit boring to read.
accepted answer of: http://stackoverflow.com/q/48869343
has comment: http://stackoverflow.com/comment/84745905
answers question: http://stackoverflow.com/q/48869343
upvote count: 5
has comment: http://stackoverflow.com/comment/84745299
has comment: http://stackoverflow.com/comment/84746066
score: 5
type: AcceptedAnswer

http://stackoverflow.com/comment/84714971
comment on: http://stackoverflow.com/q/48855725
score: 0
has text: Please show (1) which version of Python you are using, (2) what `list("ć")` returns.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48881224
has comment: http://stackoverflow.com/comment/93243257
has title: Strange behavior for Spyder code annotations
score: 0
tagged with: ide
has comment: http://stackoverflow.com/comment/84972390
has comment: http://stackoverflow.com/comment/84984418
tagged with: spyder
tagged with: python
tagged with: editor
linked to: http://stackoverflow.com/q/9586478
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84781414
type: Question
has comment: http://stackoverflow.com/comment/84984665
has body: Using comments such as #TIPS and #HINTS will render a blue checkmark in the Spyder IDE like this: If you go to Tools|Editor|Code Introspection/Analysis and activate Code Annotations (TODO, FIXME, XXX, HINT, TIP...), those keywords do not seem to trigger any effect in the SPyder IDE at all: I would assume that HINT and TIP should render the checkmark and not HINTS and TIPS. Does anyone know if it is supposed to be like this? Thank you! My system: Windows 7, 64 bit Python 3.6.0 IPython 5.1.0 Spyder 3.2.5

http://stackoverflow.com/q/48891997
type: UnansweredQuestion
score: 0
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84789959
type: Question
has comment: http://stackoverflow.com/comment/84790671
tagged with: pandas
favorite count: 0
tagged with: python-3.x
has title: SettingWithCopyWarning although I use .loc
linked to: http://stackoverflow.com/q/45170312
has comment: http://stackoverflow.com/comment/84790797
has comment: http://stackoverflow.com/comment/84789817
tagged with: python
linked to: http://stackoverflow.com/q/20625582
has body: I am using the following code: video_df_x.loc[:, 'duration'] = pd.to_datetime(video_df['datetime_2']) - pd.to_datetime(video_df_x['datetime_1']) The code runs but gives me the following warning: C:\Program Files\Anaconda3\lib\site-packages\pandas\core\indexing.py:337: 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 I do not understand why I receive this error, since I am already using .loc in my code, which is recommended in the warning message. Any insights?
answer count: 0

http://stackoverflow.com/comment/84899073
type: AnswerComment
has text: Thank you very much for the help - when I used the code with the ".text" at the end of the html it printed out exactly the share price value. I do have a small question regarding the logic in your answer - are you saying the problem was that the way my Chrome browser was reading the html on the site and sending it to Python was incorrect? How did you get the information within the "headers" variable? Another small question - how is ".find" different to ".find_all"? Thank you again!
comment on: http://stackoverflow.com/a/48925268
type: Comment
score: 0

http://stackoverflow.com/q/48873247
has title: API endpoint as a django model
answer count: 0
has comment: http://stackoverflow.com/comment/84751073
has comment: http://stackoverflow.com/comment/84756039
type: Question
has comment: http://stackoverflow.com/comment/84751664
score: 0
has body: I want an API endpoint to be linked to a model that supports relationships. For example, if I have an endpoint http://api-url/users which gives all users, I want to create a model 'Order' with a field 'user' which is a ForiegnKey to a User model linked to the API.
type: UnansweredQuestion
tagged with: django
tagged with: python

http://stackoverflow.com/a/59803712
score: -1
has body: You need to add this option to chrome : chrome_options = Options() chrome_options.add_argument("--use-fake-ui-for-media-stream")
answers question: http://stackoverflow.com/q/48825633
downvote count: 1
type: Answer
upvote count: 0

http://stackoverflow.com/comment/84696475
score: 0
comment on: http://stackoverflow.com/a/48843765
type: AnswerComment
type: Comment
has text: Yes I got them, thank you! I tried to use your example. However, I get the type error: "tuple indices must be integers or slices, not str" which refers to the values within self.assertCountEqual(). I changed it to the following: self.assertCountEqual(np.size(run['l_modeloutputs'],0), np.size(run['l_dataoutputs'],0)). But still, I get the same error. Any idea?

http://stackoverflow.com/a/48962469
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84930967
has comment: http://stackoverflow.com/comment/84931026
answers question: http://stackoverflow.com/q/48962435
score: 1
upvote count: 1
has body: I think the best is use dictionary of DataFrames instead list of DataFrames: df_dict={'weight': weight,'inventory': inventory} and then select by keys: df1 = df_dict['weight']
accepted answer of: http://stackoverflow.com/q/48962435
has comment: http://stackoverflow.com/comment/84931018

http://stackoverflow.com/comment/84636615
comment on: http://stackoverflow.com/q/48816326
score: 1
type: Comment
type: QuestionComment
has text: Possible duplicate of [matplotlib error - no module named tkinter](https://stackoverflow.com/questions/36327134/matplotlib-error-no-module-named-tkinter)

http://stackoverflow.com/comment/84827075
type: QuestionComment
comment on: http://stackoverflow.com/q/48909751
has text: @Andy G Thanks! That fixed the error, but now I am only getting data for the first and last numbers in the range and not all the numbers in between. So instead of getting data for 1, 2, and 3 I only get it for 1 and 3.
score: 0
type: Comment

http://stackoverflow.com/q/48887160
tagged with: python
answer count: 0
upvote count: 2
linked to: http://stackoverflow.com/q/20584527
type: Question
tagged with: opencv
has comment: http://stackoverflow.com/comment/84816677
has body: I am taking pictures of the same object on a turning table from different angles. Like this I found matching points on the Image: https://docs.opencv.org/3.0-beta/doc/py_tutorials/py_feature2d/py_feature_homography/py_feature_homography.html#py-feature-homography Now I want to put all the pictures on top of each other and eventually analyse it. Is it possible to match / overlay these pictures using the previously found matching points? I was playing around with getAffineTransform / getPerspectiveTransform and warpAffine / warpPerspective but I couldn't really get anywhere.
has comment: http://stackoverflow.com/comment/84780731
score: 2
has title: How to lay twisted Images on top of each other; Python - OpenCV
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84781371

http://stackoverflow.com/comment/84836165
type: QuestionComment
score: 0
has text: @sascha setting param1 to 10 , param2 to 20, param3 to 30 , param4 to 40 is beat solution for this example? This is what is meant by setting all ' vars @ lower-bound ' ?
comment on: http://stackoverflow.com/q/48914146
type: Comment

http://stackoverflow.com/comment/84882813
has text: Correct, this is fixed
comment on: http://stackoverflow.com/a/48937834
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84760481
score: 0
has text: You can cast variables to int `map(int, input_list)`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48878102

http://stackoverflow.com/q/48876981
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84758039
has comment: http://stackoverflow.com/comment/84758048
type: Question
has title: How to properly format Python Print with multiple parameters?
tagged with: python
has body: Currently I am getting the following output: data1 57578896 data2 57695876 anotherdata 59859485 What formatting do I add, so that it will look something like this: data1 57578896 data2 57695876 anotherdata 59859485 What I have now looks like this: print "%s %d" % (input_list[i], data)
upvote count: 1
has answer: http://stackoverflow.com/a/48877002
has comment: http://stackoverflow.com/comment/84758046
answer count: 1
tagged with: printing
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48877002

http://stackoverflow.com/q/48890532
has comment: http://stackoverflow.com/comment/84786412
downvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48890595
has answer: http://stackoverflow.com/a/48890604
has body: I have a question about dictionaries and for loops. In this piece of code there is a dictionary, and I want to print keys and values from that dictionary separatly. From official documentation for Python I found that it's possible to use items() method, and that's clear for me. I can't understand why "print prices[x]" will give an output of only values, not key:value or just key. I'm running this code in Codeacademy website. prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3} for x in prices: print x # will print only keys print prices[x] # will print values Thanks.
has title: Python: For loop with dictionaries (codeacademy example)
has comment: http://stackoverflow.com/comment/84788140
answer count: 2
tagged with: for-loop
upvote count: 0
favorite count: 0
type: UnansweredQuestion
score: -3
tagged with: python

http://stackoverflow.com/a/48891405
has comment: http://stackoverflow.com/comment/84788237
type: Answer
has body: Text is a class in tkinter (which you're importing using a wildcard import as in the module's attributes occupy the main namespace directly without dereferencing first), while the write method accepts str object, not a 'Text-class' object. You must have meant: f.write(t.get('1.0', 'end-1c')) which first returns the entire text in the Text object as a string, then writes that string to file, f.
has comment: http://stackoverflow.com/comment/84790453
answers question: http://stackoverflow.com/q/48891302
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84788270
downvote count: 0
has comment: http://stackoverflow.com/comment/84788383

http://stackoverflow.com/q/48866756
answer count: 1
has comment: http://stackoverflow.com/comment/84736928
has body: I am trying to train face recognizer but I don't want to train every time a new user data is entered in face database so I want to train new user data and then concatenate with previous trained recognizer. I have two trained recognizer I want to concatenate these two. Any help in this regard would be appreciated. This is my code I am reading from three recognizer and want to save them to one: face_recognizer1=my.facerecognizer(cv2.face_LBPHFaceRecognizer.create()) face_recognizer1.read("trainer"+"/"+"s1"+".xml") face_recognizer1.read("trainer"+"/"+"s2"+".xml") face_recognizer1.read("trainer"+"/"+"s3"+".xml") face_recognizer1.save("trainer"+"/"+"s11"+".xml")
score: 0
has comment: http://stackoverflow.com/comment/84738105
type: UnansweredQuestion
tagged with: python
tagged with: computer-vision
has answer: http://stackoverflow.com/a/48868300
tagged with: opencv
tagged with: image-processing
tagged with: face-recognition
type: Question
has comment: http://stackoverflow.com/comment/84739184
has title: How to load more than one trained face recognizer in one face recognizer open CV?

http://stackoverflow.com/q/48888556
has answer: http://stackoverflow.com/a/48936661
upvote count: 6
has comment: http://stackoverflow.com/comment/84794738
has body: I am trying to convert audio clips [.flac format] to text using the google cloud speech api.I am using the python client library for making requests and have a bucket on the GCP with a flat directory structure which is used to store the audio files and make asynchronous requests.Below is the python code for making requests from google.cloud import storage from google.cloud import speech from google.cloud.speech import enums from google.cloud.speech import types import json def AudioAnalyze(bucket_name): storage_client = storage.Client() speech_client = speech.SpeechClient() bucket = storage_client.get_bucket(bucket_name) bucket_contents = bucket.list_blobs() urls = [] audio_content=[] for i in bucket_contents: urls.append("gs://"+i.bucket.name+"/"+i.public_url.split("/")[-1]) for gcs_uri in urls: audio = types.RecognitionAudio(uri=gcs_uri) config = types.RecognitionConfig( encoding=enums.RecognitionConfig.AudioEncoding.FLAC, sample_rate_hertz=44100, language_code='en-US') operation = speech_client.long_running_recognize(config,audio) print(gcs_uri) print('Waiting for operation to complete...') response = operation.result(timeout=450) speech2text=[] for result in response.results: for alternative in result.alternatives: speech2text.append(alternative.transcript) ad_content=" ".join(speech2text) audio_content.append(ad_content) with open("path/to a/json file/file.json","w") as f: json.dump(audio_content,f) if __name__=="__main__": AudioAnalyze("adsaudiocontent") I am encountering an error: google.api_core.exceptions.NotFound: 404 Requested entity was not found on a particular file present in the bucket while all the other files are being processed properly.The audio files have gone through a similar processing pipeline.The audio files are available on my public bucket:adsaudiocontent so that you can replicate the error.For Additional details here is the traceback. Traceback (most recent call last): File "/home/pythonuser1/.virtualenvs/virtual_env/lib/python3.5/site-pa…
tagged with: google-cloud-storage
tagged with: google-cloud-platform
has comment: http://stackoverflow.com/comment/84784725
has comment: http://stackoverflow.com/comment/84805905
downvote count: 0
answer count: 1
favorite count: 0
tagged with: google-app-engine
score: 6
tagged with: python
type: AnsweredQuestion
has title: Google Speech API unable to find a file on Google Storage: error 404
accepted answer: http://stackoverflow.com/a/48936661
tagged with: google-speech-api
type: Question

http://stackoverflow.com/a/48886922
type: Answer
score: 2
upvote count: 2
has body: Thank you for the ideas. At first, your code wouldn't print the text on the toplevel window. So I edited it a little and it worked! Thank you. GUI1 and GUI2 look like: import tkinter as tk def GUI1(Frame): label = tk.Label(Frame, text="Hello from %s" % __file__) label.pack(padx=20, pady=20) return if __name__ == "__main__": root = tk.Tk() GUI1(root) root.mainloop() And then the caller looks like this: from tkinter import * import GUI1 import GUI2 def call_GUI1(): win1 = Toplevel(root) GUI1.GUI1(win1) return def call_GUI2(): win2 = Toplevel(root) GUI2.GUI2(win2) return # the first gui owns the root window if __name__ == "__main__": root = Tk() root.title('Caller GUI') root.minsize(720, 600) button_1 = Button(root, text='Call GUI1', width='20', height='20', command=call_GUI1) button_1.pack() button_2 = Button(root, text='Call GUI2', width='20', height='20', command=call_GUI2) button_2.pack() root.mainloop()
answers question: http://stackoverflow.com/q/48817749
downvote count: 0

http://stackoverflow.com/q/48837999
has body: How would I find the values from a certain column in an array? For example I have: [1, 1, 2, 4, 1, 7, 1, 7, 6, 9] [1, 2, 5, 3, 9, 1, 1, 1, 9, 1] [7, 4, 5, 1, 8, 1, 2, 0, 0, 4] [1, 4, 1, 1, 1, 1, 1, 1, 8, 5] [9, 0, 0, 0, 0, 0, 1, 1, 9, 8] [7, 4, 2, 1, 8, 2, 2, 2, 9, 7] [7, 4, 2, 1, 7, 1, 1, 1, 0, 5] [3, 4, 5, 3, 4, 5, 9, 1, 0, 9] [0, 0, 5, 1, 1, 1, 9, 7, 7, 7] If I wanted to list all of the values of column 5, how would I do this? I have figured out how to do this for the rows, but for the columns it is tricky, since they are all part of a separate list. I have not been able to find anything about this and I am very new to Python so I don't really know what I don't know.
downvote count: 0
has title: How would I display the values of a selected column in Python array?
has comment: http://stackoverflow.com/comment/84680714
has answer: http://stackoverflow.com/a/48838024
tagged with: python
has comment: http://stackoverflow.com/comment/84680670
favorite count: 0
has comment: http://stackoverflow.com/comment/84680726
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84701227
upvote count: 1
has comment: http://stackoverflow.com/comment/84700892
score: 1
has comment: http://stackoverflow.com/comment/84680678
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48838027

http://stackoverflow.com/comment/84799771
type: Comment
type: QuestionComment
has text: but why include both the **data_directory** and **d** in the parameters? Why not only have _**d**_ as a parameter? What is the significance of having both of them and how do they interact?
comment on: http://stackoverflow.com/q/48896971
score: 0

http://stackoverflow.com/q/48814815
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48814924
has answer: http://stackoverflow.com/a/48815537
accepted answer: http://stackoverflow.com/a/48814861
type: Question
tagged with: split
has answer: http://stackoverflow.com/a/48814904
tagged with: replace
tagged with: pandas
has body: I have a dataframe like this df = pd.DataFrame({'a' :[{'id':'0','num':10 } ,{'id':'1','num':20 },{'id':'2','num':30 }]}) I want to get id num 0 0 10 1 1 20 2 2 30 I wanted to remain only numbers and letters and then apply split But I cann't make it df['a'] = df['a'].replace('[^a-zA-Z0-9]', '', regex = True) df or df['a'].str.strip('{').astype(str) or df['a'].str.replace('\{','') all options are incorrect. How to fix it?
possible better answer: http://stackoverflow.com/a/48814904
downvote count: 0
has title: How to split a column into some columns with cells like type dict?
favorite count: 0
has answer: http://stackoverflow.com/a/48814861
has answer: http://stackoverflow.com/a/48815129
upvote count: 2
answer count: 5
tagged with: python
score: 2

http://stackoverflow.com/comment/84805905
score: 1
comment on: http://stackoverflow.com/q/48888556
has text: Thanks a ton Brandon - Looks like the issue was with how I was creating the filenames. I was unaware about the .name attribute. It works now!
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84920551
type: Comment
type: QuestionComment
score: 2
has text: Examine the result of `compare_ssim` and make sure that it is a numpy array of the correct data type (uint8) and shape (specifically the number of channels). Looks like it's not. Proper [mcve] wouldn't hurt.
comment on: http://stackoverflow.com/q/48956585

serverless-framework
tag name: serverless-framework
tags question: http://stackoverflow.com/q/48945389
type: Tag

http://stackoverflow.com/comment/84749037
type: QuestionComment
comment on: http://stackoverflow.com/q/48872133
score: 0
type: Comment
has text: If you are calling from another python script; why are you using `if __name__ == '__main__'` instead of calling a function from the calling script?

http://stackoverflow.com/q/48902691
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: birth_data.sort_values(by='name',ascending = True) name numbers bruh 96570 gib 95095 mel 115195 nish 112055 raw 88018 I can sort the "numbers" but if i replace it with "name" I receive an error. KeyError Traceback (most recent call last) ~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 2441 try: -&gt; 2442 return self._engine.get_loc(key) 2443 except KeyError: pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 'name' During handling of the above exception, another exception occurred:
score: 2
type: Question
has comment: http://stackoverflow.com/comment/84810551
downvote count: 0
tagged with: sorting
has title: sort dataframe alphabetically
has answer: http://stackoverflow.com/a/48902766
tagged with: pandas

http://stackoverflow.com/comment/84932691
score: 2
has text: please edit your question to provide clear information. Right now it is hard to understand what you are trying to say
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48963431

http://stackoverflow.com/q/48827493
downvote count: 0
has body: I came across a blog post with the following function call: intersection_cardinality = len(set.intersection(*[x, y])) Is there any benefit in passing parameters as an unpacked array created just for that, instead of simply calling set.intersection(x, y)? The blog post was written in python2, but the question goes for 3 as well.
has answer: http://stackoverflow.com/a/48827663
accepted answer: http://stackoverflow.com/a/48827663
type: Question
has comment: http://stackoverflow.com/comment/84659483
answer count: 1
upvote count: 3
has comment: http://stackoverflow.com/comment/84658645
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 3
has title: Pass parameters as unpacked array

http://stackoverflow.com/q/48814613
has comment: http://stackoverflow.com/comment/84633051
upvote count: 2
duplicate of: http://stackoverflow.com/q/20449427
has comment: http://stackoverflow.com/comment/84633271
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48814719
has answer: http://stackoverflow.com/a/48814719
type: Question
tagged with: python-2.7
answer count: 2
has answer: http://stackoverflow.com/a/48814675
score: 2
has comment: http://stackoverflow.com/comment/84633113
downvote count: 0
favorite count: 0
has title: Python 2.7.10 : How can i stop the user exploiting input by entering equation instead of integer?
has body: x2 = (randint(0, 1000000)) y2 = (randint(0, 1000000)) ans2 = input("2. Answer to " + str(x2) + "-" + str(y2)) if ans2 == x2 - y2: print("Correct!") CorrectAns = CorrectAns + 1 else: print("Wrong!") My goal: to ask question i.e 1-1 without user inputting 2-2 and getting it correct Dilemna: if the person wrote 2-2 when asked, which is 0, which is also the answer to 1-1, the computer thinks it is correct. How do i prevent this?
tagged with: python
accepted answer: http://stackoverflow.com/a/48814675

http://stackoverflow.com/comment/84662016
type: Comment
type: QuestionComment
has text: Is this a toy example or your actual problem?
score: 0
comment on: http://stackoverflow.com/q/48826763

http://stackoverflow.com/a/49099664
has body: You could use seaborn to plot these smooth histograms. These smoothed histograms are called kernel density estimations. You can find some examples here, here for 2D and here. And here is an example which kinda looks like what you are trying to achieve.
downvote count: 2
score: -2
upvote count: 0
answers question: http://stackoverflow.com/q/48925982
type: Answer

http://stackoverflow.com/q/48830865
tagged with: ffmpeg
tagged with: python
possible better answer: http://stackoverflow.com/a/58205504
upvote count: 6
linked to: http://stackoverflow.com/q/2017843
type: AnsweredQuestion
has title: Why is random video seeks with OpenCV slow?
has body: Seeking to random points in a video file with OpenCV seems to be much slower than in media players like Windows Media Player or VLC. I am trying to seek to different positions on a video file encoded in H264 (or MPEG-4 AVC (part10)) using VideoCapture and the time taken to seek to the position seems to be proportional to the frame number queried. Here's a small code example of what I'm trying to do: import cv2 cap = cv2.VideoCapture('example_file') frame_positions = [200, 400, 8000, 200000] for frame_position in frame_positions: cap.set(cv2.cv.CV_CAP_PROP_FRAMES, frame_position) img = cap.read() cv2.imshow('window', img) cv2.waitKey(0) The perceived times for when the images are displayed from above are proportional to the frame number. That is, frame number 200 and 400, barely have any delay, 8000 some noticeable lag, but 200000 would take almost half a minute. Why isn't OpenCV able to seek as "quickly" as say Windows Media Player? Could it be that OpenCV is not using the FFMPEG codecs correctly while seeking? Would building OpenCV from sources with some alternate configuration for codecs help? If so, could someone tell me what the configuration could be? I have only tested this on Windows 7 and 10 PCs, with OpenCV binaries as is, with relevant FFMPEG DLLs in system path. Another observation: With OpenCV (binaries) versions greater than 2.4.9 (Example 2.4.11, 3.3.0), the first seek works, but not the subsequent ones. That is, it can seek to frame 200 from above example, but not to 400 and the rest; the video just jumps back to frame 0. But since it works for me with 2.4.9, I'm happy for now.
has answer: http://stackoverflow.com/a/48831205
type: Question
tagged with: opencv
score: 6
answer count: 3
has answer: http://stackoverflow.com/a/64620375
downvote count: 0
accepted answer: http://stackoverflow.com/a/48831205
favorite count: 0
has answer: http://stackoverflow.com/a/58205504

http://stackoverflow.com/q/48857300
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I am trying to write and run a test that demonstrates that all the slaves in an AWS EMR cluster have a required dependency of a pyspark package (defined in a requirements.txt somewhere else). # tests/test_basic.py import unittest import pyspark class SimpleTestCase(unittest.TestCase): @classmethod def setUpClass(cls): conf = pyspark.SparkConf().setAppName("testing") cls.sc = pyspark.SparkContext(conf=conf) @classmethod def tearDownClass(cls): cls.sc.stop() def test_use_scipy(self): test_input = [ ' hello spark ', ' hello again spark spark' ] input_rdd = self.sc.parallelize(test_input) from operator import add def f(x): import scipy # an hypotetical operation that requires scipy return x.split() results = input_rdd.flatMap(f).map(lambda x: (x, 1)).reduceByKey(add).collect() self.assertEqual(set(results), {('hello', 2), ('spark', 3), ('again', 1)}) I am executing the code on the master as follow: PYSPARK_PYTHON=python3 PYSPARK_DRIVER_PYTHON=python3 python3 -m unittest I do not understand why this test passes: when I ssh the slave, pip-3.4 list does not contain scipy. I would expect this code to fail because the slave does not have the dependency to run. I suspect that the job is not being executed by the slave, possibly because I am not using spark-submit. This is because the test fails when I uninstall scipy from the master node. How do I run Python unit tests on a hypothetical staging EMR cluster?
score: 2
type: Question
has title: How to validate that dependencies are correctly installed on a spark slave node?
tagged with: pyspark
downvote count: 0
tagged with: apache-spark
favorite count: 0
answer count: 0

http://stackoverflow.com/a/48909658
downvote count: 0
upvote count: 2
answers question: http://stackoverflow.com/q/48908353
has body: This question may provide some useful insights: What does `**` mean in the expression `dict(d1, **d2)`? Essentially you could do something like this: def foo(fname): with open(fname, "r") as f: reader = csv.DictReader(f, delimiter='|') for row in reader: yield { "_source": dict(filename=fname, **row) }
type: Answer
score: 2

http://stackoverflow.com/a/48934345
has comment: http://stackoverflow.com/comment/84894311
has comment: http://stackoverflow.com/comment/84875474
has comment: http://stackoverflow.com/comment/84895230
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48929403
has body: Although I do not quite understand what you mean, how does this look? import time import socket from ftplib import FTP def try_connect(host, user, passwd): print('Connecting to FTP Server') ftp = FTP() try: # domain name or server ip ftp.connect(host, timeout=5) except socket.error: print('Connect failed!') return False # Passwd and User ftp.login(user, passwd) print('Connected to the FTP server') ftp.quit() ftp.close() return True def main(): while True: try_connect('192.168.1.1', user='anonymous', passwd='') print() time.sleep(5) if __name__ == '__main__': main() It tries to connect FTP every 5 seconds and output the result.
type: Answer
accepted answer of: http://stackoverflow.com/q/48929403
score: 1
upvote count: 1

http://stackoverflow.com/a/48818026
downvote count: 0
type: Answer
score: 6
upvote count: 6
has body: Use the group by filter df.groupby('col1').filter(lambda x: len(x) == 2) col3 col1 col2 b f n g o c h p i q
answers question: http://stackoverflow.com/q/48817964

http://stackoverflow.com/comment/84842970
type: AnswerComment
has text: @COLDSPEED is there any way to get the street (first column values) apart from doing this. `df.T.index.values.T.tolist()`
score: 0
comment on: http://stackoverflow.com/a/48917680
type: Comment

http://stackoverflow.com/q/48923721
linked to: http://stackoverflow.com/q/54276596
tagged with: ipython
type: Question
upvote count: 2
has body: I encounter an error while running the following code in PyCharm. %load_ext autoreload %autoreload 2 import funcs as f for i in range(1): df = f.read_data() The error I get is: File "&lt;ipython-input-16-7841cd68b0d1&gt;", line 7 df = f.read_data() ^ IndentationError: expected an indented block The code throws the error when I select the code and press CTRL + Enter. However, the code works fine when I run the magic statements and the rest of the code separately, or when I run the code by copy-pasting it into the iPython console. In the gif below, you can see that when pressing CTRL + Enter, the indentation seems to disappear from the code (I have tried both tab and spaces). This confuses me, because the code runs in the same console independently of which method I use to run it. I am very curious to know what causes the difference. Is the code interpreted differently? Am I using the magic statements incorrectly? Thanks in advance for any advice.
has comment: http://stackoverflow.com/comment/84853914
favorite count: 0
has comment: http://stackoverflow.com/comment/84854142
has comment: http://stackoverflow.com/comment/84854280
duplicate of: http://stackoverflow.com/q/54276596
score: 2
tagged with: pycharm
answer count: 0
downvote count: 0
has title: Getting an indentation error after autoreload statement in Python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84853990
tagged with: python

http://stackoverflow.com/comment/84882745
type: Comment
has text: One last thing: when I run my code, it generates me a 3D model. And depending on the input parameters, that might take a while (~ 1 min.). Does that mean that running the unittesting script will also take that long? Since the corresponding functions should be tested here.
type: AnswerComment
comment on: http://stackoverflow.com/a/48917872
score: 0

http://stackoverflow.com/comment/84906112
type: QuestionComment
comment on: http://stackoverflow.com/q/48949192
has text: It's hard to run your code without the shapefile.
score: 0
type: Comment

http://stackoverflow.com/comment/84644980
type: QuestionComment
comment on: http://stackoverflow.com/q/48820375
has text: @codelt Thanks a lot! it clears me
score: 0
type: Comment

http://stackoverflow.com/comment/84754879
type: QuestionComment
has text: No problem at all :) What gets stored as CSV is just a convenience issue.It depends on what resources you want to use later. Based on what you have indicated above, I would do the following. 1) iterate over entire corpus and collect TFIDF stats. Save somewhere (csv or pickle works) for later. 2) create a dictionary/csv of document_ids and years. 3) Then do subsequent processing or model building, etc. If you need to do sentence structure parsing, PoS tagging etc, just start from scratch rather than trying to make your csv handle all possible contingencies
score: 1
comment on: http://stackoverflow.com/q/48874610
type: Comment

http://stackoverflow.com/comment/84695615
comment on: http://stackoverflow.com/a/48845736
has text: I will ask a friend to try as maybe I have requested the site too much today
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84991284
type: Comment
comment on: http://stackoverflow.com/a/48923589
score: 0
type: AnswerComment
has text: I'm developing a GUI that should have precise timings in each stage, and that timings must have millisecond precision. I tried to re-paint all, but it's more time consuming in my case, and it adds time displacements.

http://stackoverflow.com/a/48883390
has body: Here is what is wrong with the code. Apparently you do not have to 'feed' item loader with add_value but you won't get field populated in the end. class SofascoreItemLoader(ItemLoader): default_item_class = SofascoreItem default_input_processor = MapCompose(methodcaller('strip')) default_output_processor = TakeFirst() review_in = MapCompose(lambda x: x.split("/")[-1]) You have to do split and then select last item in list that is generated by splitting. split(SEPARATOR, [-1]) is not what you want. Second argument is for selecting in how many parts you want string to be split. Second, you want to add url value to review field, right? This is not an answer how to use regex in scrapy ItemLoader, but you do not need it here. You just need to properly use split method.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48882651

http://stackoverflow.com/a/48816266
has body: You want to create a virtualenv and then use pip3 to install. Like Rolf of Saxony said, try pip3 install wxpython inside your virtualenv. It will download six (dependency) and the newest wxPython (currently 4.0.1) and build it from source. For all the usual reasons you generally do not want to install wxPython at system level. You will also need to make sure you have the development packages installed needed to build wxWidgets itself: gtk-dev, gstreamer, et al. If the build fails you can check the log file for details.
has comment: http://stackoverflow.com/comment/84640248
upvote count: 1
has comment: http://stackoverflow.com/comment/84639574
score: 1
has comment: http://stackoverflow.com/comment/84678367
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84636797
accepted answer of: http://stackoverflow.com/q/48811564
type: Answer
answers question: http://stackoverflow.com/q/48811564

http://stackoverflow.com/comment/84678146
type: Comment
type: QuestionComment
has text: I think you should include your code.
score: 0
comment on: http://stackoverflow.com/q/48836620

http://stackoverflow.com/comment/84929023
type: AnswerComment
comment on: http://stackoverflow.com/a/48961294
type: Comment
has text: @Maryam no worries, note https://stackoverflow.com/help/someone-answers
score: 0

http://stackoverflow.com/q/48865040
favorite count: 0
score: 6
tagged with: python
has title: Pythonic reduce with accumlation and arbitrary lambda function?
tagged with: lambda
upvote count: 6
type: AnsweredQuestion
has body: What would be the Pythonic way of performing a reduce with accumulation? For example, take R's Reduce(). Given a list and an arbitrary lambda function it allows for yielding a vector of accumulated results instead of only the final result by setting accumulate=T. An example for this with a simple multiplication as lambda function would be (taken from this answer): Reduce(`*`, x=list(5,4,3,2), accumulate=TRUE) # [1] 5 20 60 120 It is important that an arbitrary lambda function (like lambda x, y: ...) can be used, so solutions that allow for e.g. only using a sum, multiplication, or else won't do the trick. I was not able to come up with a Pythonic solution to do this with e.g. Python's itertools or functools, but there might be a way. And though there are numerous other questions and answers on reduce and specially accumulation with Python I did not spot a generic answer so far. A non-Pythonic example using a loop for performing a accumulated reduce with an arbitrary lambda function could look like this: # the source list l = [0.5, 0.9, 0.8, 0.1, 0.1, 0.9] # the lambda function for aggregation can be arbitrary # this one is just made up for the example func = lambda x, y: x * 0.65 + y * 0.35 # the accumulated reduce: # a) the target list with initializer value hardcoded l2 = [l[0]] # b) the loop for i in range(1, len(l)): l2 += [func( l2[i-1], # last value in l2 l[i] # new value from l )] So: how would you do a reduce with accumulation and arbitrary lambda function in a Pythonic way?
has answer: http://stackoverflow.com/a/48865189
type: Question
tagged with: reduce
tagged with: functional-programming
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48865189
linked to: http://stackoverflow.com/q/28545688
tagged with: accumulate

http://stackoverflow.com/comment/110245185
type: AnswerComment
has text: In other words, I want to prevent 2 binaries being true by use of the inequality, and a naive implementation using 1-bit registers would fail to allow that. I guess I could do a minimal working example but just in case you knew. Thanks again
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48891798

http://stackoverflow.com/a/48855926
type: Answer
upvote count: 4
downvote count: 0
answers question: http://stackoverflow.com/q/48804687
has body: Because you want to only hit your database one time, a good way to add your extra data to your queryset is by adding a custom version of ListModelMixin to your ViewSet that includes extra context: class PersonList(generics.ListAPIView): ... def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) # Pseudo-code for filtering, adjust to work for your use case filter_criteria = self.kwargs.get('some_filter_criteria') personal_data = Microservice.objects.custom_filter(filter_criteria) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer( page, many=True, context={'personal_data': personal_data} ) return self.get_paginated_response(serializer.data) serializer = self.get_serializer( queryset, many=True, context={'personal_data': personal_data} ) return Response(serializer.data) Then, access the extra context in your serializer by overriding the to_representation method: def to_representation(self, instance): """Add `personal_data` to the object from the Microservice""" ret = super().to_representation(instance) personal_data = self.context['personal_data'] ret['personal_data'] = personal_data[instance.uuid] return ret
score: 4

http://stackoverflow.com/comment/84690880
type: QuestionComment
score: 2
has text: There's nothing wrong with those strings. They just aren't printed the way you expected. Try `print(u'ra\xfal')` and you'll get `raúl` as output.
comment on: http://stackoverflow.com/q/48843237
type: Comment

http://stackoverflow.com/comment/84831955
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48912755
score: 1
has text: As shown, `guessToken = 0` is the *only* thing in the function `Loop`. Fix your indentation.

http://stackoverflow.com/a/48873514
downvote count: 0
answers question: http://stackoverflow.com/q/48873321
type: Answer
has body: There are two things that you can improve: 1) You need to configure the hyper-parameters of your linear model properly. The scikit-learn SGDRegressor is very sensitive to the choice of values for several parameters, being the most important ones alpha, penalty, loss and max_iter. Have a look around and try to learn about a technique called cross-validation, and use it to determine sensible values for these parameters given your data. 2) Except in very specific cases, you don't really need to scale the target variable y
upvote count: 1
score: 1

void-pointers
tags question: http://stackoverflow.com/q/48937548
type: Tag
tag name: void-pointers

http://stackoverflow.com/a/48937834
has comment: http://stackoverflow.com/comment/84882813
has comment: http://stackoverflow.com/comment/84888087
downvote count: 0
answers question: http://stackoverflow.com/q/48937718
upvote count: 2
type: Answer
has body: You can use re.sub with a flag to do this in a case insensitive manner. import re bannedWords = ['hi', 'hi you', 'hello', 'and you'] sentence = "Hi, how are Tim and you doing" new_sentence = re.sub('|'.join(bannedWords) + r'\s+', '', sentence, flags=re.I) # new_sentence: ", how are Tim doing"
has comment: http://stackoverflow.com/comment/84882686
score: 2

http://stackoverflow.com/comment/84884063
type: QuestionComment
comment on: http://stackoverflow.com/q/48938522
score: 0
has text: Several ways, did you search for one and try it?
type: Comment

http://stackoverflow.com/a/48813053
score: 0
answers question: http://stackoverflow.com/q/48812441
type: Answer
has comment: http://stackoverflow.com/comment/84656580
has body: As I mention using apply , data from jp df[~df.apply(lambda x : x.str.contains('A')).any(1)] Out[491]: COL1 COL2 COL3 COL4 1 E F G H 4 S T U V

http://stackoverflow.com/q/48937592
answer count: 4
has comment: http://stackoverflow.com/comment/84882979
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48937765
type: Question
tagged with: conditional-statements
has title: Confused with logic of my if-statement
tagged with: if-statement
has answer: http://stackoverflow.com/a/48937803
score: 0
possible better answer: http://stackoverflow.com/a/48937765
upvote count: 1
has answer: http://stackoverflow.com/a/48937740
downvote count: 1
accepted answer: http://stackoverflow.com/a/48937716
favorite count: 0
has comment: http://stackoverflow.com/comment/84882349
tagged with: python
has body: right = 0 left = 0 if(left &gt; right or (left and right) == 0): print 'doing task 1' else: print 'doing task2' for some reason no matter what value I give right or left (for example, if i set right to be 10 and left to be 2)... it always does the "doing task 1" condition.....does anybody know why?
has answer: http://stackoverflow.com/a/48937716

http://stackoverflow.com/q/48877899
answer count: 1
has comment: http://stackoverflow.com/comment/84759924
favorite count: 0
has comment: http://stackoverflow.com/comment/84759967
has comment: http://stackoverflow.com/comment/84760043
tagged with: django
upvote count: 1
tagged with: python
tagged with: python-requests
has answer: http://stackoverflow.com/a/48877996
has comment: http://stackoverflow.com/comment/84760108
has comment: http://stackoverflow.com/comment/84759891
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84759925
tagged with: post
type: Question
downvote count: 0
has body: I'm trying to take information from a POST request made from Python requests and add them to my model: def message(request): if request.method == 'POST': form = InputInfoForm(request.POST) #form models make validation easy if form.is_valid(): InputInfo.name = request.POST.get('name') InputInfo.conversation_id = request.POST.get('conversation_id') InputInfo.message_body = request.POST.get('message_body') return HttpResponse(status=200) return HttpResponse(status=200) Here's the request post_data = {'name': 'charles', 'conversation_id': '3', 'message_body': 'Ada Challenge'} r = requests.post('http://127.0.0.1:8000/message/', data=post_data) I am not sure if I am handling the requests right in the view
accepted answer: http://stackoverflow.com/a/48877996
has title: Creating new model in Django with POST data from Python requests

http://stackoverflow.com/q/48820958
answer count: 0
type: Question
tagged with: matplotlib
score: 0
tagged with: flask
has comment: http://stackoverflow.com/comment/84646095
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84653813
tagged with: python
has title: Call another app route from different app route in Flask
has body: I have one webapp flask that running to handle the data charting to display and some gpio control. all the function such as displaying data from SQLite db, and gpio control from button totally work. this code below is my webapp flask that contain many app-route. my main problem is: when I press button for turn off/on the relay, somehow my data wont load automatically. so I must hit refresh button manually when I type the specific number for input, and expect the data displayed as the range on specific number it will work if I did this before I hit gpio control button for relay. but I hit the gpio control button, I'm unable to do this and the web page said "method not allowed". so on my point of view, it may work if we add some code to call the index rout ("/") inside this route: @app.route("/<changePin>/<action>"), but unfortunately, I have little experience with python and flask, on PHP webserver might work but don't know with this type of language. maybe you can give me some clue? my goals is, the page will able to handle both action which is controlling gpio (relay), and displaying data with chart with matplotlib #!/usr/bin/env python # -*- coding: utf-8 -*- from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import io import RPi.GPIO as GPIO #import water from flask import Flask, render_template, send_file, make_response, request app = Flask(__name__) import sqlite3 #GPIO NEEDS############################################################ GPIO.setmode(GPIO.BCM) # Create a dictionary called pins to store the pin number, name, and pin state: pins = { 13 : {'name' : 'Waterpump 1', 'state' : GPIO.LOW}, 19 : {'name' : 'Growlight 2', 'state' : GPIO.LOW} } # Set each pin as an output and make it low: for pin in pins: GPIO.setup(pin, GPIO.OUT) GPIO.output(pin, GPIO.LOW) conn=sqlite3.connect('../sensorsData.db') curs=conn.cursor() # Retrieve LAST data from database def getLastData(): for row in curs.execute("SELE…

http://stackoverflow.com/a/48912706
score: 2
accepted answer of: http://stackoverflow.com/q/48912313
upvote count: 2
answers question: http://stackoverflow.com/q/48912313
has body: Your PizzaPie class contains an array, but is not an ndarray subclass. Typically a np function tries to turn its input into an array, and then apply the function to that, possibly invoking the corresponding method. np.cos is compiled, but we can get an idea of what it attempts to do by giving it a list, specifically a list that can't be made into a simple numeric array: In [51]: np.cos([np.arange(3),3,[1,2]]) --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-51-0d338a087870&gt; in &lt;module&gt;() ----&gt; 1 np.cos([np.arange(3),3,[1,2]]) AttributeError: 'numpy.ndarray' object has no attribute 'cos' In [52]: np.array([np.arange(3),3,[1,2]]) Out[52]: array([array([0, 1, 2]), 3, list([1, 2])], dtype=object) np.cos has turned the input into an object array and tried to do [x.cos() for x in np.array(input)]. For your case it does work, since you defined a cos method. np.imag is Python code, and attempts to return the imag attribute (property). It assumes imag is a property, not a method, which is why you get the unevaluated method. np.imag(val) return val.imag # or return np.asanyarray(val).imag In [53]: np.imag([np.arange(3),3,[1,2]]) Out[53]: array([0, 0, 0], dtype=object) Try setting imag as a property. Then it should evaluate.
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84832764
type: Answer

http://stackoverflow.com/a/48881300
score: 0
type: AcceptedAnswer
type: Answer
has body: Well, you have couple of options: Use multiprocessing.pool.ThreadPool (Python 2.7) where you create pool of threads and then use them for dispatching requests. map_async may be of interest here if you want to make async requests, Use concurrent.futures.ThreadPoolExecutor (Python 3) with similar way of working with ThreadPool pool and yet it is used for asynchronously executing callables, You even have option of using multiprocessing.Pool, but I'm not sure if that will give you any benefit since everything you will be doing is I/O bound, so threads should do just fine, You can make asynchronous requests with Twisted or asyncio but that may require a bit more learning if you are not accustomed to asynchronous programming.
answers question: http://stackoverflow.com/q/48880508
accepted answer of: http://stackoverflow.com/q/48880508

http://stackoverflow.com/q/48851439
has answer: http://stackoverflow.com/a/48852491
accepted answer: http://stackoverflow.com/a/48852491
favorite count: 0
has title: How to display a list of all gradients in Tensorboard?
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
tagged with: tensorflow
type: Question
downvote count: 0
answer count: 1
has body: I'm using Tensorboard 1.5 and I would like to see how my gradients are doing. Here is an example of layer I am using: net = tf.layers.dense(features, 40, activation=tf.nn.relu, kernel_regularizer=regularizer, kernel_initializer=tf.contrib.layers.xavier_initializer()) And here is my optimizer: train_op = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(loss) For my model parameters I create summaries this way: for var in tf.trainable_variables(): tf.summary.histogram(var.name, var) Is there a similar way to get the all gradients in a for loop to create my summaries?
tagged with: deep-learning
tagged with: tensorboard

protobuf-3
tags question: http://stackoverflow.com/q/48957440
tag name: protobuf-3
type: Tag

http://stackoverflow.com/comment/84697546
has text: You set `newstate = state`
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48846735

http://stackoverflow.com/q/48947777
answer count: 0
type: Question
has body: My simple Django blog don't work - if I go to http://127.0.0.1:8000/posts/create/ I see Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/posts/create/ Raised by: posts.views.post_create Looking in the git history I understand what error in posts/views.py. The file itself looks like this from urllib.parse import quote from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.contrib import messages from .forms import PostForm from .models import Post from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.shortcuts import render def post_create(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 form = PostForm(request.POST or None, request.FILES or None) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, 'Successfully Created') return HttpResponseRedirect(instance.get_absolute_url()) context = { 'form': form, } return render(request, 'posts/post_form.html', context) def post_detail(request, id=None): instance = get_object_or_404(Post, id=id) share_string = quote(instance.content) context = { 'title': instance.title, 'instance': instance, 'share_string': share_string } return render(request, 'posts/post_detail.html', context) def post_list(request): queryset_list = Post.objects.all() paginator = Paginator(queryset_list, 5) page = request.GET.get('page') queryset = paginator.get_page(page) context = { 'object_list': queryset, 'title': 'List' } return render(request, 'posts/post_list.html', context) def post_update(request, id=None): if not request.user.is_staff or not request.user.is_superuser: raise Http404 instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, request.FILES or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() messages.success(request, 'ItemSaved', extra_tags='…
has comment: http://stackoverflow.com/comment/84908106
has title: Error in Basic User Permissions in Django blog
score: 0
has comment: http://stackoverflow.com/comment/84901770
type: UnansweredQuestion
tagged with: django
tagged with: python

pip
tags question: http://stackoverflow.com/q/48815411
tags question: http://stackoverflow.com/q/48815152
tags question: http://stackoverflow.com/q/48893528
tags question: http://stackoverflow.com/q/48889786
tags question: http://stackoverflow.com/q/48856754
tags question: http://stackoverflow.com/q/48839504
tags question: http://stackoverflow.com/q/48869032
tags question: http://stackoverflow.com/q/48904263
tags question: http://stackoverflow.com/q/48940601
tags question: http://stackoverflow.com/q/48872120
tags question: http://stackoverflow.com/q/48901950
tags question: http://stackoverflow.com/q/48838606
tags question: http://stackoverflow.com/q/48870820
tags question: http://stackoverflow.com/q/48912500
tags question: http://stackoverflow.com/q/48876746
tags question: http://stackoverflow.com/q/48937645
tags question: http://stackoverflow.com/q/48924490
tags question: http://stackoverflow.com/q/48954337
tag name: pip
tags question: http://stackoverflow.com/q/48902662
tags question: http://stackoverflow.com/q/48831553
tags question: http://stackoverflow.com/q/48880649
tags question: http://stackoverflow.com/q/48935775
tags question: http://stackoverflow.com/q/48962952
tags question: http://stackoverflow.com/q/48958745
tags question: http://stackoverflow.com/q/48852137
tags question: http://stackoverflow.com/q/48871849
tags question: http://stackoverflow.com/q/48875480
tags question: http://stackoverflow.com/q/48876814
tags question: http://stackoverflow.com/q/48897562
tags question: http://stackoverflow.com/q/48941116
tags question: http://stackoverflow.com/q/48925659
tags question: http://stackoverflow.com/q/48872885
tags question: http://stackoverflow.com/q/48846844
tags question: http://stackoverflow.com/q/48820824
tags question: http://stackoverflow.com/q/48937722
type: Tag
tags question: http://stackoverflow.com/q/48826015
tags question: http://stackoverflow.com/q/48826618
tags question: http://stackoverflow.com/q/48884253
tags question: http://stackoverflow.com/q/48959380
tags question: http://stackoverflow.com/q/48886551
tags question: http://stackoverflow.com/q/48884204
tags question: http://stackoverflow.com/q/48956557
tags question: http://stackoverflow.com/q/48869196
tags question: http://stackoverflow.com/q/48949078
tags question: http://stackoverflow.com/q/48952993
tags question: http://stackoverflow.com/q/48879011
tags question: http://stackoverflow.com/q/48845803

http://stackoverflow.com/comment/84915137
has text: @martineau I’m doing the tests with my web browser window, so the title text should say chrome or something. The `HWND` that `GetForegroundWindow()` returns is the same regardless of the actual window focussed :/
comment on: http://stackoverflow.com/q/48939350
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48833583
has body: Wiktor's response worked perfect. I had to remove my extra %.
answers question: http://stackoverflow.com/q/48831730
score: 0
type: Answer

http://stackoverflow.com/a/48814637
has comment: http://stackoverflow.com/comment/84633100
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48814581
answers question: http://stackoverflow.com/q/48814581
score: 9
has comment: http://stackoverflow.com/comment/84637053
type: AcceptedAnswer
upvote count: 9
has body: Don't use groupby(); you'd get separate groups for those words with and without punctuation, which you then have to re-combine. Use a generator function: import string def sentence_groups(l, punctuation=tuple(string.punctuation)): group = [] for w in l: group.append(w) if w.endswith(punctuation): yield group group = [] if group: yield group The generator collects words from the input list until one ends with punctuation, at which point that whole group is yielded, after which the group is cleared for a new group. When iteration ends and there are still words in the group, that last group is yielded too (even though they don't have punctuation at the end). Use this together whith str.join() to produce your output: &gt;&gt;&gt; list1 = ['hello', 'how', 'are', 'you?', 'i', 'am', 'fine', 'thanks.', 'great!'] &gt;&gt;&gt; [' '.join(group) for group in sentence_groups(list1)] ['hello how are you?', 'i am fine thanks.', 'great!'] I used all punctuation in the string.punctuation string; this is quite broad: &gt;&gt;&gt; string.punctuation '!"#$%&amp;\'()*+,-./:;&lt;=&gt;?@[\\]^_`{|}~' Pass in a tuple of specific punctuation characters as the second argument if you wanted to narrow that down, or hardcode your own definition.
has comment: http://stackoverflow.com/comment/84634758
type: Answer
has comment: http://stackoverflow.com/comment/84636821

http://stackoverflow.com/a/62165649
has comment: http://stackoverflow.com/comment/109986672
has comment: http://stackoverflow.com/comment/109946338
has comment: http://stackoverflow.com/comment/109975928
downvote count: 0
has body: First we'll need to read the user's input after they read the question: hungry = input("Are you hungry? True or False \n") Now that we have their response in a variable, hungry, we're able to use it in some statements: if hungry.lower() == "true": Notice the use of .lower(), which will take their string, regardless of capitalisation of letters, and convert it all to lowercase. This means that whether they enter "True", "tRue" or "TRUE", they will all evaluate to being True if compared to the lowercase counterpart "true". What's important when doing this, is to always have your comparison string be lowercase as well. because if you tried evaluating "true" against "True", it would return False. Using this knowledge, we're able to put it all together and print out what we want: hungry = input("Are you hungry? True or false \n") if hungry.lower() == "true": print("Feed me!") else: print("I'm not hungry.")
has comment: http://stackoverflow.com/comment/109948097
type: Answer
answers question: http://stackoverflow.com/q/48817461
score: 1
upvote count: 1

http://stackoverflow.com/q/48821533
type: AnsweredQuestion
has body: I have a dict of values, which I want to sum up. I have used this code to achieve this countTest = Counter(chain.from_iterable(e.items() for e in tickets)) result = [{'name': key, 'value': value} for key, value in countTest.items()] print(json.dumps(result, sort_keys=True, indent=4)) This produces the following values, which is the values that I expect. [ { "name": [ "ticket", "Class A" ], "value": 1 }, { "name": [ "ticket", "Class B" ], "value": 2 }, { "name": [ "ticket", "Class C" ], "value": 3 } ] However I would like a more dense representation of this, preferably like this { "ticket": { “Class A”: 1, “Class B”: 2, “Class C”: 3 } } How can I achieve this?
has title: How to get a more dense representation from Counter?
possible better answer: http://stackoverflow.com/a/48821736
type: Question
score: 0
has answer: http://stackoverflow.com/a/48821609
answer count: 3
has answer: http://stackoverflow.com/a/48821676
has comment: http://stackoverflow.com/comment/84646576
tagged with: python
has answer: http://stackoverflow.com/a/48821736
accepted answer: http://stackoverflow.com/a/48821609

http://stackoverflow.com/q/48951818
has body: I have several files that can be downloaded on my website. The HTML content refers to this method: from flask_httpauth import HTTPBasicAuth auth = HTTPBasicAuth() ... @app.route('/customer_section/download/&lt;product_id&gt;') @login_required def customer_download_file(product_id): # get the company the currently logged in user belongs to user_company = current_user.company # get the product entity product = Product.query.filter_by(id=product_id).first_or_404() # now get the company, the product belongs to product_company = product.project.owner if current_user.is_admin or (not current_user.is_admin and product_company.id == user_company.id): print("Splitting Path %s to folder and filename..." % product.path) # Split the path to folder and filename folder, filename = os.path.split(product.path) return send_from_directory(folder, filename, mimetype="application/octet-stream", as_attachment=True) else: # Unauthorized abort(401) This works great when the user logs in via flask_login in my login view. So the user logs in via my login view, then somehow navigates through my website, and the clicks on a download link to download a file. But what if a user tries to download a file directly? I'd then like to show the user a popup so the user can enter his credentials and may download the file. Is this possible? Sorry, I guess my description was not clear enough: I‘m not trying to show a custom popup view of mine when a user calls my download method. I‘d like the default (browser specific) Basic Authentication popup to appear if a non logged in user tries to call that specific url. As if I had a restrictive .htaccess file that ensures that only authorized users continue. If the user reaches the same url via my webpage (after logging in, this method simply returns the file stream).
answer count: 1
accepted answer: http://stackoverflow.com/a/48993493
tagged with: flask
has title: Show basic auth popup if user is not logged in
tagged with: python
tagged with: flask-login
linked to: http://stackoverflow.com/q/33724161
score: 0
has answer: http://stackoverflow.com/a/48993493
type: AnsweredQuestion
type: Question

http://stackoverflow.com/q/48811203
tagged with: python
has comment: http://stackoverflow.com/comment/84626458
has title: Converting image to Greyscale
has comment: http://stackoverflow.com/comment/84627807
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48814031
tagged with: image-processing
type: Question
has comment: http://stackoverflow.com/comment/84627896
tagged with: python-imaging-library
has comment: http://stackoverflow.com/comment/84626152
tagged with: grayscale
tagged with: rgb
has comment: http://stackoverflow.com/comment/84626013
has comment: http://stackoverflow.com/comment/84625922
score: 0
has body: I know that we can convert RGB image to greyscale by using PIL or PILLOW. We can do this by importing Image. One way that can be used to do this is as follows. from PIL import Image img=Image.open('Sample.jpg').convert('LA') img.save('greyscale.png') Can we convert RGB image to greyscale without using a python package? I wan to learn that way. Any help, how can I do this?
answer count: 1
has comment: http://stackoverflow.com/comment/84626313
has answer: http://stackoverflow.com/a/48814031

http://stackoverflow.com/comment/84916505
has text: @LiuJJ, check whether required node located inside an iframe
comment on: http://stackoverflow.com/q/48953127
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84647359
score: 0
type: Comment
type: QuestionComment
has text: In lexicographic comparison "10" < "3". Try: `if int(row["year"][:-1]) > 3:`
comment on: http://stackoverflow.com/q/48822061

http://stackoverflow.com/q/48951151
type: UnansweredQuestion
upvote count: 10
tagged with: python
downvote count: 0
type: Question
linked to: http://stackoverflow.com/q/54174938
has title: marshmallow flatten nested objects
score: 10
tagged with: marshmallow
has body: I have objects that look a little something like: source = { id: 123, objects: [ { random_data: aaaa, actual_data: { useful: 111, ... } }, { random_data: bbbb, actual_data: { useful: 222, ... } } ] } and while I could easily serialize that as is, it would be far more useful to transform it into the following format: dest = { id: 123, objects: [ { useful: 111, ... }, { useful: 222, ... } ] } Given I already have a schema for the innermost object (actual_data in the source above - it is a lot more complex than my example shows), what is the best way of flattening that nested object so I only get the objects from actual_data without the extra depth? I would have thought it would be something like objects = Nested(UsefulSchema, many=True, load_from"&lt;something&gt;.useful_data") but I have been unable to find a solution without preprocessing the data. NB I have simplified my example a lot to give the simplest form of my problem. In my actual code, the source data is a large list of similar objects from sqlalchemy.
has answer: http://stackoverflow.com/a/57703338
answer count: 1
favorite count: 0

http://stackoverflow.com/a/48869963
upvote count: 6
score: 6
accepted answer of: http://stackoverflow.com/q/48825785
answers question: http://stackoverflow.com/q/48825785
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I am answering my own question. I found the issue! What I needed to do is tf.unstack() the label like this: label = tf.unstack(features['label']) label = label[0] before I give it to tf.equal(): result = tf.reshape(tf.equal(label, 'some_label_value'), []) I suppose the problem was that the label is defined as an array with one element of type string tf.FixedLenFeature([1], tf.string), so in order to get the first and single element I had to unpack it (which creates a list) and then get the element with index 0, correct me if I'm wrong.

http://stackoverflow.com/comment/84884402
score: 0
type: Comment
type: AnswerComment
has text: @pault You are correct. I just have a Python 2.7 project open in PyCharm so that is what console I'm currently using. Sometimes I also like using `operator.truediv` for Python 2/3 compatibility since it's very obvious.
comment on: http://stackoverflow.com/a/48938697

http://stackoverflow.com/q/48843223
has comment: http://stackoverflow.com/comment/84690597
type: Question
has comment: http://stackoverflow.com/comment/84691048
has comment: http://stackoverflow.com/comment/84691470
upvote count: 0
answer count: 1
favorite count: 0
has title: Python 3 File Input Syntax Error
has body: I put all my input into a file and went into the terminal to run a program getting input from a file but I got a syntax error. Where did I go wrong? Thanks. Terminal Image Here is the main program. # Create a list of 99 Boolean elements with value False isCovered = 99 * [False] endOfInput = False while not endOfInput: # Read numbers as a string from the console s = input("Enter a line of numbers separated by spaces: ") items = s.split() # Extract items from the string lst = [eval(x) for x in items] # Convert items to numbers for number in lst: if number == 0: endOfInput = True else: # Mark its corresponding element covered isCovered[number - 1] = True # Check whether all numbers (1 to 99) are covered allCovered = True # Assume all covered initially for i in range(99): if not isCovered[i]: allCovered = False # Find one number not covered break # Display result if allCovered: print("The tickets cover all numbers") else: print("The tickets don't cover all numbers") Here is the input file: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 91 92 93 94 95 96 97 98 99 0
tagged with: python
score: -2
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48844311
type: UnansweredQuestion
downvote count: 2

http://stackoverflow.com/a/48824235
has comment: http://stackoverflow.com/comment/84653153
downvote count: 0
has body: I don't pretend to have the solution to generate the proper hour shift according to the time zone, but I can explain what happens here. As hinted in Python timezone '%z' directive for datetime.strptime() not available answers: strptime is implemeted in pure python so it has a constant behaviour strftime depends on the platform/C library it was linked against. On my system (Windows, Python 3.4), %z returns the same thing as %Z ("Paris, Madrid"). So when strptime tries to parse it back as digits, it fails. Your code gives me: ValueError: time data '2018-02-16T10:00:49ZParis, Madrid' does not match format '%Y-%m-%dT%H:%M:%SZ%z' It's system dependent for the generation, and not for the parsing. This dissymetry explains the weird behaviour.
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84652122
has comment: http://stackoverflow.com/comment/84652014
has comment: http://stackoverflow.com/comment/84653903
score: 1
has comment: http://stackoverflow.com/comment/84653401
answers question: http://stackoverflow.com/q/48823828

http://stackoverflow.com/comment/84857623
comment on: http://stackoverflow.com/q/48925401
score: 0
has text: this is jython which you are importing have you started jar as a service....
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48840378
upvote count: 41
possible better answer: http://stackoverflow.com/a/48842348
tagged with: python
type: AnsweredQuestion
score: 41
tagged with: aiohttp
tagged with: http://stackoverflow.com/tag/json
type: Question
has answer: http://stackoverflow.com/a/48841071
has title: Python - Attempt to decode JSON with unexpected mimetype:
answer count: 2
has body: I recently swapped over from requests to aiohttp because I couldn't use it in asyncio loops. The swap went perfectly and everything goes well except for one thing. My console is full of Attempt to decode JSON with unexpected mimetype: and Attempt to decode JSON with unexpected mimetype: txt/html; charset=utf-8 My code has a list of sites it goes too and grabs JSON from, Each site is different but my loop is basically the same for each of them, Ive simplified it here: PoolName = "http://website.com" endpoint = "/api/stats" headers = "headers = {'content-type': 'text/html'}" #Ive tried "application/json" and no headers async with aiohttp.get(url=PoolName+endpoint, headers=headers) as hashrate: hashrate = await hashrate.json() endVariable = hashrate['GLRC']['HASH'] It works perfectly, connects to the site grabs the json and sets endVariable correctly. but for some reason Attempt to decode JSON with unexpected mimetype: prints every time it goes through the loop. Which is annoying because it prints stats to the console and they get lost in the the errors each time it grabs a sites json Is there a way to fix this error or to hide it?
downvote count: 0
has answer: http://stackoverflow.com/a/48842348
favorite count: 0
accepted answer: http://stackoverflow.com/a/48841071
tagged with: python-3.x
tagged with: python-asyncio

http://stackoverflow.com/comment/84755734
comment on: http://stackoverflow.com/q/48875458
type: QuestionComment
type: Comment
has text: You can't reasonably create a list of strings of that size. If you have billions of elements you'll have to work with external storage. Put them in a file, use a file-based sort to get the file in sequence, then read through the resulting sorted file constructing your summary list.
score: 1

http://stackoverflow.com/a/48937400
has body: def a(): print('a returned') def b(): print('b returned') def c(): print('c returned') funcs = [a, b, c] def sample_func(x, funcs=None): if x &lt; 0: return None thresholds = [.40, .60] for i, threshold in enumerate(thresholds): if x &lt;= threshold: return funcs[i]() return funcs[len(thresholds)]() sample_func(.1, funcs) returns a returned sample_func(.65, funcs) returns c returned
answers question: http://stackoverflow.com/q/48937024
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/q/48850764
has comment: http://stackoverflow.com/comment/84705080
type: Question
tagged with: numpy
tagged with: opencv
tagged with: image
has comment: http://stackoverflow.com/comment/84705032
score: 0
tagged with: pandas
has body: I have a 512x512 .png radar image name png_image I also have a csv rainfall_colour_table with the following headers B, G, R, rainfall_mm, that I can use to link colour values to rainfall intensity values. What is the best way to read png_image and convert it to a 512x512 Pandas DataFrame where the values are rainfall_mm from rainfall_colour_table. I have used the following approach. from urllib.request import urlopen, Request import cv2 import os import numpy as np import pandas as pd # NOTE: the ftp sourve of the png changes every 30 min # get any current .png file name from the website ftp://ftp.bom.gov.au/anon/gen/radar// # and set the below variable file_name = # get connection to file input_url = "ftp://ftp.bom.gov.au/anon/gen/radar//" + file_name req = Request(input_url) req_html = urlopen(req).read() # read file radar_image = np.fromstring(req_html, np.uint8) # read byte image radar_image = cv2.imdecode(radar_image, cv2.IMREAD_COLOR) # convert to numppy array # OS agnostic relative file path # get the current directory path base_dir = os.path.dirname(__file__) # OS agnostic relative file path # load colour to mm/hr concurrency table rainfall_colour_table = os.path.join(os.sep, base_dir, 'sample_data', 'radar_colours.csv') rainfall_colour_df = pd.read_csv(rainfall_colour_table) rainfall_colour_df.set_index(['B', 'G', 'R'], inplace=True) # switch colours with rain intensity radar_df = pd.DataFrame(rainfall_colour_df.loc[list(map(tuple, pin))].rainfall.values for pin in radar_image) radar_df.columns = ['pixel_col_' + str(col) for col in radar_df.columns] The rainfall_colour_table.csv colour_id,rainfall,B,G,R 2,1.5,255,180,180 3,2.5,255,120,120 4,4,255,20,20 5,6,195,216,0 6,10,144,150,0 7,15,102,102,0 8,20,0,255,255 9,35,0,200,255 10,50,0,150,255 11,80,0,100,255 12,120,0,0,255 13,200,0,0,200 14,300,0,0,120 15,360,0,0,40
has comment: http://stackoverflow.com/comment/86235872
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84705996
answer count: 0
linked to: http://stackoverflow.com/q/47038538
has title: Convert .png file to pandas DataFrame

http://stackoverflow.com/a/48856442
has comment: http://stackoverflow.com/comment/105376109
has comment: http://stackoverflow.com/comment/101617049
has comment: http://stackoverflow.com/comment/105376860
upvote count: 24
has body: In a nutshell, if you use an offset like "2D" (2 days), pandas will use the datetime info in the index (if available), potentially accounting for any missing rows or irregular frequencies. But if you use a simple int like 2, then pandas will treat the index as a simple integer index [0,1,2,...] and ignore any datetime info in the index. A simple example should make this clear: df=pd.DataFrame({'x':range(4)}, index=pd.to_datetime(['1-1-2018','1-2-2018','1-4-2018','1-5-2018'])) x 2018-01-01 0 2018-01-02 1 2018-01-04 2 2018-01-05 3 Note that (1) the index is a datetime, but also (2) it is missing '2018-01-03'. So if you use a plain integer like 2, rolling will just look at the last two rows, regardless of the datetime value (in a sense it's behaving like iloc[i-1:i] where i is the current row): df.rolling(2).count() x 2018-01-01 1.0 2018-01-02 2.0 2018-01-04 2.0 2018-01-05 2.0 Conversely, if you use an offset of 2 days ('2D'), rolling will use the actual datetime values and accounts for any irregularities in the datetime index. df.rolling('2D').count() x 2018-01-01 1.0 2018-01-02 2.0 2018-01-04 1.0 2018-01-05 2.0 Also note, you need the index to be sorted in ascending order when using a date offset, but it doesn't matter when using a simple integer (since you're just ignoring the index anyway).
accepted answer of: http://stackoverflow.com/q/48855400
score: 24
has comment: http://stackoverflow.com/comment/105376828
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/109300079
answers question: http://stackoverflow.com/q/48855400
has comment: http://stackoverflow.com/comment/101602376
type: Answer

http://stackoverflow.com/comment/84923309
score: 0
type: Comment
has text: Thank you. I just noticed that when using your solution, it's even not mandatory to create a table with `default null`: even if I remove all `default null`, it will still work with your solution, all these values will default to `None` anyway!
type: AnswerComment
comment on: http://stackoverflow.com/a/48958161

http://stackoverflow.com/a/49037691
downvote count: 0
has comment: http://stackoverflow.com/comment/85082659
score: 9
accepted answer of: http://stackoverflow.com/q/48939937
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48939937
upvote count: 9
has body: I am using a python library call pydub: pydub github link They were built upon ffmpeg
type: Answer

http://stackoverflow.com/comment/84764588
type: Comment
comment on: http://stackoverflow.com/a/48867114
score: 0
type: AnswerComment
has text: Well in your specific case I would go with Bash. I understand if you are not familiar with Bash this may be scary, Bash is really not easy to learn, especially for somebody without strong scripting / development skills. But anyway, from what I understood, Bash is what you really want.

http://stackoverflow.com/q/48837953
has answer: http://stackoverflow.com/a/48838128
answer count: 4
has title: Power of a number tail recursion
has comment: http://stackoverflow.com/comment/84686532
tagged with: recursion
has body: I am trying to calculate power of a num using tail recursion with a running time of log(n). From what I understand, the difference between using power // 2 instead of power - 1 is to reduce the running time. Thus when I calculate the value, I need to multiply the old value with two other sum instead of just one. My code works find until it reaches power_of(2,6) def power_of(num,power,value = 1): if power == 0: return 1 elif power == 1: return value elif power % 2 != 0: return power_of(num, power // 2 , value * num * num * num) else: return power_of(num, power // 2 , value * num * num) power_of(2,6)
has answer: http://stackoverflow.com/a/65926816
type: Question
downvote count: 0
tagged with: data-structures
score: 2
has answer: http://stackoverflow.com/a/48838093
has comment: http://stackoverflow.com/comment/84680814
favorite count: 0
has answer: http://stackoverflow.com/a/48838705
tagged with: tail-recursion
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48879914
type: Answer
has body: Replace cv2.putText(img,str(sampleNum + 1), (x,y+h+30),font, (255,255,255)) with cv2.putText(img, str(sampleNum + 1), (x,y+h+30), font, 2, 255) More Info on putText method
accepted answer of: http://stackoverflow.com/q/48877502
score: 0
answers question: http://stackoverflow.com/q/48877502
type: AcceptedAnswer

http://stackoverflow.com/q/48942155
has comment: http://stackoverflow.com/comment/84891721
has comment: http://stackoverflow.com/comment/84891814
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84891624
tagged with: tensorflow
type: Question
score: 1
has body: I am trying to install tensorflow on windows 10. I followed this Install TensorFlow with GPU for Windows 10 tutorial step-by-step. No error while I followed all the steps. But when I comleted the entire process and tried to import tensorflow I got the following error: import tensorflow as tf Traceback (most recent call last): File "C:\Users\salma\AppData\Local\conda\conda\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\platform\self_check.py", line 62, in preload_check ctypes.WinDLL(build_info.nvcuda_dll_name) File "C:\Users\salma\AppData\Local\conda\conda\envs\tensorflow-gpu\lib\ctypes__init__.py", line 348, in init self._handle = _dlopen(self._name, mode) OSError: [WinError 126] The specified module could not be found During handling of the above exception, another exception occurred: Traceback (most recent call last): File "", line 1, in File "C:\Users\salma\AppData\Local\conda\conda\envs\tensorflow-gpu\lib\site-packages\tensorflow__init__.py", line 24, in from tensorflow.python import * File "C:\Users\salma\AppData\Local\conda\conda\envs\tensorflow-gpu\lib\site-packages\tensorflow\python__init__.py", line 49, in from tensorflow.python import pywrap_tensorflow File "C:\Users\salma\AppData\Local\conda\conda\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 30, in self_check.preload_check() File "C:\Users\salma\AppData\Local\conda\conda\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\platform\self_check.py", line 70, in preload_check % build_info.nvcuda_dll_name) ImportError: Could not find 'nvcuda.dll'. TensorFlow requires that this DLL be installed in a directory that is named in your %PATH% environment variable. Typically it is installed in 'C:\Windows\System32'. If it is not present, ensure that you have a CUDA-capable GPU with the correct driver installed. What am I missing? Also, please let me know if there is any other better way of installing tensorflow on windows, on Ubuntu it's way more simpler.
downvote count: 0
has title: Install/Setup Tensorflow on Windows
favorite count: 0
has comment: http://stackoverflow.com/comment/84891198
type: UnansweredQuestion
tagged with: windows
tagged with: python

vote
type: Tag
tag name: vote
tags question: http://stackoverflow.com/q/48855674

http://stackoverflow.com/comment/84720173
type: QuestionComment
comment on: http://stackoverflow.com/q/48858269
has text: This works on version 0.22. You may want to upgrade.
score: 1
type: Comment

http://stackoverflow.com/a/48861443
accepted answer of: http://stackoverflow.com/q/48861268
has body: Using while True for such cases is a bad habit. You should use cron Task Scheduler instead. Back to your code - if it works fine for few hours it means there's a bug in the #Lots more code part. There's no problem with the time.sleep() itself.
has comment: http://stackoverflow.com/comment/84726081
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84725965
score: 0
answers question: http://stackoverflow.com/q/48861268
has comment: http://stackoverflow.com/comment/84726190
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84725877
type: Answer

http://stackoverflow.com/q/48863307
type: Question
answer count: 2
has title: "Backend not found" django social auth
favorite count: 0
accepted answer: http://stackoverflow.com/a/48863557
upvote count: 7
has body: When I'm trying process social authorization with Google or Facebook, I get this error without trace for both socials. Backend not found Someone can find an mistake in social_django settings? settings INSTALLED_APPS = [ ... 'social_django', ... ] MIDDLEWARE_CLASSES = [ ... 'social_django.middleware.SocialAuthExceptionMiddleware' ] TEMPLATES = [ { ... 'OPTIONS': { 'context_processors': [ ... 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] AUTHENTICATON_BACKENDS = ( 'social_core.backends.facebook.FacebookOAuth2', 'social_core.backends.google.GoogleOAuth2', 'users.backends.AuthBackend', ) SOCIAL_AUTH_URL_NAMESPACE = 'social' SOCIAL_AUTH_FACEBOOK_KEY = '...' SOCIAL_AUTH_FACEBOOK_SECRET = '...' SOCIAL_AUTH_GOOGLE_OAUTH2_KEY ='...' SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = '...' urls.py urlpatterns = [ url('', include('social_django.urls', namespace='social')), ... ] template FB GOOGLE</a users.backend.AuthBackend from django.db.models import Q from django.contrib.auth.backends import ModelBackend from users.models import User class AuthBackend(ModelBackend): supports_object_permissions = True supports_anonymous_user = False supports_inactive_user = False def authenticate(self, username, password): try: user = User.objects.filter(is_active=True).get(Q(email=username) | Q(phone_number=username)) except User.DoesNotExist: return None return user if user.check_password(password) else None
has answer: http://stackoverflow.com/a/48863557
has comment: http://stackoverflow.com/comment/84729853
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84729751
possible better answer: http://stackoverflow.com/a/53259901
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/53259901
downvote count: 0
score: 7

http://stackoverflow.com/comment/84841664
has text: A process down the line and out of my hands takes only this format. The array is the end result of quite a lot of linear algebra done in numpy, so I am left at the end with an array in the wrong format.
type: QuestionComment
comment on: http://stackoverflow.com/q/48917460
score: 0
type: Comment

http://stackoverflow.com/q/48923495
type: Question
has answer: http://stackoverflow.com/a/48923844
score: 0
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48924443
has title: Multiple histogram based on groupby and for different column
type: UnansweredQuestion
tagged with: python
has body: I am just new in pandas. I have the following dataframe. import pandas as pd import numpy as np Group = ['A','B','A','B','B','A','A','B','A','B'] Weight = np.random.uniform(0.1, 2, size=10) Parameter_1 = np.random.uniform(0, 100, size=10) Parameter_2 = np.random.randint(low =1, high = 5, size=10) Parameter_3 = np.random.randint(low =1, high = 5, size=10) data = pd.DataFrame({'Group':Group, 'Weight':Weight,'Parameter_1':Parameter_1,'Parameter_2':Parameter_2, 'Parameter_3':Parameter_3}) I am trying to create a separate PDF for each group containing the histograms based on Parameter_1, Parameter_2, Parameter_3 and their Weight. Not quite sure as attack the problem :( Thanks Mick

http://stackoverflow.com/comment/84861050
type: Comment
type: QuestionComment
has text: There might be data that don't fall into those 3 classes. Because I labeled it a1,a2,a3,None. And I want to remove 'None' data.
comment on: http://stackoverflow.com/q/48925311
score: 0

http://stackoverflow.com/comment/97374121
has text: Can you provide the entire code? I'm having the same problem as you
type: AnswerComment
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48846445

http://stackoverflow.com/q/48818380
has answer: http://stackoverflow.com/a/48818752
tagged with: datetime
possible better answer: http://stackoverflow.com/a/48818483
has answer: http://stackoverflow.com/a/48818411
tagged with: python
has answer: http://stackoverflow.com/a/48818511
accepted answer: http://stackoverflow.com/a/48818469
type: AnsweredQuestion
has title: Find maximum value of time in list containing tuples of time in format ('hour', 'min', 'AM/PM')
tagged with: list
downvote count: 0
has body: I have a list of of tuples that represent different times timeList = [('4', '12', 'PM'), ('8', '23', 'PM'), ('4', '03', 'AM'), ('1', '34', 'AM'), ('12', '48', 'PM'), ('4', '13', 'AM'), ('11', '09', 'AM'), ('3', '12', 'PM'), ('4', '10', 'PM')] I want to return the max from the list, after some searching I realized I could use the key in max to search by the AM or PM first. print(max(timeList, key = operator.itemgetter(2))) When I run this however, I'm getting the wrong max ('4', '12', 'PM') I thought about it, and not only does it not make sense, given that 8:23 should be max, but I also realized that 12:48 would probably return max since it's a PM and also technically greater than 8 in my search. That being said, how might I get this max to find the latest possible time, given formatting of the list can not be changed.
has answer: http://stackoverflow.com/a/48818469
type: Question
score: 5
has comment: http://stackoverflow.com/comment/84640670
tagged with: max
has answer: http://stackoverflow.com/a/48818483
answer count: 6
tagged with: sorting
has answer: http://stackoverflow.com/a/48819038
has comment: http://stackoverflow.com/comment/84642150
has comment: http://stackoverflow.com/comment/84641978
favorite count: 0
has comment: http://stackoverflow.com/comment/84640652
upvote count: 5

http://stackoverflow.com/comment/84719189
type: Comment
comment on: http://stackoverflow.com/q/48857769
has text: @zwol ran the commands you suggested and edited the question
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84884286
score: 0
comment on: http://stackoverflow.com/q/48938632
type: Comment
has text: @roganjosh I know but it kind of works nicely here. Caveat for OP: [Why is eval bad](https://stackoverflow.com/questions/1832940/why-is-using-eval-a-bad-practice)?
type: QuestionComment

http://stackoverflow.com/comment/84755871
has text: SO is for coding issues, where is your code/attempts ?
score: 1
comment on: http://stackoverflow.com/q/48875911
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84795330
comment on: http://stackoverflow.com/q/48892583
has text: Thanks my dude, you've really given me a lot to go off of. Now all I've got to do is get around this 500 error. I'm guessing its because I'm not handling the `__RequestVerificationToken` properly.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84790535
type: QuestionComment
type: Comment
score: 1
has text: Consider what each of the following does: 1) `[i for i in 'foobar']` 2) `[i for i in ['foobar']]`
comment on: http://stackoverflow.com/q/48892475

http://stackoverflow.com/q/48945589
type: UnansweredQuestion
tagged with: django
type: Question
score: 3
tagged with: database
answer count: 1
downvote count: 0
favorite count: 0
tagged with: postgresql
has body: According to Django docs: Usually, if another transaction has already acquired a lock on one of the selected rows, the query will block until the lock is released. If this is not the behavior you want, call select_for_update(nowait=True). This will make the call non-blocking. If a conflicting lock is already acquired by another transaction, DatabaseError will be raised when the queryset is evaluated. I was experimenting with this but found a strange behavior. Below code when run simultaneously doesn't raise the error but works in a blocking manner. def test4(): with transaction.atomic(): WorkflowCallContact.objects.select_for_update(nowait=True).filter(id__in=[1,2,3,4]).update(number="22222") time.sleep(10) list(WorkflowCallContact.objects.filter(id__in=[1,2,3,4])) To test, I am just opening to shells and calling the same function parallelly. But instead of throwing DatabaseError on the second call because of nowait=True, the call becomes blocked for 10 secs. Database I'm using: postgres Django version: 1.9
has answer: http://stackoverflow.com/a/66577322
has title: Django select_for_update with nowait=True not raising DatabaseError for conflicting transctions
tagged with: python
has comment: http://stackoverflow.com/comment/84899305
upvote count: 3

http://stackoverflow.com/comment/84745121
comment on: http://stackoverflow.com/a/48868661
type: Comment
has text: Ugh. I'm dumb. This is all in a test script right now, and I was accidentally re-redefining df1 before outputting it again. This does indeed work, but I imagine because the min isn't exactly 2.4 ms, it is slightly changing the time stamps. It's also more than doubling the length of the DataFrame, because for each gap it's adding NaNs at 2.4 ms (when you really only need one). ...
type: AnswerComment
score: 0

http://stackoverflow.com/q/48920014
answer count: 5
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/84846365
linked to: http://stackoverflow.com/q/21767529
has title: how to extract the min value and max value from csv file using python
tagged with: list
has answer: http://stackoverflow.com/a/48920108
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/70941887
has comment: http://stackoverflow.com/comment/84846375
tagged with: max
upvote count: 5
score: 4
tagged with: min
has answer: http://stackoverflow.com/a/48920562
has comment: http://stackoverflow.com/comment/84846389
has answer: http://stackoverflow.com/a/48921053
favorite count: 0
has body: i have a python script that read from csv file and append the requested columns into 2 empty list. after that i need to extract the minimum and maximum value of the columns extracted. i wrote this code but it seems not working be cause the result is empty . code: import csv mydelimeter = csv.excel() mydelimeter.delimiter=";" myfile = open("C:/Users/test/Documents/R_projects/homework/rdu-weather-history.csv") myfile.readline() myreader=csv.reader(myfile,mydelimeter) mywind,mydate=[],[] minTemp, maxTemp = [],[] for row in myreader: print(row[1],row[2]) minTemp.append(row[1]) maxTemp.append(row[2]) print ("min value element : ", min(minTemp)) print ("max value element : ", min(maxTemp))
has answer: http://stackoverflow.com/a/48920169

http://stackoverflow.com/q/48840876
has comment: http://stackoverflow.com/comment/84686112
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84686503
tagged with: python
type: UnansweredQuestion
has title: why pandas change (large)numbers when it exports data to csv and excel
type: Question
has comment: http://stackoverflow.com/comment/84686180
has answer: http://stackoverflow.com/a/61442489
linked to: http://stackoverflow.com/q/42006890
has comment: http://stackoverflow.com/comment/84687297
has comment: http://stackoverflow.com/comment/84686172
has body: I have a dataframe with one column number: df = pd.DataFrame([34032872653290886,57875847776839336],['A','B'],columns=['numbers']) when I save dataframe to excel and to csv, saved data are shown as scientific number and became 34032872653290900, 57875847776839300. To convert df I use following codes. df.to_excel('a1.xlsx') df.to_csv('a1.csv') Is it a bug? Or should I change a setting? I check my code from two system(Mac and windows) and my pandas version is '0.20.2'.
has comment: http://stackoverflow.com/comment/84686340
has comment: http://stackoverflow.com/comment/108689631
has comment: http://stackoverflow.com/comment/84686143
answer count: 1

http://stackoverflow.com/comment/84825693
has text: There is a tool called [GumTreeDiff](https://github.com/GumTreeDiff/gumtree/issues/31) but the python support is not yet available. Is this what you are looking for?
comment on: http://stackoverflow.com/q/48907886
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48812547
downvote count: 0
has comment: http://stackoverflow.com/comment/84628918
type: Answer
answers question: http://stackoverflow.com/q/48812501
score: 2
has body: You can use inequality expression: a[ (b + diff &gt;= a) &amp; (a &gt;= b - diff) ]
upvote count: 2

http://stackoverflow.com/comment/84867844
score: 0
has text: Not that obvious ??? Simply test your code !
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48930069

http://stackoverflow.com/a/48871080
type: Answer
has body: Your write statement is out of indent. file = open("text.txt","a") n=0 while n&lt;=5: y = str(input("name: ")) x = int(input("marks: ")) result = "Pass" if x&lt;35: result = "Fail" print(y,result) file.write('"{}#{}"/n', format(y,result)) elif 35&lt;=x&lt;=54: result = "S" print(y,result) file.write('"{}#{}"/n', format(y,result)) elif 55&lt;=x&lt;=64: result = "C" print(y,result) file.write('"{}#{}"/n', format(y,result)) elif 65&lt;=x&lt;=74: result = "B" print(y,result) file.write('"{}#{}"/n', format(y,result)) elif (75&lt;=x&lt;=100): result = "A" print(y,result) file.write('"{}#{}"/n', format(y,result)) else: print ("Invalid Enter") n = n+1 file.close
score: 0
answers question: http://stackoverflow.com/q/48871015

http://stackoverflow.com/a/48896111
answers question: http://stackoverflow.com/q/48895867
accepted answer of: http://stackoverflow.com/q/48895867
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: Could You add some code and file structure? You need empty __init__.py files in folders to make them python package, so imports will work for modules You can import also: from app.folder1 import name [as sub_name]
has comment: http://stackoverflow.com/comment/84798175
score: 2
upvote count: 2

http://stackoverflow.com/comment/84638039
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48816938
has text: You're welcome, I've added a minor change to address the issue that you have a list of arrays of numbers, and not just a list of numbers.
score: 0

http://stackoverflow.com/q/48814864
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84634805
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84634905
type: Question
has comment: http://stackoverflow.com/comment/84635004
has title: How to fix Tkinter canvas overlapping image?
has body: Hey guys i have a simple Chessboard made in python with Tkinter, i am trying to add images of pieces to the board at a specific row and column but the canvas keeps overlapping the image. Please help! Here is my board code: class GameBoard(tk.Frame): def __init__(self, parent, rows=8, columns=8, size=75, color1="white", color2="lightgrey"): '''size is in pixels''' self.rows = rows self.columns = columns self.size = size self.color1 = color1 self.color2 = color2 self.pieces = {} canvas_width = columns * size canvas_height = rows * size tk.Frame.__init__(self, parent) self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0, width=canvas_width, height=canvas_height, background="white") self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2) And here is my image placing code, i have put the image placement at 600 by 600 just for testing purposes. self.canvas.WhiteKnight = tk.PhotoImage(file = 'E:\\Final Project + Report\\Pieces\\WhiteKnight.png') self.canvas.create_image(600,600, image = self.canvas.WhiteKnight, anchor = 'c') Here you can see the image showing but being overlapped Any help would be much appreciated!
score: 0
answer count: 1
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48815587
accepted answer: http://stackoverflow.com/a/48815587
tagged with: python
has comment: http://stackoverflow.com/comment/84634522

http://stackoverflow.com/q/48926156
score: 0
tagged with: pandas
tagged with: python
has body: Currently met with a problem when handling a comparison betweem two data frames. df1 contains rows I would like to drop with a value is found in df2 df1 = col1: (cat, dog, mouse, rabbit, shrew, shark, deer, human) df2 = col3: (mouse, rabbit) From the above example data frames i would like to remove rows featuring 'mouse' and 'rabbit' from df1. I have tried: df1.loc[df1['col1'] != df2['col3']] However this requires both series to be the same length and only compares rows in df1 to the row in df2 with the same index (not hashable) Any help would be appreciated. I am mainly working with pandas &amp; numpy
answer count: 0
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/28901683
has title: Look for value in df1('col1') is equal to any value in df2('col3') and remove row from df1 if True [Python]
has comment: http://stackoverflow.com/comment/84858309
tagged with: dataframe
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/28901683
has comment: http://stackoverflow.com/comment/84861200

http://stackoverflow.com/comment/84699872
score: 0
type: QuestionComment
has text: `for i in range()` and `for i in x` - See a problem there anywhere? Read the code you write. Also read the words in the error message: *'int' object is not iterable" at line 8* - they tell you exactly what the problem is and exactly where it is located. The message doesn't exist just to take up space on your screen.
type: Comment
comment on: http://stackoverflow.com/q/48847939

http://stackoverflow.com/comment/84749725
type: QuestionComment
has text: With numpy arrays there's an added layer of 'view' versus 'copy': https://stackoverflow.com/questions/48871320/why-does-using-on-numpy-arrays-modify-the-original-array.
comment on: http://stackoverflow.com/q/48872113
score: 0
type: Comment

http://stackoverflow.com/comment/84768148
has text: Couldn't converting the value to seconds and add it to today's zero-hour timestamp, then adding that timestamp to a Time Series help? It is, after all, the meaning of the value you use, right?
comment on: http://stackoverflow.com/q/48881901
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84635855
type: QuestionComment
comment on: http://stackoverflow.com/q/48815924
has text: `(j[0])` isn't a tuple; it's just `j[0]` in grouping parentheses. `(j[0],)` would be a tuple.
type: Comment
score: 2

http://stackoverflow.com/a/48917560
answers question: http://stackoverflow.com/q/48917405
has body: This ''.join(iter(iter(s).__next__, ' ')) will work regardless of whether there actually is a ' ' in your string or not.
score: 0
type: Answer

http://stackoverflow.com/q/48920795
answer count: 1
has comment: http://stackoverflow.com/comment/84892170
tagged with: machine-learning
has title: Class inheritance in classes that encapsulate TensorFlow computational graphs
tagged with: python
type: AnsweredQuestion
tagged with: oop
has comment: http://stackoverflow.com/comment/84848803
has body: I like to build python classes around my Tensorflow models to make them portable and easier to work with (at least in my mind). The approach I take is to write something like class MyAwesomeModel(object): def __init__(self, some_graph_params): # bunch of code that defines the tensors, optimizer, etc... # e.g. self.mytensor = tf.placeholder(tf.float32, [1]) def Train(self, tfsession, input_val): # some code that calls the run() method on tfsession, etc. def other_methods(self): # other things like testing, plotting, etc. all managed nicely # by the state that MyAwesomeModel instances maintain I have two models that are very similar. The only differences are in a few places in the computational graph architecture - I would like to create a base class that has all the common functionality and just have child classes which overwrite a few things in the base class. Here's how it would work in my mind Say my base class looks like this import tensorflow as tf class BaseClass(object): def __init__(self, multiplier): self.multiplier = multiplier # This is where I construct the graph self.inputnode = tf.placeholder(tf.float32, [1]) self.tensor1 = tf.constant(self.multiplier, dtype=tf.float32) * self.inputnode self.tensor2 = self.tensor1 # this is where the two # child classes will differ self.tensoroutput = 10*self.tensor2 def forward_pass(self, tfsession, input_val): return tfsession.run(self.tensoroutput, feed_dict={self.inputnode: [input_val]}) def other_methods(self): print("doing something here...") print(self.multiplier) Then I pop in two child classes, which just redefine the relationship between self.tensor2 and self.tensor1: class ChildClass1(BaseClass): def __init__(self, multiplier): BaseClass.__init__(self, multiplier) self.tensor2 = self.tensor1 + tf.constant(5.0, dtype=tf.float32) class ChildClass2(BaseClass): def __init__(self, multiplier): BaseClass.__init__(self, multiplier) self.tensor2 = self.tensor1 + tf.constant(4.0, dtype=tf.float32) My objective would b…
has answer: http://stackoverflow.com/a/48938560
accepted answer: http://stackoverflow.com/a/48938560
tagged with: tensorflow
type: Question
tagged with: inheritance
score: 0

http://stackoverflow.com/comment/84862805
comment on: http://stackoverflow.com/q/48928215
has text: Quoting the accepted answer from the duplicated question: "That's why we have `functools.wraps`. This takes a function used in a decorator and adds the functionality of copying over the function name, docstring, arguments list, etc"
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84917095
type: QuestionComment
type: Comment
has text: weeeeeeelllllll fair question, but `Questions asking us to recommend or find a book, tool, software library, tutorial or other off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam.`
score: 0
comment on: http://stackoverflow.com/q/48955051

http://stackoverflow.com/q/48907925
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84823387
has comment: http://stackoverflow.com/comment/84824584
type: Question
has comment: http://stackoverflow.com/comment/84824350
has answer: http://stackoverflow.com/a/48909247
duplicate of: http://stackoverflow.com/q/46390231
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/46390231
score: 0
tagged with: display
has body: I'm doing a project that using Python and Pygame. I want to ask some question about the key in Pygame. Thank you Shubhitgarg. I use his/her suggestions(use pygame_textinput), it succeed. Now I want to change the text input position with pressed an enter, but it can't detect the enter. How can I fix it? My real code: # installing package import pygame from pygame import * import pygame_textinput pygame.init() # colour settings red = (255, 0, 0) green = (0, 255, 0) grass_green = (112, 173, 71) blue = (0, 0, 255) yellow = (255, 255, 0) white = (255, 255, 255) black = (0, 0, 0) # screen settings window = pygame.display.set_mode((680, 600)) window.fill(grass_green) pygame.display.flip() # font settings default_font = pygame.font.get_default_font() big_font = pygame.font.Font(default_font, 96) font_a = pygame.font.Font(default_font, 50) font_b = pygame.font.Font(default_font, 30) font_c = pygame.font.Font(default_font, 18) # text input settings textinput = pygame_textinput.TextInput("freeansbold.ttf", 96, True, black, white, 400, 35) # timer start = pygame.time.get_ticks() # text please_guess_a_number = font_a.render("Please guess a number. ", 1, white) text_range = font_c.render("from to", 1, white) wrong_bigger = font_b.render("Sorry, You haven’t guess it rightly. Please try again.(The answer must be bigger.)", 1, white) wrong_smaller = font_b.render("Sorry, You haven’t guess it rightly. Please try again.(The answer must be smaller.)", 1, white) correct = font_b.render("Congratulations! You guess it correctly!!", 1, white) # game ask_you_to_set_range_1 = True ask_you_to_set_range_2 = False while True: if ask_you_to_set_range_1: window.blit(please_guess_a_number, (60, 80)) pygame.draw.rect(window, yellow, [60, 200, 230, 300]) pygame.draw.rect(window, yellow, [390, 200, 230, 300]) window.blit(text_range, (10, 550)) pygame.display.flip() while True: events = pygame.event.get() textinput.update(events) window.blit(textinput.get_surface(), (110, 300)) pygame.display.flip() i…
linked to: http://stackoverflow.com/q/48770344
tagged with: python
tagged with: pygame
tagged with: blit
has title: How to let pygame text input detect the key in Pygame?
type: UnansweredQuestion

strftime
type: Tag
tags question: http://stackoverflow.com/q/48823828
tag name: strftime

http://stackoverflow.com/q/48937267
has body: I am working on a project in particle using internet button, as well as a program in python. How would I combine my particle code, so that the python code then runs the particle code, what's the best way to combine them? #include &lt;Arduino.h&gt; #include &lt;InternetButton.h&gt; InternetButton button = InternetButton(); bool rainbow_mode = false; int buzzer = D0; void setup() { button.begin(); pinMode(buzzer, OUTPUT); } void loop() { if (button.allButtonsOff()) { button.rainbow(5); } if (button.buttonOn(1)) { button.allLedsOff(); tone(buzzer, 2000, 500); delay(1000); } } With my code in python: def on_message(ws, message): global KETTLEIP global LIGHTIP global MACADDRESS print (message) #tweet(message) if (message == "kettle"): if kettle_ip.exists(): file = open("ketIP", "r") data = file.read() ket.setOn(data) elif ("lights" in message and "on" in message): light.setAll(LIGHTIP) elif ("lights" in message and "off" in message): light.setOff(LIGHTIP) def on_error(ws, error): print (error) def on_close(ws): print ("### closed ###") def on_open(ws): print ('Opening Websocket connection to the server ... ') if __name__ == "__main__": websocket.enableTrace(True) ws = websocket.WebSocketApp("ws://", on_open=on_open, on_message=on_message, on_error=on_error, on_close=on_close, ) ws.on_open = on_open ws.run_forever() What I want to do, is the lights are on then run the code on particle too
upvote count: 1
tagged with: python
has title: using particle with python
type: Question
downvote count: 0
favorite count: 0
score: 1
tagged with: particles
answer count: 0
type: UnansweredQuestion

http://stackoverflow.com/comment/84782928
score: 0
has text: allusers1 is the name of the class in mainpage/models.py . MY DIRECTORIES ARE LIKE THIS --> MajorProject->src->mainpage(it is an app),signup(it is an app in same directory 'src' as mainpage) ,login(it is an app in same directory src as mainpage) I tried src.signup.models and MjorProject.src.signup.models and Got An error
type: Comment
comment on: http://stackoverflow.com/a/48888388
type: AnswerComment

http://stackoverflow.com/comment/84827619
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48908748
has text: @Eric - The row you're calling "line 18" (which is row 17 in XlsxWriter) should be level 1. Basically, the level indicates how many of the continuous vertical bars to draw on that row. Dots and "minus boxes" (or plus boxes) do not count toward the level.
type: AnswerComment

http://stackoverflow.com/q/48861533
type: Question
has answer: http://stackoverflow.com/a/48864466
tagged with: search
score: 0
answer count: 1
type: UnansweredQuestion
has title: algorythm to find "next neighbor matching" in a multi branch tree
tagged with: python
tagged with: tree
has body: I have a data structure that essentially is a tree with multiple branching. The program is implemented in python (3.5, currently, if it matters). Problem: Starting from an arbitrary node find a "matching" node which is at the shortest possible distance. Definition of "distance" is having the least possible number of "backtracking" (a backtrack happens when reaching back to parent from the starting node). This means children of start node are preferred, then come children of parent of starting node, third choice are children of parent of parent of starting node, etc. Naive implementation leads to infinite recursion: def find(self, name, skip=None): if self.name == name: return self for c in self.child: if c != skip: s = c.find(name, skip) if s is not None: return s if name != 'Start': if self.parnt is not None: return self.parnt.find(name, self) return None I have not found an algorithm not needing branch tagging, which is cumbersome. Current implementation has also the problem it implements a depth-first search, while a breadth-first would be preferred. Can someone suggest an efficient algorithm?

http://stackoverflow.com/comment/86784202
type: Comment
comment on: http://stackoverflow.com/a/48927964
has text: Can you help me out on this ? https://stackoverflow.com/questions/49883875/mapping-columns-of-two-data-frames-and-adding-a-value-from-the-list
score: 0
type: AnswerComment

http://stackoverflow.com/q/48913015
has answer: http://stackoverflow.com/a/48914568
has body: Im trying to write a code to say that if a condition is met of a value in a list then in the next iteration make that value a different one. the problem is i dont know what the code is to tell python to do it in the next iteration my code. list_ = [4, 5, 6, 6, 4, 5] for i in range(0, 10): for j in range(0, len(list_)): if list_[j] == 5: if list_[(j-1) % len(list)] == 4: list_[j][i+1] = 3 but this doesnt work as i get a int' object does not support item assignment error. also i know some of the indentation maybe wrong its because i struggled to put them into here
has answer: http://stackoverflow.com/a/48914553
has comment: http://stackoverflow.com/comment/84832396
type: UnansweredQuestion
has title: How to give a command for the next iteration
type: Question
has comment: http://stackoverflow.com/comment/84834755
answer count: 2
tagged with: for-loop
score: 0
has comment: http://stackoverflow.com/comment/84834363
has comment: http://stackoverflow.com/comment/84834257
tagged with: python

http://stackoverflow.com/q/48856920
upvote count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84717442
type: AnsweredQuestion
score: -2
has answer: http://stackoverflow.com/a/48857722
accepted answer: http://stackoverflow.com/a/48857722
has comment: http://stackoverflow.com/comment/84718259
type: Question
answer count: 2
downvote count: 2
has body: I am using Idle and tkinter.messagebox. I am trying to display the product of a calculation from entry inputs. I have been unable to figure out how to capture the user entries and then run the calculation and produce the result. So, what I want the user to be able to input numbers, say 2, and 2. Then, I want the user to push a button. Next, the answer to 2+2 should appear in the blank entry label. My question is how do I capture user inputs and use them in a calculation, then display the result? mydict = {'good':0.7, 'average':0.5, 'optimal': 1, 'unacceptable': 0, 'major innovation': 1, 'minor innovation': 0.7, 'no innovation': 0.4, '1st lowest': 1, '2nd lowest': 0.7, '3rd lowest': 0.5, '4th lowest': 0.3} # Widgets: from tkinter import * master = Tk() label1 = Label(master, text = 'Bid Number', relief = 'groove', width = 16) label2 = Label(master, text = 'Cost Score', relief = 'groove', width = 16) label3 = Label(master, text = 'Past Performance', relief = 'groove', width = 16) label8 = Label(master, text = 'Bid 1' , relief = 'groove', width = 12) entry1 = Entry(master, relief = 'groove', width = 12) entry2 = Entry(master, relief = 'groove', width = 12) label9 = Label(master, text = 'Bid Score', relief = 'groove', width = 16) def button_function(): a = float( mydict[entry1.get()] ) * float( mydict[entry2.get()] ) button1 = Button(master, text = 'calculate', relief = 'groove', width = 12, command = button_function) label16 = Frame(master, print(a)) #Geometry label1.grid( row = 1, column = 1, padx = 10 ) label2.grid( row = 1, column = 2, padx = 10 ) label3.grid( row = 1, column = 3, padx = 10 ) label8.grid( row = 2, column = 1, padx = 10 ) entry1.grid( row = 2, column = 2, padx = 10 ) entry2.grid( row = 2, column = 3, padx = 10 ) label9.grid( row = 1, column = 8, padx = 10 ) label16.grid( row = 2, column = 8, padx = 10 ) button1.grid( row = 3, column = 4, columnspan = 2)
has answer: http://stackoverflow.com/a/48857085
has comment: http://stackoverflow.com/comment/84718075
favorite count: 0
has comment: http://stackoverflow.com/comment/84718397
has title: calculating entry inputs in tkinter
possible better answer: http://stackoverflow.com/a/48857085
tagged with: python
has comment: http://stackoverflow.com/comment/84717998

http://stackoverflow.com/q/48818500
tagged with: legend
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84640908
tagged with: colorbar
accepted answer: http://stackoverflow.com/a/48818953
type: Question
tagged with: matplotlib
has body: I have googled how to set legends in matplotlib pcolor, but I am still unsure and have not found references to how to set a legend for the specific colors I have set to .set_under and .set_over Is this possible to have a legend and a colorbar in this case? Since I have done cmap.set_under(1) for example, this means I have set the colorbar to show a different range than the legend (which I have still yet to figure out how to add). I have found an example here on https://matplotlib.org/examples/pylab_examples/image_masked.html which I have reduced a bit to better explain my question: from copy import copy import numpy as np import matplotlib.pyplot as plt import matplotlib.colors as colors import matplotlib.mlab as mlab x0, x1 = -5, 5 y0, y1 = -3, 3 x = np.linspace(x0, x1, 500) y = np.linspace(y0, y1, 500) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = 10*(Z2 - Z1) cmap = copy(plt.cm.gray) cmap.set_over('r', 1.0) cmap.set_under('g', 1.0) cmap.set_bad('b', 1.0) Zm = np.ma.masked_where(Z &gt; 1.2, Z) fig, ax = plt.subplots() im = ax.imshow(Zm, interpolation='bilinear', cmap=cmap, norm=colors.Normalize(vmin=-1.0, vmax=1.0), aspect='auto', origin='lower', extent=[x0, x1, y0, y1]) ############ ### Here a title is used instead of a legend ax.set_title('Green=low, Red=high, Blue=masked') ### instead of a set_title above, I would like it to be a legend ############ cbar = fig.colorbar(im, extend='both') plt.show() In this example, there is a set title to explain the out-of-bounds colors. However, instead of a title as above, I would like it to be a legend.
has comment: http://stackoverflow.com/comment/84641213
score: 0
has title: adding legend in pcolor with cs.cmap.set_under and .set_over
answer count: 1
has comment: http://stackoverflow.com/comment/84641024
has answer: http://stackoverflow.com/a/48818953

http://stackoverflow.com/q/48834813
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84674957
has comment: http://stackoverflow.com/comment/84674970
has comment: http://stackoverflow.com/comment/84674460
has answer: http://stackoverflow.com/a/48835237
has comment: http://stackoverflow.com/comment/84675039
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84674433
has comment: http://stackoverflow.com/comment/84675055
tagged with: python
has comment: http://stackoverflow.com/comment/84675000
tagged with: regex
answer count: 4
upvote count: 1
has comment: http://stackoverflow.com/comment/84674307
has comment: http://stackoverflow.com/comment/84675016
downvote count: 1
has comment: http://stackoverflow.com/comment/84674907
has answer: http://stackoverflow.com/a/48834918
type: Question
has comment: http://stackoverflow.com/comment/84674958
has comment: http://stackoverflow.com/comment/84674897
has body: I have the set set1={'*klj?', 'bl:VOLTe?', 'abkjld:Sure:STe?', 'JKLJS?', 'TRered[:AMide]?', 'DKJ[:dkja]?'} I want to have the set look like set1={'*klj?', 'bl:VOLTe?', 'abkjld:Sure:STe?', 'JKLJS?', 'TRered?','DKJ?'} where I want to get rid of the [:AMide] and [:dkja] inside the set. I was trying to use regex What I have so far is set2={} for element in set: x=re.sub("([\(\[]).*?([\)\]])", "", str(element)) set2.add(x) This gets rid of the [] and what is inside but doesn't properly recreate the set, ie set2.add(x) doesn't work
has comment: http://stackoverflow.com/comment/84674553
score: 0
has answer: http://stackoverflow.com/a/48834924
has comment: http://stackoverflow.com/comment/84674353
has answer: http://stackoverflow.com/a/52790893
has comment: http://stackoverflow.com/comment/84675086
has comment: http://stackoverflow.com/comment/84674858
has title: get rid of a specific part of an element in a set
has comment: http://stackoverflow.com/comment/84674717
linked to: http://stackoverflow.com/q/17373161
favorite count: 0

http://stackoverflow.com/comment/84695056
has text: I donot find any solution to generate image URL from my local PC image in python .
comment on: http://stackoverflow.com/q/48845368
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48821832
accepted answer: http://stackoverflow.com/a/48822324
has comment: http://stackoverflow.com/comment/84647241
tagged with: beautifulsoup
possible better answer: http://stackoverflow.com/a/48838445
tagged with: http://stackoverflow.com/tag/html
has title: I want to separate dates and prices using BeautifulSoup, but they're all under the same td tags
tagged with: python
has answer: http://stackoverflow.com/a/48838445
tagged with: parsing
score: 0
tagged with: web-scraping
has answer: http://stackoverflow.com/a/48822324
has body: I want to get the nickel price data from http://www.westmetall.com/en/markdaten.php?action=show_table&field=LME_Ni_cash#y2017 by doing webscraping using BeautifulSoup. There are two problems 1) I would like to separate the price from the dates, putting them on different columns 2) I want to remove the '.' in the dates My code so far is: import bs4 import csv from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup from datetime import datetime my_url='http://www.westmetall.com/en/markdaten.php?action=show_table&field=LME_Ni_cash#y2017' uClient=uReq(my_url) page_html=uClient.read() uClient.close() page_soup=soup(page_html, "html.parser") containers=page_soup.findAll("table") contain=containers[0] print(contain.td.text) #I only print this because I want to view the HTML If I do it this way and apply the loop, it will extract all the elements under td and it will the date and price in 1 column. My goal is to separate them into two columns. The preview of the HTML is as follows: 15. Febuary 2018 14.150,00 14.200,00 339.708 14. Febuary 2018 13.630,00 13.660,00 338.652 Thanks so much for the help!!!
type: Question
type: AnsweredQuestion
answer count: 2

http://stackoverflow.com/q/48949273
tagged with: python-2.7
score: 0
has answer: http://stackoverflow.com/a/48949500
tagged with: python
has comment: http://stackoverflow.com/comment/84904969
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84905075
type: Question
linked to: http://stackoverflow.com/q/699866
has body: I am trying to display all the binary numbers which are divisible by 5 and I am able to successfully show them. But the output is in decimal format even though I have converted them to base 2 (binary). My code - user_input = raw_input("Enter three numbers separated by commas: ") input_list = user_input.split(',') decimal_list=[] binary_list=[] for i in input_list: decimal_list.append(int(i,2)) print decimal_list for x in decimal_list: if x%5==0: binary_list.append(int(str(x),10)) print binary_list My input 0000,0001,0010,0011,0100,0101,0110,0111,1000 Output - [0, 1, 2, 3, 4, 5, 6, 7, 8] [0, 5] Why do I get [0,5] instead of [0000,0101] ? I did convert them back to binary using (int(str(x),10))
has title: Binary conversion returning decimal value
answer count: 1
duplicate of: http://stackoverflow.com/q/699866

http://stackoverflow.com/a/61190823
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48841342
type: Answer
has comment: http://stackoverflow.com/comment/108250605
downvote count: 0
has body: def round_sum(a, b, c): return round10(a) + round10(b) + round10(c) def round10(nums): return (((nums+5)/10)*10)

http://stackoverflow.com/comment/84855094
has text: In your code you are dropping the collection and then inserting some items. So I think count 5 is correct behaviour. Comment out the `self.collection.insert` line and run I am sure it will work. @徐博俊
type: AnswerComment
comment on: http://stackoverflow.com/a/48923771
score: 0
type: Comment

http://stackoverflow.com/a/48850340
answers question: http://stackoverflow.com/q/48850339
has body: I solved my problem by checking if my error message was in the error string: Input: try: raise KeyError('some error message') except KeyError as e: if 'some error message' in str(e): print('Caught error message') else: print("Didn't catch error message") Output: Caught error message Can someone shine some light on why this works but checking for equality doesn't? Edit: As KGSH pointed out, str(e) is really 'some error message' WITH the single quotation marks.
upvote count: 3
type: Answer
downvote count: 0
score: 3

http://stackoverflow.com/comment/84677050
has text: It works ! thanks a lot guys for the help! jbch, your code was right, it works like a charm. thanks
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48835765

http://stackoverflow.com/comment/84657175
has text: Thank you so much, this worked out really well, and helped me with parts of the code unmentioend :)
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48809926
type: AnswerComment

http://stackoverflow.com/comment/84685632
score: 0
comment on: http://stackoverflow.com/q/48839463
type: Comment
has text: `ssh-keygen -t rsa -N '' -f ~/.ssh/id_rsa`?
type: QuestionComment

http://stackoverflow.com/comment/84950493
has text: Matias' answer solves the problem. But wonder why would you ever want to do that? The purpose of using multi-layer networks is to learn different level of abstraction/representation. By fixing the weights of the layers, I think it'll be no better than single-layer one.
type: QuestionComment
comment on: http://stackoverflow.com/q/48950745
type: Comment
score: 0

http://stackoverflow.com/comment/84810362
comment on: http://stackoverflow.com/a/48901107
has text: The .xs() function was exactly what I needed, but I unfortunately couldn't figure out how to find the name I was looking for. Much appreciated.
type: AnswerComment
type: Comment
score: 0

apache-spark
tags question: http://stackoverflow.com/q/48863790
tags question: http://stackoverflow.com/q/48927271
tags question: http://stackoverflow.com/q/48896113
tags question: http://stackoverflow.com/q/48900842
tags question: http://stackoverflow.com/q/48815341
tags question: http://stackoverflow.com/q/48822984
tags question: http://stackoverflow.com/q/48941963
tags question: http://stackoverflow.com/q/48864173
tags question: http://stackoverflow.com/q/48857300
tags question: http://stackoverflow.com/q/48936131
tag name: apache-spark
tags question: http://stackoverflow.com/q/48950500
tags question: http://stackoverflow.com/q/48829993
tags question: http://stackoverflow.com/q/48924308
tags question: http://stackoverflow.com/q/48828736
tags question: http://stackoverflow.com/q/48832630
tags question: http://stackoverflow.com/q/48869922
tags question: http://stackoverflow.com/q/48872477
tags question: http://stackoverflow.com/q/48870590
tags question: http://stackoverflow.com/q/48959869
tags question: http://stackoverflow.com/q/48846882
tags question: http://stackoverflow.com/q/48958067
tags question: http://stackoverflow.com/q/48949387
tags question: http://stackoverflow.com/q/48817747
tags question: http://stackoverflow.com/q/48865615
tags question: http://stackoverflow.com/q/48870399
tags question: http://stackoverflow.com/q/48913153
tags question: http://stackoverflow.com/q/48940743
type: Tag
tags question: http://stackoverflow.com/q/48959246
tags question: http://stackoverflow.com/q/48880934
tags question: http://stackoverflow.com/q/48926751
tags question: http://stackoverflow.com/q/48951557
tags question: http://stackoverflow.com/q/48868855

http://stackoverflow.com/comment/84913814
type: Comment
score: 1
has text: @titipata `np.hstack(a)` did end up working, if you post as an answer I'll accept
comment on: http://stackoverflow.com/q/48953373
type: QuestionComment

http://stackoverflow.com/comment/84710258
comment on: http://stackoverflow.com/q/48853214
score: 0
type: Comment
has text: CPU and memory IO will always be faster than disk IO. Whether SSD will help depends on how much data you read from disk, and how often.
type: QuestionComment

http://stackoverflow.com/q/48931084
score: 1
downvote count: 0
answer count: 1
favorite count: 0
has title: How can I use python to combine data from multiple excel files into one excel file?
has comment: http://stackoverflow.com/comment/84869136
tagged with: python
has comment: http://stackoverflow.com/comment/84882369
has body: This is my code so far: import glob import pandas as pd import numpy as np import openpyxl log = 'G:\Data\Hotels\hotel.txt' #text file with my long list of hotels file = open(log, 'r') hotels = [] line = file.readlines() for a in line: hotels.append(a.rstrip('\n')) for hotel in hotels : path = "G:\\Data\\Hotels\\"+hotel+"\\"+hotel+" - Meetings" file = hotel+"_Action_Log.xlsx" print(file) So all this code has done so far is print the name (string i guess?) of all the hotel files of which i now want to copy and paste the contents into one "Master" excel file. I only require one sheet in each excel file and I don't require the headers (which are placed in row 5 due to fancy formatting in the first 4 rows). What would my next steps be? I am new to python.
type: AnsweredQuestion
upvote count: 1
has answer: http://stackoverflow.com/a/48931360
accepted answer: http://stackoverflow.com/a/48931360
type: Question
has comment: http://stackoverflow.com/comment/84869178

http://stackoverflow.com/a/48934974
answers question: http://stackoverflow.com/q/48934807
type: Answer
has body: Here is a quick solution - I didn't try to optimize your code at all, just fed it into a multiprocessing pool. This will run your function on each row individually, return a row with the new properties, and create a new dataframe from this output. import multiprocessing as mp pool = mp.Pool(processes=mp.cpu_count()) def func( arg ): idx,row = arg dist = gcd.dist(row['destination'], row['ping_location']) row['gc_distance'] = dist temp_idx = str(row['address_fields_dest']).find(":") pos_start = temp_idx + 3 pos_end = str(row['address_fields_dest']).find(",") - 2 row['destination address'] = str(row['address_fields_dest'])[pos_start:pos_end] ##### calculate velocity which is: v = d/t ## time is the difference btwn destination time and the ping creation time timediff = abs(row['dest_data_generate_time'] - row['event_time']) row['velocity km/hr'] = 0 ## check if the time dif btwn destination and event ping is more than a minute long if timediff &gt; datetime.timedelta(minutes=1): row['velocity km/hr'] = dist / timediff.total_seconds() * 3600.0 return row new_rows = pool.map( func, [(idx,row) for idx,row in data_all.iterrows()]) data_all_new = pd.concat( new_rows )
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84877094
upvote count: 3

http://stackoverflow.com/comment/84826114
score: 0
comment on: http://stackoverflow.com/a/48909657
type: AnswerComment
type: Comment
has text: @Idlehands The phone numbers are extracted from unstructured text so they don't necessarily always follow this format.

http://stackoverflow.com/comment/84921411
comment on: http://stackoverflow.com/q/48957165
score: 0
type: Comment
type: QuestionComment
has text: Are you reading double from bytes? Then this should help: https://stackoverflow.com/a/8074533/2288384 - easy way using `ByteBuffer.wrap(...).getXXX()`

http://stackoverflow.com/q/48963178
tagged with: python
has answer: http://stackoverflow.com/a/48966468
type: AnsweredQuestion
downvote count: 0
tagged with: celery
type: Question
score: 3
has body: I use celery with Flask and I have the following task: @celery.task(bind=True, max_retries=5) def failing_task(self): time.sleep(random.randint(4, 10)) try: raise ValueError('Exception occurred') except Exception as e: self.retry(exc=e, countdown=int(random.uniform(2, 3) ** self.request.retries)) I have created Flask endpoint to access task results: @app.route('/api/task/&lt;task_id&gt;') def task_status(task_id): task = AsyncResult(task_id) task_result = task.result if isinstance(task_result, Exception): task_result = '{e.__class__.__name__}: {e}'.format(e=task_result) app.logger.info(task.info) content = {'task_id': task.id, 'state': task.state, 'result': task_result} return jsonify(content) I would like to return the retry attempt number so that I could display it on the web page. I know that I can do it within the task definition using self.request.retries, but I didn't figure out how to access it from AsyncResult object.
tagged with: flask
upvote count: 3
answer count: 1
accepted answer: http://stackoverflow.com/a/48966468
has title: How to access retry attempt in Celery AsyncResult
favorite count: 0

http://stackoverflow.com/comment/84797692
type: Comment
comment on: http://stackoverflow.com/a/48895887
score: 1
type: AnswerComment
has text: so now trying a workaround with selenium coz i searched that it gives the browser instance. hope it works.....btw thanx for your efforts.

http://stackoverflow.com/q/48888341
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/15887820
tagged with: python
has title: python matplotlib - dynamical plot with errorbars?
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/84782206
score: 1
tagged with: matplotlib
type: Question
has body: I want to have a script where the plot is interactively updated. I can do this for regular plots. The main code is, that a plot object is assigned into a variable, and this can than be set to whatever one wants. Example: import matplotlib.pyplot as plt fig = plt.figure() test, = ax.plot([1,2,3],[1,2,3]) test.set_ydata([7,8,9]) This works nicely. But this does not work if I use .errorbar() instead of .plot(). The syntax for errorbar is ax.errorbar(x,y,error), but test,=ax.errorbar([1,2,3],[1,2,3],[1,2,3]) gives me a "too many values to unpack" error. Do you know how I can make this happen? Thx.
linked to: http://stackoverflow.com/q/25210723
upvote count: 1
duplicate of: http://stackoverflow.com/q/25210723
favorite count: 0
has comment: http://stackoverflow.com/comment/84782176

http://stackoverflow.com/a/48859842
downvote count: 0
has body: Let's try using extractall: df.assign(**df.Body.str.extractall('(software|is already paid)')[0] .str.get_dummies().sum(level=0)) Output: No Body is already paid software 0 1 Office software is already paid 1 1 1 2 Excel software is not paid yet 0 1 2 3 Power point software is already paid 1 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48859714
score: 3
answers question: http://stackoverflow.com/q/48859714
upvote count: 3
type: AcceptedAnswer

http://stackoverflow.com/a/48806834
accepted answer of: http://stackoverflow.com/q/48806770
has comment: http://stackoverflow.com/comment/84616395
type: Answer
answers question: http://stackoverflow.com/q/48806770
downvote count: 0
has comment: http://stackoverflow.com/comment/84616733
upvote count: 8
has comment: http://stackoverflow.com/comment/84616968
has body: Make sure you have the following in your settings.py AUTHENTICATION_BACKENDS = ( 'oauth2_provider.backends.OAuth2Backend', 'django.contrib.auth.backends.ModelBackend' ) And: OAUTH2_PROVIDER = { 'REFRESH_TOKEN_EXPIRE_SECONDS': 360000, 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'}, 'ACCESS_TOKEN_EXPIRE_SECONDS': 1800 } For debugging purposes: Remove authentication_classes = () from view.py Remove TokenHasReadWriteScope from view.py If you want to make a logout endpoint, I would recommend using oauth2_views in your urls.py: from oauth2_provider import views as oauth2_views #..... urlpatterns = [ #.... url(r'^logout/$', oauth2_views.RevokeTokenView.as_view()), ]
has comment: http://stackoverflow.com/comment/84616639
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84617301
score: 8

http://stackoverflow.com/a/48872939
answers question: http://stackoverflow.com/q/48872800
has comment: http://stackoverflow.com/comment/84755770
upvote count: 5
has body: Requests are almost always the slowest portion of any networking code so you'll absolutely want to batch your IDs. Uniprot has a batching capability in it's API. There's a Perl example on that page that should help you get started – I'd look at what the batch size limit is and go for the largest as a starting point (it's likely much smaller than 4,000,000). As noted on the Uniprot site, there's also an ID mapping service that may fit the bill.
score: 5
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84750087
has comment: http://stackoverflow.com/comment/85574359

http://stackoverflow.com/a/48885985
answers question: http://stackoverflow.com/q/48885281
has comment: http://stackoverflow.com/comment/84778385
has comment: http://stackoverflow.com/comment/84801305
score: 0
type: Answer
has body: You could output the date to a file, and the when the person tries to perform the command, read the date from the file and compare it with the current date.

http://stackoverflow.com/q/48876481
tagged with: grouping
tagged with: sequence
favorite count: 0
tagged with: python
linked to: http://stackoverflow.com/q/16974047
possible better answer: http://stackoverflow.com/a/48877004
accepted answer: http://stackoverflow.com/a/48876543
type: AnsweredQuestion
score: 2
has title: Count missing instances in subgroups
has answer: http://stackoverflow.com/a/48877004
upvote count: 3
downvote count: 1
has answer: http://stackoverflow.com/a/48877217
type: Question
has body: I have a dataframe in Pandas with collected data; import pandas as pd df = pd.DataFrame({'Group': ['A','A','A','A','A','A','A','B','B','B','B','B','B','B'], 'Subgroup': ['Blue', 'Blue','Blue','Red','Red','Red','Red','Blue','Blue','Blue','Blue','Red','Red','Red'],'Obs':[1,2,4,1,2,3,4,1,2,3,6,1,2,3]}) +-------+----------+-----+ | Group | Subgroup | Obs | +-------+----------+-----+ | A | Blue | 1 | | A | Blue | 2 | | A | Blue | 4 | | A | Red | 1 | | A | Red | 2 | | A | Red | 3 | | A | Red | 4 | | B | Blue | 1 | | B | Blue | 2 | | B | Blue | 3 | | B | Blue | 6 | | B | Red | 1 | | B | Red | 2 | | B | Red | 3 | +-------+----------+-----+ The Observations ('Obs') are supposed to be numbered without gaps, but you can see we have 'missed' Blue 3 in group A and Blue 4 and 5 in group B. The desired outcome is a percentage of all 'missed' Observations ('Obs') per group, so in the example: +-------+--------------------+--------+--------+ | Group | Total Observations | Missed | % | +-------+--------------------+--------+--------+ | A | 8 | 1 | 12.5% | | B | 9 | 2 | 22.22% | +-------+--------------------+--------+--------+ I tried both with for loops and by using groups (for example: df.groupby(['Group','Subgroup']).sum() print(groups.head) ) but I can't seem to get that to work in any way I try. Am I going about this the wrong way? From another answer (big shoutout to @Lie Ryan) I found a function to look for missing elements, however I don't quite understand how to implement this yet; def window(seq, n=2): "Returns a sliding window (of width n) over data from the iterable" " s -&gt; (s0,s1,...s[n-1]), (s1,s2,...,sn), ... " it = iter(seq) result = tuple(islice(it, n)) if len(result) == n: yield result for elem in it: result = result[1:] + (elem,) yield result def missing_elements(L): missing = chain.from_iterable(range(x + 1, y) for x, y in window(L) if (y - x) &gt; 1) return list(missing) Can anyone give me a pointer is the right direction?
tagged with: data-science
answer count: 3
has answer: http://stackoverflow.com/a/48876543
tagged with: pandas

http://stackoverflow.com/a/50385056
type: Answer
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/116537954
has body: I'm not an export either in multiprocessing or in ipykernel(which is used by jupyter notebook) but because there seems nobody gives an answer, I will tell you what I guessed. I hope somebody complements this later on. I guess your jupyter notebook server is running on Windows host. In multiprocessing there are three different start methods. Let's focus on spawn, which is the default on windows, and fork, the default on Unix. Here is a quick overview. spawn (cpython) interactive shell - always raise an error run as a script - okay only if you nested multiprocessing code in if __name__ == '__main'__ Fork always okay For example, import multiprocessing def worker(): """worker function""" print('Worker') return if __name__ == '__main__': multiprocessing.set_start_method('spawn') jobs = [] for i in range(5): p = multiprocessing.Process(target=worker) jobs.append(p) p.start() This code works when it's saved and run as a script, but raises an error when entered in an python interactive shell. Here is the implementation of ipython kernel, and my guess is that that it uses some kind of interactive shell and so doesn't go well with spawn(but please don't trust me). For a side note, I will give you an general idea of how spawn and fork are different. Each subprocess is running a different python interpreter in multiprocessing. Particularly, with spawn, a child process starts a new interpreter and imports necessary module from scratch. It's hard to import code in interactive shell, so it may raise an error. fork is different. With fork, a child process copies the main process including most of the running states of the python interpreter and then continues execution. This code will help you understand the concept. import os main_pid = os.getpid() os.fork() print("Hello world(%d)" % os.getpid()) # print twice. Hello world(id1) Hello world(id2) if os.getpid() == main_pid: print("Hello world(main process)") # print once. Hello world(main process)
downvote count: 0
answers question: http://stackoverflow.com/q/48846085

http://stackoverflow.com/comment/84829192
comment on: http://stackoverflow.com/a/48911370
type: AnswerComment
has text: ah! that's two solutions I missed out on. you were faster ;)
type: Comment
score: 0

http://stackoverflow.com/a/48941129
type: Answer
has body: &gt;&gt;&gt; words = ['xerox', 'trust', 'follow', 'blurb', 'maroon', 'ready', 'salad', 'yummy', 'evidence'] &gt;&gt;&gt; [w for w in words if w[0] == w[-1]] ['xerox', 'trust', 'blurb', 'yummy', 'evidence']
answers question: http://stackoverflow.com/q/48941102
score: 5
upvote count: 5
downvote count: 0

http://stackoverflow.com/comment/84748910
comment on: http://stackoverflow.com/a/48848778
type: Comment
has text: Hmm, I'm not sure why inserting a `Reshuffle` between `SampleDepths` and `RunClustering` doesn't fix my issue. It's still taking the same amount of time, autoscaling up to 3 workers. Here's my new pipeline: https://i.imgur.com/Gew9Oy3.png (I just upgraded to 2.3.0 and added `| 'PreventFusion' >> beam.Reshuffle()` between the aforementioned steps).
score: 0
type: AnswerComment

http://stackoverflow.com/a/48895589
upvote count: 2
has comment: http://stackoverflow.com/comment/85134557
type: Answer
accepted answer of: http://stackoverflow.com/q/48895370
score: 2
has comment: http://stackoverflow.com/comment/85134454
answers question: http://stackoverflow.com/q/48895370
has body: Use a list comprehension list_of_A = [x for x in df['A'] if x != '.'] Probably more performant list_of_A = [x for x in df['A'].values.tolist() if x != '.'] Faster still tbl.A.values[tbl.A.values != '.'].tolist()
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48952045
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/84910800
score: 2
accepted answer of: http://stackoverflow.com/q/48951527
has comment: http://stackoverflow.com/comment/84910770
answers question: http://stackoverflow.com/q/48951527
type: AcceptedAnswer
downvote count: 0
has body: You can use: [i.find(class_='cta2 visit', href=True)['href'] for i in soup.find_all(class_='buttons')]

http://stackoverflow.com/a/76424338
score: 0
has body: If your time series has cycles or periodics and is continious: Look at your data as a grid. The first dimension is your time variable and your second dimension is the time series number. In order to incorporate this concept you need to make sure that each time series has the exact same initial state and it is continious. Here is an example: Assume power consumption in a city. You'll have 24hrs and 7 days cycles for sure in such scenarios. You can devide the time series from 0 to N: Sat(0) ... Fri(0) Sat(1) ... Fri(1) . . . Sat(N) ... Fri(N) Instead of forecasting the end of each time series you can fore cast the N+1 data set by fitting your ARMA model over all Sat(0)...Sat(N) and obtain Sat(N+1) etc. Repeat this for each day of the week and you'll get the next value. If your data does't have preiodicities this method or any other method will never work. If your time series doesn't have cycles or periodics and is segmented: You may want to use a statespace method to obtain the spectra of your dynamical system and make decsisions based on directions and magnitudes.
type: Answer
answers question: http://stackoverflow.com/q/48962963

http://stackoverflow.com/comment/84845195
comment on: http://stackoverflow.com/q/48919374
score: 1
has text: It would be easier to understand your problem if you posted your error message as text instead of an image. Check out https://stackoverflow.com/help/formatting
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84876511
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48932552
type: AnswerComment
has text: Nope that still creates a key error... Sorry for so many questions I'm brand new to python.

http://stackoverflow.com/comment/87861131
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48953529
has text: @ÍhorMé `main` import from `pip` is not supported in pip 10.
type: Comment

http://stackoverflow.com/q/48921720
has answer: http://stackoverflow.com/a/48922152
score: 2
downvote count: 0
tagged with: delta
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84875224
type: Question
has body: I am writing a function to ask the user for a date. I would like the user to be able to enter the date in a familiar format: MM-DD-YYYY I've tried a number of variations but have been unsuccessful in being able to calculate the difference in days in a delta calculation. My attempts have returned a number of errors, mainly that I cannot pass str arguments while trying to calculate a difference. What is the best way to get a date input in MM-DD-YYYY while subtracting .today() which returns YYYY-MM-DD, ultimately returning the number of days between the two dates? Thanks for any and all input! (using .PY 3.6) Note: the code below DOES work but does not allow for the U.S. date formatting convention. def get_days_since_last_app(): then = datetime.strptime(input("What is the date of your last credit " "card application? e.g. YYYY-MM-DD - 2017-07-26 "), '%Y-%m-%d') today = datetime.today() delta = then - today print(abs(delta.days)) return abs(delta) Here is the code that does NOT work when allowing a user to input the date in a MM-DD-YYYY input. I've tried casting both variables between int's and str's with no luck. Error: TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'str' Code: def get_days_since_last_app(): then = datetime.strptime(input("What is the date of your last credit " "card application? e.g. MM-DD-YYYY - 07-26-2017 "), '%m-%d-%Y') today = arrow.now().format('MM-DD-YYYY') delta = then - today print(arrow.now().format('MM-DD-YYYY')) print(delta) print(abs(delta.days)) return abs(delta)
has comment: http://stackoverflow.com/comment/84849902
has comment: http://stackoverflow.com/comment/84849807
tagged with: date
upvote count: 2
has title: Wrote my first Python program, would appreciate input on user input incrementing
tagged with: difference
has comment: http://stackoverflow.com/comment/84850098
has comment: http://stackoverflow.com/comment/84850749
answer count: 1
favorite count: 0
tagged with: python

http://stackoverflow.com/a/48874203
accepted answer of: http://stackoverflow.com/q/48871327
answers question: http://stackoverflow.com/q/48871327
type: AcceptedAnswer
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84754308
has body: The problem is caused because the on_pre_enter event is done before adding the BoxLayout so it does not exist, a possible solution is to use Clock: class MainScreen(Screen): def __init__(self, *args, **kwargs): Screen.__init__(self, *args, **kwargs) Clock.schedule_once(self.finished_init) def finished_init(self, *args): show_view = self.ids.rc_display # error here show_view.clear_widgets() buttons = BoxLayout(orientation = 'vertical') pr = requests.get('http://127.0.0.1:5000/stageplanning/api/v1.0/shows') for show in pr.json(): buttons.add_widget(Button(text = show['show_title'])) show_view.add_widget(buttons) Another option is to define it in the BoxLayout constructor: *.py class MainBoxLayout(BoxLayout): def __init__(self, *args, **kwargs): BoxLayout.__init__(self, *args, **kwargs) self.clear_widgets() buttons = BoxLayout(orientation = 'vertical') pr = requests.get('http://127.0.0.1:5000/stageplanning/api/v1.0/shows') for show in pr.json(): buttons.add_widget(Button(text = show['show_title'])) self.add_widget(buttons) *.kv ScreenManager: MainScreen: LoginScreen: &lt;MainScreen&gt;: name: 'MainScreen' id: ms MainBoxLayout: id: rc_display orientation: "vertical" padding: 10 spacing: 10 &lt;LoginScreen&gt;: name: 'LoginScreen' id: ls Button: on_release: app.root.current text: 'Click to Login' font_size: 20

http://stackoverflow.com/comment/84914328
comment on: http://stackoverflow.com/q/48953689
score: 0
type: Comment
type: QuestionComment
has text: Also, what type of object does `args.input_file.read()` return on Python 3? Presumably `bytes`, or you'd have a different error when wrapping it in a `io.TextIOWrapper()` object.

http://stackoverflow.com/q/48959563
has comment: http://stackoverflow.com/comment/84928405
type: Question
has comment: http://stackoverflow.com/comment/84926310
upvote count: 0
score: -2
has body: I can't figure out how to get this 'order_by' to work. reviews = product.review_set.all().order_by('-created_at')
has title: The 'order_by' method not working on a foreign key query
has comment: http://stackoverflow.com/comment/84926132
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84951604
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84926639
downvote count: 2
has comment: http://stackoverflow.com/comment/84926186
has answer: http://stackoverflow.com/a/48961406

http://stackoverflow.com/comment/84647974
comment on: http://stackoverflow.com/q/48821732
has text: great that you figured it out. You can post it as answer.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84877266
type: Comment
has text: Hi @Nathan, I have modified the string a bit, can you please have a kind look. The actual response is huge which contains a lot of tags. Thanks.
type: AnswerComment
comment on: http://stackoverflow.com/a/48913111
score: 0

http://stackoverflow.com/comment/84729562
comment on: http://stackoverflow.com/a/48840336
type: Comment
has text: @Enigma have you seen documentation that I have attached (equivalent database functions)? Think that usage is self explanatory
score: 0
type: AnswerComment

http://stackoverflow.com/comment/90199367
comment on: http://stackoverflow.com/a/48856798
type: Comment
has text: What does `w+` signify?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84653833
comment on: http://stackoverflow.com/q/48825011
type: Comment
type: QuestionComment
has text: no a single one
score: 0

http://stackoverflow.com/comment/84760549
type: Comment
has text: If you want to use `s` variable from `connect` function, use `constructor` and initialize it while instantiating the class.
comment on: http://stackoverflow.com/a/48878152
score: 0
type: AnswerComment

http://stackoverflow.com/q/48878391
has answer: http://stackoverflow.com/a/48878635
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48878495
has answer: http://stackoverflow.com/a/48878572
has body: I made up a dataframe to illustrate my question. Say, I have three patients: 'a', 'b', 'c'. We got results from these patient at three different time points (t1, t2, t3). What I need is to create another column 'Fold', which is the fold change from t1. Since patient 'c' does not has any result at t1, its fold change vs t1 should be nan. Below is the code: df = pd.DataFrame ({ \ 'time': np.repeat(['t1','t2','t3'], [2,3,3]), 'id': ['a', 'b', 'a', 'b', 'c', 'a', 'b', 'c'], 'result':np.random.randint(10,20,size=8) }) # create indicator column has_t1: if a patient has t1: 1 if not: 0 df['is_t1'] = np.where(df['time']=='t1', 1, 0) df['has_t1'] = df.groupby('id')['is_t1'].transform(sum) # create fold change column df['fold'] =df.sort_values(['id', 'time']).groupby('id').apply(lambda x: x['result']/x['result'].iloc[0] if x['has_t1'].iloc[0]==1 else np.nan) I got error: AttributeError: 'float' object has no attribute 'index' My desired output is something like: Fold id time a t1 1.000000 t2 1.545455 t3 1.000000 b t1 1.000000 t2 1.062500 t3 0.937500 c t2 NaN t3 NaN Does anyone know what I did wrong? Thank you for the help in advance.
has comment: http://stackoverflow.com/comment/84760821
type: Question
possible better answer: http://stackoverflow.com/a/48878572
downvote count: 0
accepted answer: http://stackoverflow.com/a/48878495
answer count: 3
tagged with: pandas
has title: apply lambda function after groupby based on values of another column in pandas
favorite count: 0

http://stackoverflow.com/q/48956426
tagged with: google-cloud-dataflow
tagged with: google-cloud-storage
accepted answer: http://stackoverflow.com/a/48986374
type: AnsweredQuestion
has body: I was using FileSystems inside a ParDo to be able to write to dynamic destinations in data storage. However I was not able to do automatic sharding as in Text.IO using wildcard for filename? Is there a way that I can do automatic sharding in FileSystems.create? Edited: This is the pipeline I used to run, the part of code in question is WriteToStorage where I want to write the result to date{week}at{year}/results*.json with beam.Pipeline(options=pipeline_options) as p: pcoll = (p | ReadFromText(known_args.input) | beam.ParDo(WriteDecompressedFile()) | beam.Map(lambda x: ('{week}at{year}'.format(week=x['week'], year=x['year']), x)) | beam.GroupByKey() | beam.ParDo(WriteToStorage())) Here's the current version of WriteToStorage() class WriteToStorage(beam.DoFn): def __init__(self): self.writer = None def process(self, element): (key, val) = element week, year = [int(x) for x in key.split('at')] if self.writer == None: path = known_args.output + 'date-{week}at{year}/revisions-from-{rev}.json'.format(week=week, year=year, rev=element['rev_id']) self.writer = filesystems.FileSystems.create(path) logging.info('USERLOG: Write to path %s.'%path) logging.info('TESTLOG: %s.'%type(val)) for output in val: self.writer.write(json.dumps(output) + '\n') def finish_bundle(self): if not(self.writer == None): self.writer.close() Thank you.
type: Question
tagged with: python
has title: Python: Automatic sharding in FileSystems.create() for a writing channel in Dataflow
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48986374

http://stackoverflow.com/q/48938198
has title: adding a day date in time.struct_time object
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48938886
type: Question
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/48938886
answer count: 1
tagged with: python
has body: I need your help with my current code. I want to add the next day date using with time.struct_time object, but I have got no idea how to do this after I have stored the string in the self.epg_time_1 list. Example: time.struct_time(tm_year=2018, tm_mon=2, tm_mday=22, tm_hour=17, tm_min=00, tm_sec=0, tm_wday=3, tm_yday=53, tm_isdst=-1) To this: time.struct_time(tm_year=2018, tm_mon=2, tm_mday=23, tm_hour=17, tm_min=00, tm_sec=0, tm_wday=3, tm_yday=53, tm_isdst=-1)[/python] If I want to add the next day, I would have to readd the same code that I have already been using: epg_time_1_days = time.strftime("%d") epg_time_1_months = time.strftime("%m") epg_time_1_year = time.strftime("%Y") epg_time_1_days = int(time.strftime("%d") + 1) epg_time_1_days = str(today_day) epg_time_1_months = str(epg_time_1_months) epg_time_1_year = str(epg_time_1_year) half_hour_date = str(epg_time_1_days + "/" + epg_time_1_months + "/" + epg_time_1_year + " " + "17:30PM") self.epg_time_1.append(half_hour_date) Here is the code: half_hour_date = ''.join(str(x) for x in self.epg_time_1) epg_time_1 = time.strptime(half_hour_date, '%d/%m/%Y %I:%M%p') Output for half_hour_date: 22/02/2018 5:00PM Output for epg_time_1: time.struct_time(tm_year=2018, tm_mon=2, tm_mday=22, tm_hour=17, tm_min=00, tm_sec=0, tm_wday=3, tm_yday=53, tm_isdst=-1) I don't want to re-add the same code that I have already wrote it. If you can show me an example how I could use a short simple code to add the date to the next day date using with time.struct_time object, that would be great.

http://stackoverflow.com/a/48834485
score: 3
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84673833
has comment: http://stackoverflow.com/comment/84675132
has body: Based on your code, you need to specify the SenderInfo in your Message object. &gt;&gt;&gt; s = SenderInfo(sender='charles') &gt;&gt;&gt; s.save() &gt;&gt;&gt; m = Messages(message=s, message_body='this is a test') &gt;&gt;&gt; m.save() Or the same: m = Messages.objects.create(message=s, message_body='your message')
type: Answer
has comment: http://stackoverflow.com/comment/84674790
has comment: http://stackoverflow.com/comment/84675152
has comment: http://stackoverflow.com/comment/84674221
accepted answer of: http://stackoverflow.com/q/48834286
upvote count: 3
answers question: http://stackoverflow.com/q/48834286
has comment: http://stackoverflow.com/comment/84674645
has comment: http://stackoverflow.com/comment/84674479
has comment: http://stackoverflow.com/comment/84673908

http://stackoverflow.com/q/48927972
tagged with: sqlite
answer count: 1
downvote count: 0
has title: Python SQL cells interaction
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48928441
score: 3
upvote count: 3
has body: I am using Python to try to gather the closing price for couple of different time intervals, save it in a database and then calculate the change in the closing price. This is my code: def database_populate(symbol, interval): base_url = "https://www.binance.com/api/v1" url_klines = "/klines" end_time = requests.get('{}/time'.format(base_url)).json()['serverTime'] start_time = end_time - 360000 kln = requests.get('{a}{b}?symbol={c}&amp;interval={d}&amp;startTime={e}&amp;endTime={f}'.format(a = base_url, b = url_klines, c = symbol, d = interval, e = start_time, f = end_time)).json() db = sqlite3.connect('database.db') cursor = db.cursor() cr_db = """ CREATE TABLE EOSBTC_symbol ( ID INTEGER PRIMARY KEY AUTOINCREMENT, EPOCH_TIME INTEGER NOT NULL, CLOSE_PRICE FLOAT, CHANGE FLOAT ) """ cursor.execute(cr_db) for i in range(len(kln)): lst = [kln[i][0], kln[i][4]] cursor.execute("""INSERT INTO EOSBTC_symbol (EPOCH_TIME, CLOSE_PRICE) VALUES (?, ?)""", (lst[0], lst[1])) db.commit() db.close() database_populate("EOSBTC", "1m") This is populating the database with the closing price for a certain time period for the pair EOSBTC. I want to calculate the change in the closing price between two consecutive rows. Do I need to use the ID or the epoch time or there is another more elegant way? Just keep in mind that this DB will be continuously updated, so the ID and the EPOCH_TIME will change with time, and I want to calculate CHANGE field immediately after I populate these cells from the Binance API. This is the database content at the moment: For example for in row 6 the CHANGE will be equal to 0.00082563 - 0.00082587, for row 5 0.00082587 - 0.00082533 and so on.
type: Question
tagged with: database
tagged with: rest

http://stackoverflow.com/q/48936202
answer count: 4
score: 2
has comment: http://stackoverflow.com/comment/84879177
has comment: http://stackoverflow.com/comment/84879239
tagged with: string-parsing
has body: I have the following string in python: text = "vagrant 11450 4344 0 Feb22 pts/2 00:00:28 python run.py abc" I want to capture the text after time field that is "python run.py abc" I am using the following regex but it is not working [\d:]+ (.)*
type: Question
has title: How to parse this string in python using regex?
downvote count: 0
has answer: http://stackoverflow.com/a/48936461
favorite count: 0
has answer: http://stackoverflow.com/a/48936274
has answer: http://stackoverflow.com/a/48936261
has answer: http://stackoverflow.com/a/48936310
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: regex

http://stackoverflow.com/a/48911452
answers question: http://stackoverflow.com/q/48911270
downvote count: 0
upvote count: 2
has body: Not sure what problem you face but below command worked for me pip install python-gettext
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84829939

http://stackoverflow.com/q/48895960
has comment: http://stackoverflow.com/comment/84797779
tagged with: python
has title: Saving data in the database with Django
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48937215
tagged with: django
has body: I've been trying to save my POST data to the database using the ModelForm but I couldn't make it go there for some reason.When I try to send the forms the page is redirecting me to the right place however the DB is still empty.I am not sure what am I doing wrong. forms.py class AddProblem(forms.ModelForm): class Meta: model = problem fields = ('lat','lng','email','importance','description','images') models.py class problem(models.Model): lat = models.BigIntegerField() lng = models.BigIntegerField() email = models.EmailField(max_length=70,blank=True) importance = models.IntegerField(default=1) description = models.TextField() images = models.FileField(upload_to='images/') published = models.BooleanField() def __str__(self): return self.email views.py def addproblem(request): temp_name = 'google_api/addproblem.html' form = AddProblem(request.POST,request.FILES) if request.method == 'POST': if(form.is_valid()): form.save() form = AddProblem() return redirect('/') else: messages.error(request, "Error") context = { } return render(request, temp_name, context) urls.py urlpatterns = [ path('', views.index, name='index'), path('add/', views.addproblem, name='addproblem'), ] template {% csrf_token %} Lat: Lng: Емайл Важност 1 2 3 4 5 6 7 8 9 10 Описание на проблема. Качете снимки
has answer: http://stackoverflow.com/a/48896165
type: Question
score: 0
answer count: 2

http://stackoverflow.com/q/48872564
linked to: http://stackoverflow.com/q/33398282
type: Question
has comment: http://stackoverflow.com/comment/84756776
tagged with: nltk
linked to: http://stackoverflow.com/q/25827058
has title: I use python 3.6 and i want to make sentiment analysis but i have an error in nltk.metrics package?
tagged with: sentiment-analysis
upvote count: 1
answer count: 1
downvote count: 0
tagged with: precision
favorite count: 0
tagged with: metrics
has body: i write the code as here : print ('pos precision:', nltk.metrics.precision(refsets['pos'], testsets['pos'])) print ('pos recall:', nltk.metrics.recall(refsets['pos'], testsets['pos'])) and the output as here : line 35, in evaluate_classifier print ('pos precision:', nltk.metrics.precision(refsets['pos'], testsets['pos'])) AttributeError: module 'nltk.translate.metrics' has no attribute 'precision' How can i solve this error ?
duplicate of: http://stackoverflow.com/q/33398282
tagged with: python
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48872610
accepted answer: http://stackoverflow.com/a/48872610

http://stackoverflow.com/q/48814937
favorite count: 0
has comment: http://stackoverflow.com/comment/84634980
tagged with: tkinter
upvote count: 3
has comment: http://stackoverflow.com/comment/84634721
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/17039481
accepted answer: http://stackoverflow.com/a/48815667
has comment: http://stackoverflow.com/comment/84635007
tagged with: image
has title: Tkinter transparency on label
type: Question
has comment: http://stackoverflow.com/comment/84634933
has body: from tkinter import * master = Tk() master.resizable(False, False) master.geometry('430x480+50+50') master.title("Ping Check") master.config(bg="#222") layer = PhotoImage(file ="logo.gif") topFrame = Label(text="Ping Checker", image=layer, fg="#fff", font="Bahnschrift 14") topFrame.place(x=11,y=10) I'm using the following code, which displays the image, however, the label seems to have a background, which I do not want. and the file https://i.sstatic.net/JgOg0.jpg
downvote count: 0
linked to: http://stackoverflow.com/q/10461045
tagged with: label
tagged with: transparency
has comment: http://stackoverflow.com/comment/84634659
score: 3
has answer: http://stackoverflow.com/a/48815667
answer count: 1

http://stackoverflow.com/q/48888713
has comment: http://stackoverflow.com/comment/84783595
has comment: http://stackoverflow.com/comment/84782751
has answer: http://stackoverflow.com/a/48906493
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/84783898
score: 0
has body: I have a problem with relative url in django application. I have structure of objects which look like this Competitions/ games/ players/ costs/ and urls to point to it competitions/ - list of all competitions {% for comp in competitions%} comp.name {% endfor %} When I clik on one of this links I'm redirected to page competitions/<competitions_id> competitions/<int:competition_id> - detail view of a competition competitions/games/<int:competition_id> - list of all game in picked competition {% for game in games%} game.name {% endfor %} So when I'm on url: competitions/games/1 which list all games in competition with id = 1 game1 game2 game3 game4 And I click for example on game4 my url address is competitions/games/4 instead of competitions/games/1/4 can someone explain me why.
has title: Relative URL replace part of old url instead of add to old one in django
answer count: 1
tagged with: url
has comment: http://stackoverflow.com/comment/84784170
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/comment/84858142
type: AnswerComment
type: Comment
has text: Thanks for the tip. Unfortunately your solution does not work.Have you tried yourself? It fails for `tornado`. It seems it does not download the packages by the same order when you change `--python-version='36'` to `--python-version='3.6'`. But you can see `tornado` is like `pandocfilters`, both only have source versions on PyPI.
score: 1
comment on: http://stackoverflow.com/a/48912975

http://stackoverflow.com/a/79440712
type: Answer
score: 0
has body: To get the classes back from sklearn.preprocessing.LabelEncoder, use the .classes_ attribute of it. # Labels labels = ["background", "objective", "method", "result", "conclusion"] # Initialize and fit the LabelEncoder encoder = LabelEncoder() encoded_labels = encoder.fit_transform(labels) print(encoder.classes_)
answers question: http://stackoverflow.com/q/48938905

http://stackoverflow.com/comment/84767567
comment on: http://stackoverflow.com/a/48857458
score: 0
type: Comment
has text: @Lylio, my mistake, I used the `card-list` url name as an example for the delete view success redirect and accidentally used it in the `url` example at the end of the answer as well. I edited the post to fix this.
type: AnswerComment

http://stackoverflow.com/comment/84921952
has text: Ok can you answer with the exact code using subprocess to make this happen ?
comment on: http://stackoverflow.com/q/48957481
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84638100
type: Comment
comment on: http://stackoverflow.com/a/48815783
has text: I did not get any errors, but the file was not created in S3.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84701227
type: QuestionComment
score: 0
has text: Certain cell, you'd need the row index `i` and the column index `j`, and just index: `list_2d[i][j]`.
comment on: http://stackoverflow.com/q/48837999
type: Comment

http://stackoverflow.com/q/48841190
has comment: http://stackoverflow.com/comment/84693305
favorite count: 0
has answer: http://stackoverflow.com/a/48842845
linked to: http://stackoverflow.com/q/29158220
tagged with: python
has title: tkinters mainloop has trapped my foo
type: AnsweredQuestion
tagged with: interpreter
tagged with: tkinter
linked to: http://stackoverflow.com/q/32114026
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48842845
has comment: http://stackoverflow.com/comment/84687786
score: -1
has body: I've seen numerous question on this site, where people ask how user-written code, say a function foo, can be executed in tkinter's mainloop, e.g. this or this. Two alternatives exist: Use the after method, or use threading. I'd like to know more about how the after method actually works. More precisely, inspired by this excellent article, where a very high-level description of how the GIL in Python works is given, I'd like to know more how the after method works in terms of the Python interpreter processing foo inside tkinter's mainloop. I'm particularly confused how the CPython interpreter steps through the code, when I insert code using after. How is foo ending up being executed by tkinter's mainloop? What I found so far: Bryan Oakley, quoted from the first link, says: "after does not create another thread of execution. Tkinter is single-threaded. after merely adds a function to a queue." But inspecting the source code def after(self, ms, func=None, *args): """Call function once after given time. MS specifies the time in milliseconds. FUNC gives the function which shall be called. Additional parameters are given as parameters to the function call. Return identifier to cancel scheduling with after_cancel.""" if not func: # I'd rather use time.sleep(ms*0.001) self.tk.call('after', ms) else: def callit(): try: func(*args) finally: try: self.deletecommand(name) except TclError: pass callit.__name__ = func.__name__ name = self._register(callit) return self.tk.call('after', ms, name) doesn't really help me, as it doesn't reveal the answers to these questions, and I'm a novice programmer, so I don't really understand how to trace this further.
has comment: http://stackoverflow.com/comment/84687142
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/84800439
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48891286
type: Comment
has text: Result is still 476798

http://stackoverflow.com/comment/84668775
has text: The reason for the IntegrityError is that you don't have an user with `id == 1` in the database. Try to override the classmethod `setUpTestData` and make sure you have created a user with id 1 there.
comment on: http://stackoverflow.com/q/48831595
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48908828
type: AnsweredQuestion
downvote count: 1
has title: Python Pandas Series if else box plot
linked to: http://stackoverflow.com/q/48874706
type: Question
score: 3
accepted answer: http://stackoverflow.com/a/48986981
tagged with: matplotlib
possible better answer: http://stackoverflow.com/a/48909500
upvote count: 4
linked to: http://stackoverflow.com/q/34139163
answer count: 2
has answer: http://stackoverflow.com/a/48909500
tagged with: pandas
has comment: http://stackoverflow.com/comment/84979546
tagged with: data-science
favorite count: 0
tagged with: python-3.x
has body: I have alot of data in a dictionary format and I am attempting to use pandas print a string based on an IF ELSE statement. For my example ill make up some data in dict and covert to Pandas: df = pd.DataFrame(dict(a=[1.5,2.8,9.3],b=[7.2,3.3,4.9],c=[13.1,4.9,15.9],d=[1.1,1.9,2.9])) df This returns: a b c d 0 1.5 7.2 13.1 1.1 1 2.8 3.3 4.9 1.9 2 9.3 4.9 15.9 2.9 My IF ELSE statement: for col in df.columns: if (df[col] &lt; 4).any(): print('Zone %s does not make setpoint' % col) else: print('Zone %s is Normal' % col) Returns: Zone a does not make setpoint Zone b does not make setpoint Zone c is Normal Zone d does not make setpoint But now I want to add in an extra to create a box plot where I am not making setpoint and also average the data frame where it is making setpoint. I know this is pandas series, but can pandas.Series.plot.box() be used? This is my IF ELSE statement that I am using in a function with df.apply(lamba x:) and I am stuck trying to get the box box plot to work in pandas series... Any advice is greatly appreciated! import matplotlib.pyplot as plt def _print(x): if (x &lt; 4).any(): print('Zone %s does not make setpoint' % x.name) df.boxplot() plt.show() else: print('Zone %s is Normal' % x.name) print('The average is %s' % x.mean()) Im getting an error when I am calling df.apply(lambda x: _print(x)) module 'matplotlib' has no attribute 'show'
has answer: http://stackoverflow.com/a/48986981
tagged with: python

http://stackoverflow.com/a/48952410
answers question: http://stackoverflow.com/q/48952350
has body: This should help. # -*- coding: utf-8 -*- json_data = [ {'version': { 'rowVersion': 2044}, 'name': 'Administrator', 'permissions': [ {'path': 'Activity/Cancel All', 'name': 'Activity/Cancel All'}, {'path': 'Activity/View All', 'name': 'Activity/View All'}, {'path': 'Audit Log/Edit', 'name': 'Audit Log/Edit'}, {'path': 'Audit Log/View', 'name': 'Audit Log/View'} ], 'id': 1, 'permissionPaths': ['Activity/Cancel All', 'Activity/View All', 'Audit Log/Edit', 'Audit Log/View'], 'displayName': 'Administrator' }, {'version': { 'rowVersion': 964033}, 'name': 'ViewOnly', 'permissions': [ {'path': 'Activity/View All', 'name': 'Activity/View All'}, {'path': 'Audit Log/View', 'name': 'Audit Log/View'}, ], 'id': 4, 'permissionPaths': ['Activity/View All', 'Audit Log/View'], 'displayName': 'ViewOnly' } ] for ROLES in json_data: for n in ROLES["permissions"]: print(ROLES["name"], n["name"]) Output: ('Administrator', 'Activity/Cancel All') ('Administrator', 'Activity/View All') ('Administrator', 'Audit Log/Edit') ('Administrator', 'Audit Log/View') ('ViewOnly', 'Activity/View All') ('ViewOnly', 'Audit Log/View')
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
accepted answer of: http://stackoverflow.com/q/48952350
upvote count: 1

http://stackoverflow.com/comment/84631477
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48813922
has text: When executing this code it shows the error message `AttributeError: '<invalid type>' object has no attribute 'onscreenclick' on line 42` that is caused by the line `turtle.onscreenclick...`. Can you please resolve this as I am not able to reproduce otherwise.
score: 0

mplot3d
tags question: http://stackoverflow.com/q/48957501
tag name: mplot3d
tags question: http://stackoverflow.com/q/48886028
type: Tag
tags question: http://stackoverflow.com/q/48937176

http://stackoverflow.com/a/68725493
answers question: http://stackoverflow.com/q/48901990
score: 0
has body: Add this in your settings.py file: AWS_QUERYSTRING_AUTH = False
type: Answer

http://stackoverflow.com/a/48947050
has body: First of all, I think it is interesting to highlight that Google Cloud Storage uses a flat name space, and in fact the concept of "directories" does not exist, as there is no hierarchical file architecture being stored in GCS. More information about how directories work can be found in the documentation, so it is a good read if you are interested in this topic. That being said, you can use a script such as the one I share below, in order to download all files in a "folder" in GCS to the same folder in your local environment. Basically, the only important addition a part from your own code is that the bucket.list_blobs() method is being called, with the prefix field pointing to the folder name, in order to look for blobs which only match the folder-pattern in their name. Then, you iterate over them, discard the directory blob itself (which in GCS is just a blob with a name ending in "/"), and download the files. from google.cloud import storage import os # Instantiate a CGS client client=storage.Client() bucket_name= "&lt;YOUR_BUCKET_NAME&gt;" # The "folder" where the files you want to download are folder="&lt;YOUR_FOLDER_NAME&gt;/" # Create this folder locally if not os.path.exists(folder): os.makedirs(folder) # Retrieve all blobs with a prefix matching the folder bucket=client.get_bucket(bucket_name) blobs=list(bucket.list_blobs(prefix=folder)) for blob in blobs: if(not blob.name.endswith("/")): blob.download_to_filename(blob.name)
downvote count: 0
answers question: http://stackoverflow.com/q/48944923
type: Answer
upvote count: 5
score: 5

http://stackoverflow.com/comment/84746665
has text: So far, your comment is the closest to a possible answer. Could you please post it as an answer so if it works I can choose it as correct? (maybe with a little more detail) @AntiMatterDynamite
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48836940

http://stackoverflow.com/q/48911436
has answer: http://stackoverflow.com/a/48952393
accepted answer: http://stackoverflow.com/a/48952393
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84850843
has title: PyOpenGL how to rotate a scene with the mouse
tagged with: python
tagged with: pygame
has body: I am trying to create a simple scene in 3d (in python) where you have a cube in front of you, and you are able to rotate it around with the mouse. I understand that you should rotate the complete scene to mimic camera movement but i can't figure out how you should do this. Just to clarify I want the camera (or scene) to move a bit like blender (the program). Thanks in advance
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84911207
tagged with: pyopengl
type: Question
tagged with: blender

http://stackoverflow.com/q/48892343
has answer: http://stackoverflow.com/a/48896198
has title: External Module into Flask - TypeError: 'Series' object is not callable
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84790386
tagged with: python
type: Question
tagged with: flask
score: 0
has body: I am looking to bring in an external module into flask 'reommendationSearch', which essentially calculates the similarity of movie titles based frequency of similar key words My issue arises when attempting to integrate this with flask, where 'title' is 'search_string'. Error: 'AttributeError: 'NoneType' object has no attribute 'indices'. Here is the traceback: Traceback Snapshot Flask Code: from flask import Flask, render_template, flash, redirect, url_for, session, logging, request from wtforms import Form,StringField, TextAreaField, PasswordField, validators from ReccomendationTest import reommendationSearch # Parse HTML Page via Flask @app.route('/') def index(): return render_template('home.html') class searchForm(Form): search = StringField('Movie Title:') @app.route('/about',methods = ['GET','POST']) def search_results(): form = searchForm(request.form) search_string = form.search.data search_results = reommendationSearch() output_results = search_results.get_recommendations(search_string) results=[] if request.method == 'POST': return(output_results) if __name__ =="__main__": app.secret_key='secret123' app.run() ReccomendationTest : import pandas as pd import numpy as np import os from ast import literal_eval from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import linear_kernel class reommendationSearch(): #Import the Open Source Dataset os.chdir('C:\\Users\parmi\Documents\Python Scripts') org_data = pd.read_csv('tmdb_5000_movies.csv') #Define a TF-IDF Vectorizer Object. Remove all english stop words such as 'the', 'a' tfidf = TfidfVectorizer(stop_words='english') #Replace NaN with an empty string org_data['overview'] = org_data['overview'].fillna('') #Construct the required TF-IDF matrix by fitting and transforming the data tfidf_matrix = tfidf.fit_transform(org_data['overview']) # Compute Consine Similarirty Matrix cosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix) indices = pd.Series(org_data.index, index=org_d…
answer count: 1
has comment: http://stackoverflow.com/comment/84790288

http://stackoverflow.com/comment/84820388
type: AnswerComment
has text: Perfect ! Thank you ! I had a quick search among already existing questions but didn't find that one, sorry.
comment on: http://stackoverflow.com/a/48907205
type: Comment
score: 0

http://stackoverflow.com/a/48848385
has comment: http://stackoverflow.com/comment/84700771
has comment: http://stackoverflow.com/comment/84700745
has comment: http://stackoverflow.com/comment/84700623
score: 0
answers question: http://stackoverflow.com/q/48848357
has comment: http://stackoverflow.com/comment/84700785
has comment: http://stackoverflow.com/comment/84700830
type: Answer
has comment: http://stackoverflow.com/comment/84700763
has comment: http://stackoverflow.com/comment/84700611
has body: I'm not exactly sure why you're getting that error, but you can bypass it by just calling json.loads() on the text of the request: result = requests.get("https://crix-api-endpoint.upbit.com/v1/crix/candles/minutes/1?code=CRIX.UPBIT.KRW-XRP&amp;count=1") result_text = result.text json_data = json.loads(result_text) return json_data[0]["highPrice"] You'll need to import json however. Also, you'll need to get the dictionary out of the list (hence the [0]). EDIT: This is actually really bizarre: sometimes it's printing out a result and other times it's raising an error. It could have to do with the request being different over a very short period of time.

http://stackoverflow.com/q/48906828
accepted answer: http://stackoverflow.com/a/48907057
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84833127
tagged with: dataframe
has body: Using Python, I want to count the number of cells in a row that has data in it, in a pandas data frame and record the count in the leftmost cell of the row.
has answer: http://stackoverflow.com/a/48907057
type: Question
has comment: http://stackoverflow.com/comment/84819390
tagged with: pandas
has comment: http://stackoverflow.com/comment/84824428
answer count: 1
has comment: http://stackoverflow.com/comment/84820591
favorite count: 0
tagged with: data-analysis
tagged with: python
downvote count: 2
score: 6
has title: Count non-empty cells in pandas dataframe rows and add counts as a column
upvote count: 8

http://stackoverflow.com/comment/84853120
type: AnswerComment
has text: Thank you for your answer! Can you tell me why/when I need the data to be contiguous? Is it just performance, or some other reason? Does PyTorch require contiguous data for some operations? Why does targets need to be contiguous and inputs not?
comment on: http://stackoverflow.com/a/48922607
type: Comment
score: 1

http://stackoverflow.com/q/48913271
answer count: 0
type: UnansweredQuestion
tagged with: weather
has body: I'm curious if neural networks (or neurolab in particular) needs the target/input data to be [-1:1]? I'm trying to train a network to predict water evaporation from my kitchen garden, given these inputs: temperature (C), barometer (mbar), precipitation (mm), wind (m/s) and initial soil moisture (%), where each row of data represents 1 hour. The training data is simply the measured delta soil moisture (%) by the end of the hour. I have collected ~1020 samples of data - perhaps this isn't enough? All of these values are outside the range of -1:1 (temperature goes to -5, and barometer to 1040). I'm completely blank on neural networks, and have read a bit and done self-study only, but I would have expected that it should be fine to use larger numbers? Code: in_min_max = [ [0, 100], # initial soil humidity [950, 1050], # hpa [0, 40], # precip_mm [0, 100], # wind_mps, [-5, 40] # temp ] # Create net with 5 inputs and 3 hidden, 1 output neuron net = nl.net.newff(in_min_max, [5, 1]) net.trainf = nl.train.train_gd error = net.train(i_data, t_data, epochs=500, show=100, goal=0.01) print error Output: Epoch: 100; Error: 27215.4999985; Epoch: 200; Error: 27215.4999985; Epoch: 300; Error: 27215.4999985; Epoch: 400; Error: 27215.4999985; Epoch: 500; Error: 27215.4999985; The maximum number of train epochs is reached [26831.39953304854, 27190.818210734968, 26736.57181692442, 27215.499998465435, 27215.499998465435, 27215.499998465435, 27215.499998465435, 27215.499998465435, 27215.499998465435, 27215.499998465435, 27215.499998465435, 27215.499998465435, 27215.499998465435, 27215.49999846543, 27215.49999846543, 27215.499998465435, 27215.499998465428, 27215.499998465428, 27215.499998465428, 27215.499998465428, 27215.499998465428, 27215.499998465428, 27215.499998465428, 27215.499998465428, 27215.499998465428, 27215.499998465428, 27215.499998465424, 27215.499998465428, 27215.499998465424, 27215.49999846542, 27215.49999846542, 27215.499998465424, 27215.499998465424, 27215.499998465424, 27…
has comment: http://stackoverflow.com/comment/84867064
type: Question
has comment: http://stackoverflow.com/comment/84833205
has title: do neural network in/output need to be [-1:1]?
tagged with: neural-network
score: 0
tagged with: python
tagged with: neurolab
has comment: http://stackoverflow.com/comment/84836928

python-unicode
tags question: http://stackoverflow.com/q/48927303
tags question: http://stackoverflow.com/q/48849394
tag name: python-unicode
type: Tag
tags question: http://stackoverflow.com/q/48911850

http://stackoverflow.com/a/65770779
has body: This will surely work. Just follow the steps: Create a "python" directory inside any empty directory and pip install the modules there mkdir lambda_layers cd lambda_layers mkdir python cd python pip install requests -t ./ cd .. zip -r python_modules.zip . If you want to have multiple modules in a single layer then install them inside the same 'python' directory that you have just created. Just make sure that you zip the "python" directory itself recursively with '-r'. That way lambda handler can locate the module in the default python version that you are using. Now you have your 'python_modules.zip' file with all the dependent modules inside. Go to the Layers of Lambda in the AWS console and create a layer uploading this zip file. Choose the runtimes as per your python version that you are using in your lambda function, or you can select multiple python runtime versions. Add this layer to your lambda function and you should be able to import your modules flawlessly.
has comment: http://stackoverflow.com/comment/133806940
upvote count: 23
answers question: http://stackoverflow.com/q/48912253
downvote count: 0
has comment: http://stackoverflow.com/comment/135509297
has comment: http://stackoverflow.com/comment/128660052
has comment: http://stackoverflow.com/comment/133605339
type: Answer
score: 23

http://stackoverflow.com/comment/84896658
score: 0
comment on: http://stackoverflow.com/a/48943822
type: AnswerComment
type: Comment
has text: Checkout my updated answer and let me know the status.

http://stackoverflow.com/a/48918733
type: Answer
has comment: http://stackoverflow.com/comment/84843853
upvote count: 5
score: 5
has body: Updated simplified using integer arithmetic. Here's a one-liner: np.arange(n+k-1, n-1, -1) // k Little demo: &gt;&gt;&gt; for k in range(4, 10, 3): ... for n in range(10, 17): ... np.arange(n+k-1, n-1, -1) // k ... array([3, 3, 2, 2]) array([3, 3, 3, 2]) array([3, 3, 3, 3]) array([4, 3, 3, 3]) array([4, 4, 3, 3]) array([4, 4, 4, 3]) array([4, 4, 4, 4]) array([2, 2, 2, 1, 1, 1, 1]) array([2, 2, 2, 2, 1, 1, 1]) array([2, 2, 2, 2, 2, 1, 1]) array([2, 2, 2, 2, 2, 2, 1]) array([2, 2, 2, 2, 2, 2, 2]) array([3, 2, 2, 2, 2, 2, 2]) array([3, 3, 2, 2, 2, 2, 2])
downvote count: 0
answers question: http://stackoverflow.com/q/48918627

http://stackoverflow.com/q/48821732
tagged with: python
has title: dictionary/list mapping for bokeh plotting glyphs
has comment: http://stackoverflow.com/comment/84647569
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84646891
tagged with: bokeh
type: Question
has body: Am relatively new to python, and even naive in bokeh. I have a dataframe that looks something like below: DEPT CATEGORY AMOUNT 500 AB11 -100 620 BF66 0 620 CD45 500 ......... ......... 2311 AB11 250 I am looking to have a scatterplot in the form of circle glyhs where the size of the circle would be some function of amount. The x and y axis need to be DEPT and CATEGORY. The problem appears to be when: Not all DEPTs have the same number of CATEGORY; leading to a possible mapping issue ? Not all Amounts are >0, so the size may also be an issue. I would like to have the negative numbers to have circles filld with red, the others in blue or white. 3.If the Amounts are huge, I dont mind using a log of the number to bring it down to a reasonable scale/size. What am currently trying to code is something like this: from bokeh.plotting import figure, output_file, show x=[df['DEPT']] y=[df['CATEGORY']] plot = figure(plot_width=300, plot_height=300) plot.circle(x=x, y=y, size=(df['AMOUNT'])) show(plot) C:\log\Anaconda3\lib\site-packages\bokeh\models\sources.py:89: BokehUserWarning: ColumnDataSource's columns must be of the same length lambda: warnings.warn("ColumnDataSource's columns must be of the same length", BokehUserWarning)) C:\log\Anaconda3\lib\site-packages\bokeh\models\sources.py:89: BokehUserWarning: ColumnDataSource's columns must be of the same length lambda: warnings.warn("ColumnDataSource's columns must be of the same length", BokehUserWarning))
has comment: http://stackoverflow.com/comment/84647162
tagged with: pandas
upvote count: 1
has comment: http://stackoverflow.com/comment/84654122
has comment: http://stackoverflow.com/comment/84647974
favorite count: 0
has comment: http://stackoverflow.com/comment/84647228
has comment: http://stackoverflow.com/comment/84647112
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84646992

http://stackoverflow.com/a/48843302
type: Answer
score: 3
has comment: http://stackoverflow.com/comment/84704474
upvote count: 3
answers question: http://stackoverflow.com/q/48843120
has comment: http://stackoverflow.com/comment/84690903
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48843120
downvote count: 0
has comment: http://stackoverflow.com/comment/84691106
has body: I believe that the original problem you are trying to solve is to get the counts of the names. If that's the case, then it can be accomplished much more easily using Counter from Python's collections module. from collections import Counter cnt = Counter() with open("nameList.csv", 'r') as f: rd = csv.reader(f) cnt = Counter(r[0] for r in rd) print(cnt) cnt will be dict-like object (you can use it just like any other dictionary) where the keys are the names from the CSV and the values are the counts. So, it might look something like this: {'john': 3, 'mike': 1, 'sam': 1} Now suppose you have another CSV with names and you want to find the count of each name in both the files. You can do this just as easily, by updating cnt: with open("nameList2.csv", 'r') as f: rd2 = csv.reader(f) cnt.update(r[0] for r in rd2) You avoid counting from scratch and the code is way more sexy! Simple and elegant!
has comment: http://stackoverflow.com/comment/84692367

http://stackoverflow.com/q/48816011
has title: Python ValueError: Bin edges must be unique
tagged with: bin
tagged with: error-handling
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84637288
accepted answer: http://stackoverflow.com/a/48816729
has comment: http://stackoverflow.com/comment/84636524
score: 0
has comment: http://stackoverflow.com/comment/84637242
tagged with: pandas
answer count: 1
favorite count: 0
linked to: http://stackoverflow.com/q/20158597
tagged with: python
has answer: http://stackoverflow.com/a/48816729
has comment: http://stackoverflow.com/comment/84636492
type: AnsweredQuestion
has body: Working in python with pandas, I am trying to assign control and treatment groups to different groups of customers. I have a large dataset. Instead of giving an example of the data, let me show you the pivot, since this summarizes the most important data. pd.pivot_table(df,index=['Test Group'],values=["Customer_ID"],aggfunc=lambda x: len(x.unique())) I get those counts Test Group Customer_ID Innovators 4634 Early Adopters 2622 Early Majority 8653 Late Majority 7645 Laggards 7645 Lost 4354 Prospective 653 I run the following code: percentages = {'Innovators':[0.0,1.0],\ 'Early Adopters':[0.2,0.8], \ 'Early Majority':[0.1,0.9],\ 'Late Majority':[0.0,1.0],\ 'Laggards':[0.2,0.8],\ 'Lost':[0.1,0.9],\ 'Prospective':[0.1,0.9]} def assigner(gp): ...: group = gp['Test Group'].iloc[0] ...: cut = pd.qcut( np.arange(gp.shape[0]), q=np.cumsum([0] + percentages[group]), labels=range(len(percentages[group])) ).get_values() ...: return pd.Series(cut[np.random.permutation(gp.shape[0])], index=gp.index, name='flag') df['flag'] = df.groupby('Test Group', group_keys=False).apply(assigner) ValueError: Bin edges must be unique: array([ 0, 0, 2621], dtype=int64). You can drop duplicate edges by setting the 'duplicates' kwarg ... and keep on getting this error I found this answer, which could be helpful How to qcut with non unique bin edges? ; but rank dowsn't work for np def assigner(gp): ...: group = gp['Campaign Test Description'].iloc[0] ...: cut = pd.qcut( np.arange(gp.shape[0]).rank(method='first'), q=np.cumsum([0] + percentages[group]), labels=range(len(percentages[group])) ).get_values() ...: return pd.Series(cut[np.random.permutation(gp.shape[0])], index=gp.index, name='flag') AttributeError: 'numpy.ndarray' object has no attribute 'rank' I tried dropping duplicates def assigner(gp): ...: group = gp['Campaign Test Description'].iloc[0] ...: cut = pd.qcut( np.arange(gp.shape[0]), q=np.cumsum([0] + percentages[group]), labels=range(len(percentages[group])),duplicates='drop' ).get_va…

http://stackoverflow.com/comment/84880785
has text: @HuStmpHrr I don't completely agree with you since I only keep it to my personal ( and this means only read/used by me ) projects. But I totally agree from a team perspective and understand that It's probably true that I should just try and pass over this (non)-issue I have with temp variables. Thank you for the advices
score: 0
comment on: http://stackoverflow.com/q/48936533
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48932732
answer count: 3
has comment: http://stackoverflow.com/comment/84873059
tagged with: python
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/48932860
favorite count: 0
linked to: http://stackoverflow.com/q/3282823
upvote count: 3
has body: I have a list that holds a dictionary row like this: queue = [{1: 0.39085439023582913, 2: 0.7138416909634645, 3: 0.9871959077954673}] I'm tryin to get it to return the smallest value along with its key, so in this case it would return 1,0.39085439023582913 I've tried using min(queue, key=lambda x:x[1]) but that just returns the whole row like this: any suggestions? thank you! {1: 0.39085439023582913, 2: 0.7138416909634645, 3: 0.9871959077954673}
type: AnsweredQuestion
score: 3
tagged with: list
has title: getting minimum (key, value) in a list that holds a dictionary
type: Question
has answer: http://stackoverflow.com/a/48932860
tagged with: min
has answer: http://stackoverflow.com/a/48932833
downvote count: 0
possible better answer: http://stackoverflow.com/a/48932820
has answer: http://stackoverflow.com/a/48932820

http://stackoverflow.com/comment/125314701
type: AnswerComment
comment on: http://stackoverflow.com/a/65604939
has text: Worked for me. Thanks. `image_64_encode = base64.urlsafe_b64encode(image_read)` `img = tf.io.decode_base64(image_64_encode)` `img = tf.image.decode_jpeg(img, channels=3)`
score: 0
type: Comment

http://stackoverflow.com/comment/84793126
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48893335
type: Comment
has text: Question before I implement and play around with this (and then accept your answer): have you runtime tested this with some strings (350,000 @ 500 each)?

http://stackoverflow.com/a/48918394
upvote count: 1
type: Answer
downvote count: 0
score: 1
has body: You should at least provide your initial effort to solve your problem with your question, but how about this: def calculate_total(hours, rate): if hours &gt; 60: over_60 = hours - 60 else: over_60 = 0 if hours &gt; 40: over_40 = hours - 40 - over_60 else: over_40 = 0 under_40 = hours - over_60 - over_40 return under_40 * rate + over_40 * rate * 1.5 + over_60 * rate * 2 You may the call this function using: calculate_total(75, 12)
answers question: http://stackoverflow.com/q/48918303

http://stackoverflow.com/comment/84757308
type: QuestionComment
has text: that was a hint...
comment on: http://stackoverflow.com/q/48876573
score: 0
type: Comment

http://stackoverflow.com/a/48818732
has comment: http://stackoverflow.com/comment/84667968
accepted answer of: http://stackoverflow.com/q/48816961
upvote count: 4
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84668071
has body: One way to implement this task is to use an HtmlDelegate, in this case the line break will be given by &lt;br&gt;: import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class HTMLDelegate(QStyledItemDelegate): def paint(self, painter, option, index): opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) painter.save() doc = QTextDocument() doc.setHtml(opt.text) opt.text = ""; style = opt.widget.style() if opt.widget else QApplication.style() style.drawControl(QStyle.CE_ItemViewItem, opt, painter) painter.translate(opt.rect.left(), opt.rect.top()) clip = QRectF(0, 0, opt.rect.width(), opt.rect.height()) doc.drawContents(painter, clip) painter.restore() def sizeHint(self, option, index ): opt = QStyleOptionViewItem(option) self.initStyleOption(opt, index) doc = QTextDocument() doc.setHtml(opt.text); doc.setTextWidth(opt.rect.width()) return QSize(doc.idealWidth(), doc.size().height()) if __name__ == '__main__': app = QApplication(sys.argv) w = QTableView() model = QStandardItemModel(4, 6) delegate = HTMLDelegate() w.setItemDelegate(delegate) w.setModel(model) w.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) w.show() sys.exit(app.exec_())
score: 4
answers question: http://stackoverflow.com/q/48816961

http://stackoverflow.com/a/48953048
answers question: http://stackoverflow.com/q/48952933
score: 0
has comment: http://stackoverflow.com/comment/84916651
has comment: http://stackoverflow.com/comment/84917002
has body: Updated I believe what you want to do is loop through the contents of the data you retrieved and stored in the variable data. Given the code you provided in your question, you could do something like: # Assumes 'url' and 'data' exist per the code sample in your question for row in data: coin_Id = row["Id"] coin_Name = row["Name"] coin_Symbol = row["Symbol"] # ... coin_Status = row["Status"] coin_StatusMessage = row["StatusMessage"] coin_ListingStatus = row["ListingStatus"] # Assumes you grabbed values for all of the keys print "ID: " + str(coin_Id) + "\n" + "Name: " + str(coin_Name) + "Symbol: " + str(coin_Symbol) + "\n" + "Status: " + str(coin_Status) + "\n" + "Status Message: " + str(coin_StatusMessage)
type: Answer

http://stackoverflow.com/comment/84630289
comment on: http://stackoverflow.com/a/48813371
has text: So does this mean that the string actually looks like this? "B " A B with a lot of spaces in front of it?
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48944290
type: Question
has answer: http://stackoverflow.com/a/48944392
has comment: http://stackoverflow.com/comment/84895482
tagged with: python
tagged with: list
has answer: http://stackoverflow.com/a/48944630
has title: Creating csv file from list using python
downvote count: 1
answer count: 4
upvote count: 0
has answer: http://stackoverflow.com/a/48944398
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv
has body: I am new in python. I have a problem in creating a csv file from a list using python. I have a list like this: mylist = ['Steve, Male, 28 years, 170 cm, 60 kg', 'Anna, Female, 26 years, 163 cm, 55 kg', 'Joe, Male, 27 years, 174 cm, 63 kg'] I want to create a csv file from the list above by adding header and removing units in the numeric data value. What I want will be like this: +-----------+--------+-----+------+------+ | name | sex | age |height|weight| +-----------+--------+-----+------+------+ | Steve | Male | 28 | 170 | 60 | +-----------+--------+-----+------+------+ | Anna | Female | 26 | 163 | 55 | +-----------+--------+-----+------+------+ | Joe | Male | 27 | 174 | 63 | +-----------+--------+-----+------+------+ This is my code so far: with open('data.csv', 'w', newline='') as csvfile: header = ['name', 'sex', 'age', 'height', 'weight'] writers = csv.writer(csvfile, delimiter=',') writers.writerow(header) for row in mylist: writers.writerow([row]) I got stuck with the code.
has answer: http://stackoverflow.com/a/48944353
score: -1
favorite count: 0

http://stackoverflow.com/q/48829494
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48830245
tagged with: list
has title: Questions about simple python script
upvote count: 3
has body: I have a homework assignment, to write a simple grocery list, the is script should be able to: Accept user input of variables such as item_name, quantity, and cost of an item Using the information gathered from the user, create a dictionary entry and add it to a list called grocery_history Print out all the items entered in the following format: Variable → number name price item_total And finally output the grand total of the cost of all the items This is my code: grocery_item = {} grocery_history=[{}] stop = 'go' item_name = input("Item name:") quantity = input("Quantity purchased:") cost = input("Price per item:") grocery_history.append(item_name) grocery_history.append(quantity) grocery_history.append(cost) cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:") while cont != 'q': item_name = input("Item name:") quantity = input("Quantity purchased:") cost = input("Price per item:") cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:") grocery_history.append(item_name) grocery_history.append(quantity) grocery_history.append(cost) grand_total = [] number = grocery_history[quantity] price = grocery_history[cost] for grocery_history in grocery_item: item_total = int(number)*float(price) grand_total.append(item_total) print(grocery_history[number][name] + "@" [price]:.2f + "ea'.format(**grocery_item)") item_total = 0 print ("Grand total:" + str(grand_total)) at my number = grocery_history[quantity] price = grocery_history[cost]statement I get aKey Error 2`, and I'm not sure why, the keys should exist, but maybe they are not being added to the list properly. Any help would be greatly appreciated, if you need more details let me know and I will edit them in.
has answer: http://stackoverflow.com/a/48829951
has comment: http://stackoverflow.com/comment/84663536
has comment: http://stackoverflow.com/comment/84663479
downvote count: 0
type: UnansweredQuestion
type: Question
score: 3
favorite count: 0
answer count: 2

http://stackoverflow.com/a/48911822
answers question: http://stackoverflow.com/q/48911531
type: Answer
has body: Another way, using numpy.r_. loc = df.index.get_loc(row) print(df.loc[np.r_[loc:loc+2], :])
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/q/48875458
score: -15
favorite count: 0
has comment: http://stackoverflow.com/comment/84755734
tagged with: sortedlist
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I need to create a sorted list with billions of elements and then create a second list without duplicate elements containing the first letter of each element of the first list and the position of this element in the first list. #input "Alfa", "Bravo","Big","Bang","Charlie" #output "A",1, "B",2, "C",5
has title: I want to create a sorted list of nom duplicated
tagged with: list
tagged with: linked-list
has comment: http://stackoverflow.com/comment/114988802
tagged with: vb6
type: Question
downvote count: 17
has answer: http://stackoverflow.com/a/56735845
has comment: http://stackoverflow.com/comment/84755304
has answer: http://stackoverflow.com/a/49108120
has comment: http://stackoverflow.com/comment/84755005
answer count: 3
has answer: http://stackoverflow.com/a/60389415

http://stackoverflow.com/comment/84618328
type: AnswerComment
has text: An extension to a web app framework is not the right tool.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48807470

http://stackoverflow.com/comment/84840038
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48916625
type: Comment
has text: You should put `if (a*d - b*c == 0):` before `x = (e*d-b*f)/(a*d-b*c)`, or you'll get `ZeroDivisionError` exception

http://stackoverflow.com/comment/84883750
type: Comment
has text: thanks that explains... is it goofy idea to always use T and T.left instead of T.left ( may be to make sure T is not None ).
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48938373

http://stackoverflow.com/q/48962697
has answer: http://stackoverflow.com/a/48972997
tagged with: python
tagged with: artificial-intelligence
type: AnsweredQuestion
tagged with: chainer
tagged with: machine-learning
tagged with: logistic-regression
type: Question
score: 0
accepted answer: http://stackoverflow.com/a/48972997
has body: I created a simple Logistic Regression model using Python and Chainer but I am not fully satisfied with the end result. Therefore, I would like to get some help. One restriction: I would not like to interchange the implemented functionalities by already existing functionalities. I know that there are loss functions in Chainer which archieve almost the same, but a more complex model I am creating is using a custom loss function. The code is found here: https://gist.github.com/kmjjacobs/62fc96ece695b47af8d667b060a64559 I would like to keep the model code as clean as possible, but as you can see, the call method is a forward to the loss method and I suspect there is a cleaner way to invoke the loss method in the training loop. I thought that it would be cleaner if the call method outputs the prediction and there is a seperate loss method for computing the loss. What are your thoughts on this? I am also not sure on the converter function. Is there a better way to achieve the same result? Do you have any remarks or best practices for writing Chainer code? Thanks in advance!
has title: Chainer - Python - Logistic Regression
answer count: 1

http://stackoverflow.com/comment/84660934
has text: `groupby(["name", df.date.dt.year])` groups data points by, well, name and year. So every data point that has the same name and year will be grouped together before calculating the mean amount of snow. In my example, this results in four different groups: 1: "place1" in 2016, 2: "place2" in 2016, 3: "place1" in 2017, and 4: "place2" in 2017. You don't need to input every date in the record book, it will extract the year from your dates during grouping.
type: Comment
comment on: http://stackoverflow.com/a/48822721
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84777293
type: Comment
comment on: http://stackoverflow.com/a/48886166
type: AnswerComment
has text: Not my words, it is Raymond's. :-) He says Counter() is a better way to count things and I agree.
score: 0

http://stackoverflow.com/comment/84701054
has text: @AlanSTACK I'm trying to add extra space by using re.sub to separate the dash within bracket
score: 0
comment on: http://stackoverflow.com/q/48848594
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84916994
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48955051
has text: Thanks! Accessing them isn't a huge problem - my question was rather regarding whether I have to manually "walk" the entire object to replace things or if there's <something> out there that does it for me in one fell swoop.
score: 0

http://stackoverflow.com/a/48869774
downvote count: 0
has body: After some searching and testing, and based on various sources, this works for me. That's all I can say about the code quality. I'm posting it only because it might help someone. Don't hesitate to comment if you see a problem. from sqlalchemy.event import listen # initialization routine # app: this Flask application # db: the database, see the question db_collate = 'sk_SK.UTF-8' # Slovak language for example def load_extension(dbapi_conn, unused): dbapi_conn.enable_load_extension(True) dbapi_conn.load_extension('/path/to/libSqliteIcu.so') dbapi_conn.enable_load_extension(False) dbapi_conn.execute("SELECT icu_load_collation(?, 'ICU_EXT_1')", (db_collate,)) with app.app_context(): listen(db.engine, 'connect', load_extension) and usage: from sqlalchemy.sql.expression import collate ...query.order_by(collate(Table.column, 'ICU_EXT_1')) The name ICU_EXT_1 is fully arbitrary.
score: 7
has comment: http://stackoverflow.com/comment/84749245
answers question: http://stackoverflow.com/q/48851097
upvote count: 7
has comment: http://stackoverflow.com/comment/121939972
has comment: http://stackoverflow.com/comment/100420466
type: Answer

http://stackoverflow.com/q/48927680
answer count: 1
has body: I am getting Attribute error while trying to unpickle my object using joblib. Should I separately pickle my classes and then unpickle them? class LengthTransformer(TransformerMixin): def transform(self, X, **transform_params): length = pd.DataFrame(X.apply(lambda x: len(x))) return length def fit(self, X, y=None, **fit_params): return self pipeline = Pipeline([('features', FeatureUnion([ ('ngram_tf_idf', Pipeline([ ('vect', CountVectorizer()), ('tfidf', TfidfTransformer()) ])), ('length',LengthTransformer()) ])), ('clf', clf),]) vectorizer_name = 'fpath'+name joblib.dump(pipeline.steps[0][1],vectorizer_name+'_vect_'+str(int(accuracy*100)) +'.pkl') Loading the pickled files here vect_file = "MultinomialNB_vect_80.pkl" vect = joblib.load(vect_file) I get the following error. I believe it is because it doesn't pickle my classes. I read the pickle can be used to serialize the classes but I am using joblib for better performance. AttributeError Traceback (most recent call last) &lt;ipython-input-4-a5d89ba85002&gt; in &lt;module&gt;() 4 vect_file = "MultinomialNB_vect_80.pkl" ----&gt; 5 vect_n = joblib.load(vect_file) 6 print(vect_n) 7 # tfid = vect_n.steps[1][1] ~/anaconda2/envs/py35/lib/python3.5/site-packages/sklearn/externals/joblib/numpy_pickle.py in load(filename, mmap_mode) 576 return load_compatibility(fobj) 577 --&gt; 578 obj = _unpickle(fobj, filename, mmap_mode) 579 580 return obj ~/anaconda2/envs/py35/lib/python3.5/site-packages/sklearn/externals/joblib/numpy_pickle.py in _unpickle(fobj, filename, mmap_mode) 506 obj = None 507 try: --&gt; 508 obj = unpickler.load() 509 if unpickler.compat_mode: 510 warnings.warn("The file '%s' has been generated with a " ~/anaconda2/envs/py35/lib/python3.5/pickle.py in load(self) 1041 raise EOFError 1042 assert isinstance(key, bytes_types) -&gt; 1043 dispatch[key[0]](self) 1044 except _Stop as stopinst: 1045 return stopinst.value ~/anaconda2/envs/py35/lib/python3.5/pickle.py in load_global(self) 1340 module = self.readline()[:…
type: UnansweredQuestion
tagged with: python
tagged with: joblib
has title: Joblib Unable to unpickle class properly
type: Question
score: 0
has answer: http://stackoverflow.com/a/48928379

http://stackoverflow.com/comment/84833584
type: Comment
score: 0
has text: @pault, yes, Jello's solution does exactly what I need (but at the cost of creating two additional arrays).
comment on: http://stackoverflow.com/q/48913014
type: QuestionComment

http://stackoverflow.com/comment/84861700
score: 0
has text: (i edit my post for example of dataset) i guess what i'm doing now is impossible because I couldn't separate target in 1 pipeline right?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48925311

http://stackoverflow.com/comment/84643321
type: AnswerComment
has text: Your question is: Shortest string between two characters. Hello is not the shortest string between `' '` and `(`. If you remove the `min` you will get all strings that match the criteria.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48819633

http://stackoverflow.com/comment/84895711
type: QuestionComment
has text: @LohmarASHAR the code is working. But my question if there is simpler or more directed way of doing so. I imported three libraries to implement one task, is it OK?
score: 0
comment on: http://stackoverflow.com/q/48938316
type: Comment

http://stackoverflow.com/a/48813636
has body: I'm not really sure what you're after, but you can pass anything you like to the form: class ScoreForm(forms.ModelForm): def __init__(self, questions, *args, **kwargs): super().__init__(*args, **kwargs) for num, question in questions.items(): self.fields.get('some_field').label = question #View def score(request): user = request.user questions = Question.objects.current_for_user(user) if: # ... else: form = ScoreForm(questions) return render(request,'MC/score.html',{'form': form})
answers question: http://stackoverflow.com/q/48813001
score: 0
has comment: http://stackoverflow.com/comment/84635870
type: Answer
has comment: http://stackoverflow.com/comment/84694869

http://stackoverflow.com/q/48957150
has answer: http://stackoverflow.com/a/48957202
answer count: 1
has title: The cause of differences of "for" loop between list and dictionary
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: dictionary
tagged with: list
has comment: http://stackoverflow.com/comment/84921448
has comment: http://stackoverflow.com/comment/84921361
has comment: http://stackoverflow.com/comment/84921367
tagged with: loops
upvote count: 1
has body: I've made a "for" loop of list. chosen_subjects = ['physics', 'maths', 'computer science', 'medicine'] for subjects in chosen_subjects: print(subjects.title()) I've made a "for" loop of dictionary chosen_subjects = {'sarah': 'physics', 'john': 'maths', 'denise': 'computer science', 'william': 'medicine'} for subjects in chosen_subjects.values(): print(subjects.title()) The outcome of these code are exactly identical. Physics Maths Computer Science Medicine Basically if you guys look at the "for" line of these two "for" loop of list and dictionary, the list of "for" loop DOESN"T NEED the parenthesis prior to colon while the dictionary of "for" loop NEED the parenthesis prior to colon. What are the programmatical reasons, and why did the python designer make such distinctive difference between list and dictionary when making "for" loop at first?
type: Question
score: -1

http://stackoverflow.com/a/48881405
answers question: http://stackoverflow.com/q/48875305
upvote count: 2
type: Answer
has body: I don't know what data from that page you are interested in. However, If the tabular data you are after then the below script is worth trying for: from selenium.webdriver import Chrome from contextlib import closing from selenium.webdriver.chrome.options import Options from bs4 import BeautifulSoup URL = "https://www.n2yo.com/passes/?s=39090&amp;a=1" chrome_options = Options() chrome_options.add_argument("--headless") with closing(Chrome(chrome_options=chrome_options)) as driver: driver.get(URL) soup = BeautifulSoup(driver.page_source, 'lxml') for items in soup.select("#passestable tr"): data = [item.text for item in items.select("th,td")] print(data) Partial output: ['Start ', 'Max altitude', 'End ', 'All passes'] ['Date, Local time', 'Az', 'Local time', 'Az', 'El', 'Local time', 'Mag ', 'Info'] ['20-Feb 19:17', 'N13°', '19:25', 'E76°', '81°', '19:32', 'S191°', '-', 'Map and details'] ['21-Feb 06:24', 'SSE151°', '06:31', 'E79°', '43°', '06:38', 'N358°', '-', 'Map and details']
score: 2
downvote count: 0

http://stackoverflow.com/q/48844384
type: Question
has body: I am trying to send messages between Amazon Deep Learning AMI instance, running somewhere, and an Ubuntu Virtual Box Machine running in my LAN. I have opened port 2019 for both TCP and UDP in my LAN. I have also enabled DMZ for my Ubuntu Virtual Machine IP, which I got running ifconfig. The virtual box machine is using "Bridge networking". I have disabled my firewalls and created rules for allowing connections in port 2019. However... When I run in my Ubuntu Virtual Box Machine (in my LAN): Servidor = sk.socket() Servidor.bind(('localhost', 2019)) print("Esperando al cliente...") Servidor.listen(1) a, b = Servidor.accept() print("Cliente aceptado. Arrancando el Juego") And this, in my Amazon Deep Learning Instance: Cliente = sk.socket() Cliente.connect(("MY_LAN_PUBLIC_IP", 2019)) print("Conectado al cliente") I get: socket.error: [Errno 111] Connection refused I have checked if my port is opened using this website http://canyouseeme.org/ and It says that the port is closed, but I don't understand why... CanYouSeeMe
score: 0
answer count: 1
has title: Messages between Virtual Box and an Amazon Instance - Python socket.error: Connection refused
tagged with: sockets
tagged with: port
tagged with: python
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48844511

http://stackoverflow.com/a/48930474
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48930217
has comment: http://stackoverflow.com/comment/84867720
has body: **### foo** Is actually well parsed and really means: ### foo It's not a Python or Markdown issue here, only a user that don't know how to format Markdown.. If you want to clean this you will have to parse user's input - but this is really not a Markdown question here, but a way more generic question that will surely requires some Regex. For Foo do ### Foo For Foo do **Foo**. Edit because of comments Ok, so you want to fix this specific case, here is how: import re string = '**### foo**' print(re.sub('\*{2}\#+([^*]+)\*{2}', '** \\1 **', string)) Output ** foo ** So, final function: def render_markdown(text): if not text: return '' text = re.sub('\*{2}\#+([^*]+)\*{2}', '** \\1 **', text) html = markdown.markdown(text, extensions=[ 'markdown.extensions.sane_lists', 'markdown.extensions.nl2br', ]) return bleach.clean(html, tags=[ 'p', 'h1', 'h2', 'br', 'h3', 'b', 'strong', 'u', 'i', 'em', 'hr', 'ul', 'ol', 'li', 'blockquote' ])
answers question: http://stackoverflow.com/q/48930217
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84867993
has comment: http://stackoverflow.com/comment/84867771
upvote count: 2

http://stackoverflow.com/comment/84713135
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48854578
type: Comment
has text: I thought I needed the `np.matrix` objects to perform matrix multiplication. If I recall correctly, I'm not performing any mathematical operations directly on whole `np.array` objects (not counting individually extracted elements). I believe I also used the `@` operator exclusively to multiply non-scalar objects together. Please let me know if the code provided fails to run as-is

http://stackoverflow.com/q/48853316
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/48854580
accepted answer: http://stackoverflow.com/a/48854580
has answer: http://stackoverflow.com/a/48853871
type: AnsweredQuestion
has title: run bash script over files that have not been converted
has body: I have a python script to convert json files to csv. It currently converts all files, but I want it to run only on those json files that have not been converted to csv already. All are in the same directory. How can I modify my code: #!/bin/bash # file: foo.sh for f in *.json; do python ~/bin/convert.py "$f" "-fcsv" done
tagged with: http://stackoverflow.com/tag/json
linked to: http://stackoverflow.com/q/18599711
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84710326
possible better answer: http://stackoverflow.com/a/48853871
score: 0
has comment: http://stackoverflow.com/comment/84711422
upvote count: 1
downvote count: 1
tagged with: shell
has comment: http://stackoverflow.com/comment/84710631
favorite count: 0
has comment: http://stackoverflow.com/comment/84710975

http://stackoverflow.com/q/48903574
accepted answer: http://stackoverflow.com/a/48907451
tagged with: python
favorite count: 0
tagged with: lambdify
upvote count: 2
tagged with: set-intersection
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84829251
score: 2
has comment: http://stackoverflow.com/comment/84848414
has answer: http://stackoverflow.com/a/48907451
type: Question
tagged with: sympy
answer count: 1
downvote count: 0
has body: I am inverting a function with the invert_real from sympy.solvers.solveset, because neither solve nor solveset can do it for some reason. The result is an Intersection and seems to be correct. I now want to use it for numeric calculations. When I try it with .subs it works fine, but when I try to lambdify I get NameError: name 'Intersection' is not defined I already found that I need to pass a source for Intersection in the modules= of lambdify. But I can't find a working source. Here is a code example: from sympy import * from sympy.solvers.solveset import invert_real x, y = symbols('x,y') expr = 1 - exp(-18000000*x) res_alg = invert_real(expr, y, x)[1] print("res_alg: ", res_alg) res_1 = res_alg.subs(y, 0.5) print("res_1: ", res_1) res = lambdify(y, res_alg, "numpy") print(res, res(0.5))
has title: How to lambdify an Intersection

http://stackoverflow.com/comment/84845097
score: 0
has text: Something in your data has an escape code that isn't handled. Find the record, find the problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48919374

http://stackoverflow.com/q/48807015
tagged with: char
answer count: 2
has comment: http://stackoverflow.com/comment/84616904
accepted answer: http://stackoverflow.com/a/48807119
has comment: http://stackoverflow.com/comment/84616738
downvote count: 0
has comment: http://stackoverflow.com/comment/84616949
tagged with: string
favorite count: 0
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/399078
tagged with: python
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48807115
has answer: http://stackoverflow.com/a/48807119
linked to: http://stackoverflow.com/q/280435
type: Question
possible better answer: http://stackoverflow.com/a/48807115
has comment: http://stackoverflow.com/comment/84617144
has comment: http://stackoverflow.com/comment/84616866
has title: Remove all slashes and backsleshes
has body: I have a string: res = 'qwer!@ 234234 4234gdf36/\////// // \ \\\$%^$% dsfg' and I want to remove ALL slashes and backslashes. I tried this: import string import re symbolsToRemove = string.punctuation res = 'qwer!@ 234234 4234gdf36/\////// // \ \\\$%^$% dsfg' res = re.sub(r'['+symbolsToRemove+']', ' ', res) print(res) But get the next result: qwer 234234 4234gdf36 \ \ \ dsfg What am I doing wrong?
duplicate of: http://stackoverflow.com/q/280435
score: 4
upvote count: 4

http://stackoverflow.com/comment/84745536
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48870489
type: QuestionComment
has text: are you trying to POST a list or GET a list?

http://stackoverflow.com/q/48822897
has comment: http://stackoverflow.com/comment/84732060
has title: pd.read_fwf() vs pd.read_table() giving discrepancies when reading a large file
has answer: http://stackoverflow.com/a/55987500
has comment: http://stackoverflow.com/comment/84649458
has comment: http://stackoverflow.com/comment/84649219
score: 0
answer count: 3
tagged with: file-io
tagged with: pandas
has body: df = pd.read_table("/media/jaideep/4F95-2DF2/test.txt", header = 11, delimiter = "|",encoding = "latin1", low_memory = False, comment = "#") produces a DataFrame of dimensions: [1100563 rows x 56 columns] while, df = pd.read_fwf("/media/jaideep/4F95-2DF2/test.txt", header = 11, delimiter = "|",encoding = "latin1",comment = "#") produces a DataFrame of dimensions: [1100654 rows x 10 columns] There is a difference of 100 rows that i need to account for using pd.read_table() as the input file is not a fixed width file -Please point me in the right direction with the possible reasons as to why pd.read_table() is skipping the 100 rows.Thanks!!
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84732506
has comment: http://stackoverflow.com/comment/84732313
has comment: http://stackoverflow.com/comment/84649223
has answer: http://stackoverflow.com/a/48823010
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84649443
has answer: http://stackoverflow.com/a/48864653
has comment: http://stackoverflow.com/comment/84649448
type: Question

http://stackoverflow.com/comment/84911632
type: Comment
comment on: http://stackoverflow.com/a/48906241
score: 0
type: AnswerComment
has text: Thanks for the nice answer. While being concise, it also eliminates the need for the intermediate array. Could you maybe elaborate a bit on how exactly the broadcast is working here. I did go through the documentation briefly, but am not totally clear with it. Also, what if even the result does not fit into memory, is there a solution for this?

http://stackoverflow.com/a/48896922
has body: Absolutely. 1) You can selectively download corpora like described at Programmatically install NLTK corpora / models, i.e. without the GUI downloader? For example, python -m nltk.downloader &lt;your package you would like to download&gt; 2) or using the GUI with instructions at http://www.nltk.org/data.html Which basically amounts to doing the following and command line python3 import nltk nltk.download()
type: Answer
accepted answer of: http://stackoverflow.com/q/48896682
downvote count: 0
answers question: http://stackoverflow.com/q/48896682
score: 1
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84799635
has comment: http://stackoverflow.com/comment/84799537

http://stackoverflow.com/q/48874898
score: 2
linked to: http://stackoverflow.com/q/33017274
downvote count: 2
tagged with: python
has body: I am working with a string of text that I want to search through and only find 4 letters words. It works, except it also finds 4+ letter words as well. import re test ="hello, how are you doing tonight?" total = len(re.findall(r'[a-zA-Z]{3}', text)) print (total) It finds 15, although I am not sure how it found that many. I thought I might have to use \b to pick the beginning and the end of the word, but that didn't seem to work for me.
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48874936
has answer: http://stackoverflow.com/a/48874985
type: Question
upvote count: 4
duplicate of: http://stackoverflow.com/q/3995034
possible better answer: http://stackoverflow.com/a/48874959
has answer: http://stackoverflow.com/a/48874959
favorite count: 0
duplicate of: http://stackoverflow.com/q/15863066
answer count: 3
has answer: http://stackoverflow.com/a/48874936
duplicate of: http://stackoverflow.com/q/33017274
tagged with: regex
has title: Python - regex - how to find ONLY four letter words?
has comment: http://stackoverflow.com/comment/84753780

transpose
tags question: http://stackoverflow.com/q/48960191
tag name: transpose
type: Tag

http://stackoverflow.com/a/48827663
has body: In the example you provided, there is no real point in using this syntax. There are cases though where creating an array or tuple to unpack it can be useful. # Python3 def print_n_times(n, string): # Instead of doing a loop we unpack an array of length n print(*n*(string,), sep='\n')
has comment: http://stackoverflow.com/comment/84659934
score: 2
answers question: http://stackoverflow.com/q/48827493
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48827493
type: AcceptedAnswer
type: Answer
downvote count: 0

http://stackoverflow.com/comment/84787899
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48842596
score: 0
has text: "I am working with circa 20GB" Can you give example dimensions for each of the arrays which will be given as input to the product?

http://stackoverflow.com/comment/84900610
type: AnswerComment
has text: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/165717/discussion-between-satendra-and-nurzhan-nogerbek).
type: Comment
comment on: http://stackoverflow.com/a/48946225
score: 0

http://stackoverflow.com/a/49287521
score: 1
answers question: http://stackoverflow.com/q/48910921
upvote count: 1
has body: You should be able to accomplish this with groupby. Here's your original DataFrame. I just named it df for convenience. df = pd.DataFrame({'AgentID': 0, 'CustomerID': 1, 'Date': ['2018-01-21', '2018-01-21', '2018-01-22', '2018-01-22'], 'Timestamp': ['2018-01-21 16:28:54', '2018-01-21 16:48:54', '2018-01-22 12:18:54', '2018-01-22 12:22:54'], 'Transcript_Line':['How can I help you?', 'I need help with this pandas problem...', 'Did you get that problem resolved?', 'Nope I still suck at pandas']}) I'm a little unclear about whether you need to sort on both AgentID and CustomerID or just one or the other, but hopefully you can see how to modify it. The initial sort guarantees that the Transcript_Line will be placed in order. groupby then finds the set of all claims for the same AgentID and CustomerID on the same day. The as_index=False, gives you the correct formatting of columns in the output. The output you want is combining the transcript lines, which you can accomplish with sum. df.sort_values(by=['AgentID', 'CustomerID', 'Timestamp']).groupby(['AgentID', 'CustomerID', 'Date'], as_index=False)['Transcript_Line'].sum() If you really need the '\n' characters between them, then you can get around this by first adding them to every single transcript line, doing the same groupby as above, and then removing the character at the end of the combined string. df['Transcript_Line'] = df['Transcript_Line'] + '\n' grouped = df.sort_values(by=['AgentID', 'CustomerID', 'Timestamp']).groupby(['AgentID', 'CustomerID', 'Date'], as_index=False)['Transcript_Line'].sum() grouped['Transcript_Line'] = grouped['Transcript_Line'].apply(lambda x: x[:-1]) resulting grouped dataframe
type: Answer
downvote count: 0

http://stackoverflow.com/q/48827207
has answer: http://stackoverflow.com/a/48827329
score: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48827294
possible better answer: http://stackoverflow.com/a/48827329
has title: Delete the repetition of a specific word in a row
linked to: http://stackoverflow.com/q/2823016
tagged with: char
tagged with: string
favorite count: 0
has body: For example I have a string: my_str = 'my example example string contains example some text' What I want to do - delete all duplicates of specific word (only if they goes in a row). Result: my example string contains example some text I tried next code: import re my_str = re.sub(' example +', ' example ', my_str) or my_str = re.sub('\[ example ]+', ' example ', my_str) But it doesn't work. I know there are a lot of questions about re, but I still can't implement them to my case correctly.
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84660402
has answer: http://stackoverflow.com/a/48827294
has comment: http://stackoverflow.com/comment/84658072
has answer: http://stackoverflow.com/a/48827337
tagged with: python
tagged with: regex
answer count: 4
has answer: http://stackoverflow.com/a/48827320
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84667813
has comment: http://stackoverflow.com/comment/84667818
upvote count: 2

http://stackoverflow.com/a/48929841
has comment: http://stackoverflow.com/comment/84892882
type: Answer
downvote count: 0
answers question: http://stackoverflow.com/q/48918137
has comment: http://stackoverflow.com/comment/84888353
score: 1
has body: It would be better to open your output file first, rather than keep on opening/closing it for each URL that you fetch. Exception handling is needed to catch cases where the URL does not exist. Also on your output, you should open the file with newline='' to avoid extra empty lines being written to the file: import csv import urllib.request from bs4 import BeautifulSoup write_header = True twiturl = "https://twitter.com/ACInvestorBlog" twitpage = urllib.request.urlopen(twiturl) soup = BeautifulSoup(twitpage,"html.parser") print(soup.title.text) tweets = [i.text for i in soup.select('a.twitter-cashtag.pretty-link.js-nav b')] print(tweets) url_base = "https://finviz.com/quote.ashx?t=" url_list = [url_base + tckr for tckr in tweets] with open('today.csv', 'w', newline='') as file: writer = csv.writer(file) for url in url_list: try: fpage = urllib.request.urlopen(url) fsoup = BeautifulSoup(fpage, 'html.parser') # write header row (once) if write_header: writer.writerow(map(lambda e : e.text, fsoup.find_all('td', {'class':'snapshot-td2-cp'}))) write_header = False # write body row writer.writerow(map(lambda e : e.text, fsoup.find_all('td', {'class':'snapshot-td2'}))) except urllib.error.HTTPError: print("{} - not found".format(url)) So today.csv would start like: Index,P/E,EPS (ttm),Insider Own,Shs Outstand,Perf Week,Market Cap,Forward P/E,EPS next Y,Insider Trans,Shs Float,Perf Month,Income,PEG,EPS next Q,Inst Own,Short Float,Perf Quarter,Sales,P/S,EPS this Y,Inst Trans,Short Ratio,Perf Half Y,Book/sh,P/B,EPS next Y,ROA,Target Price,Perf Year,Cash/sh,P/C,EPS next 5Y,ROE,52W Range,Perf YTD,Dividend,P/FCF,EPS past 5Y,ROI,52W High,Beta,Dividend %,Quick Ratio,Sales past 5Y,Gross Margin,52W Low,ATR,Employees,Current Ratio,Sales Q/Q,Oper. Margin,RSI (14),Volatility,Optionable,Debt/Eq,EPS Q/Q,Profit Margin,Rel Volume,Prev Close,Shortable,LT Debt/Eq,Earnings,Payout,Avg Volume,Price,Recom,SMA20,SMA50,SMA200,Volume,Change -,-,-10.85,4.60%,2.36M,11.00%,8.09M,-,-,-62.38%,1.95M,-16.1…
upvote count: 1

http://stackoverflow.com/q/48869150
accepted answer: http://stackoverflow.com/a/48870517
has comment: http://stackoverflow.com/comment/84741878
type: Question
has body: I am trying to simply filter based on the date in the Date_Start column and return a dataframe that includes the index, Full_Path and Date_Start columns. Seems like all examples I have found do not return the NaN and NaT I am receiving as seen below. On Pandas .22 and Python 2.7.13. In: FilesFrame Out: Full_Path Date_Start 0 \\file_path\file2018-02-12_20-47-01.txt 2018-02-12 20:47:01 1 \\file_path\file2018-02-12_20-47-01.txt 2018-02-12 20:47:01 2 \\file_path\file2018-02-12_20-47-01.txt 2018-02-12 20:47:01 3 \\file_path\file2018-02-15_20-47-05.txt 2018-02-15 20:47:05 In[2]: start_date = '2018-02-15 20:47:05' In[3]: condition1 = FilesFrame['Date_Start'] == start_date In[4]: FilesFrame[(condition1)] Out[4]: Full_Path Date_Start 0 NaN NaT 1 NaN NaT 2 NaN NaT 3 NaN 2018-02-15 20:47:05 Desired result: Full_Path 3 \\file_path\file2018-02-15_20-47-05.txt 2018-02-15 20:47:05 Additional Information: In[5]: FilesFrame.dtypes Out[5]: Full_Path object Date_Start datetime64[ns]
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84742265
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
has title: Pandas Dataframe but does not display filtered results. Filter Logic works, display shows NaT for filtered results
tagged with: python
has comment: http://stackoverflow.com/comment/84742124
score: 1
has answer: http://stackoverflow.com/a/48870517
upvote count: 1
type: AnsweredQuestion

http://stackoverflow.com/comment/84657238
score: 0
comment on: http://stackoverflow.com/q/48826813
type: Comment
type: QuestionComment
has text: And what does the oserror say?

http://stackoverflow.com/comment/84618732
comment on: http://stackoverflow.com/a/48807772
has text: I am thinking about your second question and hard question. I have no idea :(
type: AnswerComment
score: 0
type: Comment

kivy
tags question: http://stackoverflow.com/q/48808015
tags question: http://stackoverflow.com/q/48870673
tags question: http://stackoverflow.com/q/48813247
type: Tag
tags question: http://stackoverflow.com/q/48871327
tags question: http://stackoverflow.com/q/48812442
tags question: http://stackoverflow.com/q/48831544
tags question: http://stackoverflow.com/q/48875866
tags question: http://stackoverflow.com/q/48897275
tags question: http://stackoverflow.com/q/48855187
tags question: http://stackoverflow.com/q/48937745
tags question: http://stackoverflow.com/q/48885367
tags question: http://stackoverflow.com/q/48910863
tags question: http://stackoverflow.com/q/48848411
tags question: http://stackoverflow.com/q/48846786
tags question: http://stackoverflow.com/q/48827526
tags question: http://stackoverflow.com/q/48923550
tags question: http://stackoverflow.com/q/48870710
tags question: http://stackoverflow.com/q/48818978
tags question: http://stackoverflow.com/q/48812242
tag name: kivy
tags question: http://stackoverflow.com/q/48929950
tags question: http://stackoverflow.com/q/48830938
tags question: http://stackoverflow.com/q/48897833
tags question: http://stackoverflow.com/q/48875133
tags question: http://stackoverflow.com/q/48840912
tags question: http://stackoverflow.com/q/48950989
tags question: http://stackoverflow.com/q/48928276
tags question: http://stackoverflow.com/q/48810449
tags question: http://stackoverflow.com/q/48949227
tags question: http://stackoverflow.com/q/48842551
tags question: http://stackoverflow.com/q/48846671

http://stackoverflow.com/q/48837560
downvote count: 2
tagged with: file-writing
has comment: http://stackoverflow.com/comment/84679860
type: Question
has body: Is it possible to read and write simultaneously to the same file? I have this chunk of code: with open(total_f, 'w') as f: s= len(resu) #print s f.write ("the total number is {}\n".format(s)) f.write('\n'.join(map(str, resu))) with open(total_f ,'r') as f: content = f.read() count = content.count("FFFF") print count but I need them to be together, because I want to write the result of count in total_f. I tried to put in the read/write together like this: with open(total_f, 'rw') as f:# i want to read and write at the same time s= len(resu) content = f.read() count = content.count("FFFF") #print s f.write ("the total number is {}\n".format(s)) f.write ("the total number is {}\n".format(count)) f.write('\n'.join(map(str, resu))) But it's still not working, and so I'm not sure if that's correct.
answer count: 2
has comment: http://stackoverflow.com/comment/84679821
score: 4
favorite count: 0
has answer: http://stackoverflow.com/a/48837585
has title: reading and writing to the same file simultaneously in python
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/84679851
has answer: http://stackoverflow.com/a/48837791
has comment: http://stackoverflow.com/comment/84679835
type: UnansweredQuestion

http://stackoverflow.com/comment/84700984
score: 1
comment on: http://stackoverflow.com/a/48847846
type: AnswerComment
type: Comment
has text: Thanks, this gives ~5x speed-up compared to the loop.

http://stackoverflow.com/comment/84623615
type: Comment
comment on: http://stackoverflow.com/q/48809356
type: QuestionComment
has text: I think you're specifying the string 'tweet.user.screen_name' and not the value of that variable / part of the Tweet object. So you're telling the API, add someone called @tweet.user.screen_name to ListSlugName, and that user does not exist. You should also note that this is a problematic use of the API - the automation rules https://help.twitter.com/en/rules-and-policies/twitter-automation indicate that you should not be doing this as an automated process based on a Tweet search.
score: 0

http://stackoverflow.com/comment/84651665
type: AnswerComment
comment on: http://stackoverflow.com/a/48823211
type: Comment
has text: Please tell me what is the problem
score: 0

progress
tags question: http://stackoverflow.com/q/48854567
type: Tag
tag name: progress

http://stackoverflow.com/comment/84812123
has text: Then I would definitely recommend trying pyenv
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48903311
type: AnswerComment

http://stackoverflow.com/q/48871785
has comment: http://stackoverflow.com/comment/84747833
has comment: http://stackoverflow.com/comment/84747369
has comment: http://stackoverflow.com/comment/84747814
tagged with: python
has comment: http://stackoverflow.com/comment/84747301
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84747823
tagged with: list
has comment: http://stackoverflow.com/comment/84747646
has comment: http://stackoverflow.com/comment/84747332
has comment: http://stackoverflow.com/comment/84747868
has comment: http://stackoverflow.com/comment/84747595
has comment: http://stackoverflow.com/comment/84747259
has answer: http://stackoverflow.com/a/48872183
type: Question
accepted answer: http://stackoverflow.com/a/48872183
has comment: http://stackoverflow.com/comment/84748108
has comment: http://stackoverflow.com/comment/84747638
has body: I have a list of lists of different lengths. For example, A is a list of length 4, where A[0] has length 222, A[1] has length 261, A[2] has length 212 and A[3] has length 201. I want to create a new list of lists with same dimensions as A but with all entries initialised by 0s. How do I do this? Code: A=[[1,2,3,4], [5,6,7], [8,9,10,11,12], [13,14]] I want to have B which should look like the following. B=[[0,0,0,0],[0,0,0],[0,0,0,0,0],[0,0]] What I tried was: B= np.zeros_like(A) On printing B gives B=[0 0 0 0] How do I fix this? Apologies if the terminologies are not consistent with the example.
has answer: http://stackoverflow.com/a/48872301
tagged with: data-structures
has comment: http://stackoverflow.com/comment/84747782
score: 0
has comment: http://stackoverflow.com/comment/84747319
answer count: 2
possible better answer: http://stackoverflow.com/a/48872301
has title: How to initialize a list of lists of different sizes with all zeros
has comment: http://stackoverflow.com/comment/84747621
has comment: http://stackoverflow.com/comment/84747707
has comment: http://stackoverflow.com/comment/84747481
has comment: http://stackoverflow.com/comment/84747919
has comment: http://stackoverflow.com/comment/84748101
has comment: http://stackoverflow.com/comment/84747752
has comment: http://stackoverflow.com/comment/84747278

http://stackoverflow.com/comment/84845817
type: Comment
type: QuestionComment
has text: Is the C library _meant_ to be called from Python?
comment on: http://stackoverflow.com/q/48919761
score: 2

http://stackoverflow.com/a/48859544
type: AcceptedAnswer
has body: You need to use a custom formatter. Here's an example from the matplotlib docs: https://matplotlib.org/examples/pylab_examples/custom_ticker1.html I tend to use FuncFormatter as the example does. The main trick is that your function need to take to arguments x and pos. I honestly don't know what pos is for. Perhaps no even intentionally, but you can use FuncFormatter as a decorator, which is what I do below: %matplotlib inline import numpy as np import matplotlib.pyplot as plt @plt.FuncFormatter def fake_log(x, pos): 'The two args are the value and tick position' return r'$10^{%d}$' % (x) x=10**np.random.random(10000)*5 y=10**np.random.random(10000)*5 samps, xedges, yedges = np.histogram2d(np.log10(y), np.log10(x), bins=50) fig, (ax1) = plt.subplots() ax1.imshow(samps, extent=[0, 5, 0, 5]) ax1.xaxis.set_major_formatter(fake_log) ax1.yaxis.set_major_formatter(fake_log) ax1.set_xlabel('X') ax1.set_ylabel('Y')
downvote count: 0
has comment: http://stackoverflow.com/comment/84739992
answers question: http://stackoverflow.com/q/48858854
upvote count: 8
type: Answer
accepted answer of: http://stackoverflow.com/q/48858854
score: 8

http://stackoverflow.com/q/48933120
favorite count: 0
has answer: http://stackoverflow.com/a/48933625
has answer: http://stackoverflow.com/a/48933241
upvote count: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48933432
has answer: http://stackoverflow.com/a/48940145
type: Question
has body: New to Python here and I'm trying to learn/figure out the basics. I'm trying to read in a file in Python that has comma separated values, one to a line. Once read in, these values should be separated into two lists, one list containing the value before the "," on each line, and the other containing the value after it. I've played around with it for quite a while, but I just can't seem to get it. Here's what I have so far... with open ("mid.dat") as myfile: data = myfile.read().replace('\n',' ') print(data) list1 = [x.strip() for x in data.split(',')] print(list1) list2 = ? List 1 creates a list, but it's not correct. List 2, I'm not even sure how to tackle. PS - I have searched other similar threads on here, but none of them seem to address this properly. The file in question is not a CSV file, and needs to stay as a .dat file. Here's a sample of the data in the .dat file: 113.64,889987.226 119.64,440987774.55 330.43,446.21 Thanks.
score: 2
downvote count: 0
has title: Python - Read in Comma Separated File, Create Two lists
possible better answer: http://stackoverflow.com/a/48933267
has answer: http://stackoverflow.com/a/48933273
has answer: http://stackoverflow.com/a/48933267
has answer: http://stackoverflow.com/a/48933206
accepted answer: http://stackoverflow.com/a/48933432
answer count: 7
tagged with: python

http://stackoverflow.com/a/48929666
type: Answer
has comment: http://stackoverflow.com/comment/84873766
downvote count: 0
answers question: http://stackoverflow.com/q/48929508
has comment: http://stackoverflow.com/comment/84866325
has comment: http://stackoverflow.com/comment/84866153
accepted answer of: http://stackoverflow.com/q/48929508
score: 1
has comment: http://stackoverflow.com/comment/84874359
has body: This doesn't seem like a suitable case to use np.pad. As an alternative you can use append and repeat. In [48]: a, b = x.shape In [49]: np.append(x, np.repeat([[0],[1]], b, axis=1), axis=0) Out[49]: array([[ 0.2129145 , 0.68606654, 0.53354256, 0.19112299], [ 0.11836389, 0.71193408, 0.49222709, 0.60790186], [ 0. , 0. , 0. , 0. ], [ 1. , 1. , 1. , 1. ]]) If you want to use a variable for number of zero rows that you're inserting you can use np.zeros() with an inplace unpacking trick as follows: In [84]: np.append(x, np.repeat([*np.zeros(z_num)[:, None],[1]], b, axis=1), axis=0) # b is x.shape[1] Which z_num represents the number of zero rows. You can then simply change this variable based on the size of your input array. Example: In [84]: np.append(x, np.repeat([*np.zeros(0)[:, None],[1]], b, axis=1), axis=0) Out[84]: array([[ 0.38922514, 0.75096968, 0.71939798, 0.84233763], [ 0.8055875 , 0.29738511, 0.57563254, 0.45073955], [ 0.94241764, 0.27107424, 0.24536665, 0.60723426], [ 1. , 1. , 1. , 1. ]]) In [85]: In [85]: np.append(x, np.repeat([*np.zeros(3)[:, None],[1]], b, axis=1), axis=0) Out[85]: array([[ 0.38922514, 0.75096968, 0.71939798, 0.84233763], [ 0.8055875 , 0.29738511, 0.57563254, 0.45073955], [ 0.94241764, 0.27107424, 0.24536665, 0.60723426], [ 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. ], [ 0. , 0. , 0. , 0. ], [ 1. , 1. , 1. , 1. ]])
upvote count: 1
has comment: http://stackoverflow.com/comment/84868272
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84866605

http://stackoverflow.com/q/48849145
has title: Parsing and Iterating over URL List in Python
has body: website_list = [ 'https://www.zillow.com/62347390?location=Chicago%2N%23253', 'https://www.zillow.com/82983250?location=Boston%3B%53324', 'https://www.zillow.com/12917837?location=Miami%7K%26345', ] How does one create a python function (e.g. city_finder()) such that we get the following output when given website_list as input? &gt;&gt;&gt; city_finder(website_list) ['Chicago', 'Boston', 'Miami']
type: Question
has comment: http://stackoverflow.com/comment/84702002
has answer: http://stackoverflow.com/a/48849191
has answer: http://stackoverflow.com/a/48849206
score: 0
has answer: http://stackoverflow.com/a/48849932
type: UnansweredQuestion
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/48849320

http://stackoverflow.com/a/48876545
score: -1
has body: From https://github.com/nltk/nltk/issues/1783#issuecomment-317174189 The pos_tag() function is trained on Sections 00-18 of the Wall Street Journal sections of OntoNotes 5. From http://www.nltk.org/api/nltk.tag.html#module-nltk.tag It uses the Penn TreeBank tagset https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html To catch all adverbs, check for RB* tags. Using list comprehension, check the first 2 characters of the tag and check for the RB, e.g. &gt;&gt;&gt; from nltk import pos_tag, word_tokenize &gt;&gt;&gt; sent = "I am running quickly" &gt;&gt;&gt; [word for word, pos in pos_tag(word_tokenize(sent)) if pos.startswith('RB')] ['quickly'] To catch adjectives, check for the JJ* tags: &gt;&gt;&gt; sent = "I am running quickly" &gt;&gt;&gt; sent = "The big red cat is redder than apple" &gt;&gt;&gt; [word for word, pos in pos_tag(word_tokenize(sent)) if pos.startswith('JJ')] ['big', 'red', 'redder'] If you only check for JJ with JJ* (i.e. .startswith('JJ')), you'll miss the comparative and superlative adjectives: &gt;&gt;&gt; sent = "The big red cat is redder than apple, it's the best in the world" &gt;&gt;&gt; [word for word, pos in pos_tag(word_tokenize(sent)) if pos.startswith('JJ')] ['big', 'red', 'redder', 'best'] &gt;&gt;&gt; [word for word, pos in pos_tag(word_tokenize(sent)) if pos == 'JJ' ] ['big', 'red'] To remove simply use not: &gt;&gt;&gt; [word for word, pos in pos_tag(word_tokenize(sent)) if not pos.startswith('JJ')] ['The', 'cat', 'is', 'than', 'apple', ',', 'it', "'s", 'the', 'in', 'the', 'world']
downvote count: 1
upvote count: 0
answers question: http://stackoverflow.com/q/48872023
type: Answer

http://stackoverflow.com/comment/84791123
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48892694
type: Comment
has text: Research the knapsack problem. See what you find.

http://stackoverflow.com/q/48873044
tagged with: python
has answer: http://stackoverflow.com/a/62695676
tagged with: list
has answer: http://stackoverflow.com/a/48873486
downvote count: 0
has answer: http://stackoverflow.com/a/60775466
has body: I have a list of lists, and I want to return those sublists that have a specific char. If the list is: lst = [['a', 'e'], ['g', 'j'], ['m', 'n', 'w'], ['z']] I want to retrive ['g', 'j'] "or it's position" if I search using j or g
type: Question
answer count: 8
score: 5
has answer: http://stackoverflow.com/a/48873181
has comment: http://stackoverflow.com/comment/110902152
has answer: http://stackoverflow.com/a/49062738
has title: Search for a char in list of lists
has answer: http://stackoverflow.com/a/49063514
has answer: http://stackoverflow.com/a/61326942
favorite count: 0
has answer: http://stackoverflow.com/a/58728325
upvote count: 5
linked to: http://stackoverflow.com/q/2191699
type: UnansweredQuestion

http://stackoverflow.com/q/48963431
type: Question
has answer: http://stackoverflow.com/a/48963470
answer count: 3
upvote count: 0
linked to: http://stackoverflow.com/q/509211
favorite count: 0
tagged with: python-3.x
score: -3
tagged with: python
has answer: http://stackoverflow.com/a/48963478
has comment: http://stackoverflow.com/comment/84932678
has comment: http://stackoverflow.com/comment/84932668
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84932691
downvote count: 3
has answer: http://stackoverflow.com/a/48964121
has comment: http://stackoverflow.com/comment/84937925
has body: Use of string to print ? St="hello to all my friends in python" Print (St[1:3:-1]) IT print blank
has title: String use python to print?

http://stackoverflow.com/comment/84708967
type: Comment
type: QuestionComment
has text: That's the correct way to install using `pip` from a git url. What do you see if you run `python setup.py egg_info` in a checked out project directory?
comment on: http://stackoverflow.com/q/48852137
score: 0

http://stackoverflow.com/comment/84781882
comment on: http://stackoverflow.com/a/48874041
has text: in your_ping_device_fn def under ping_device, there is first "if not"condition. I see there is no else for it.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48979819
type: Answer
has body: Sometimes you can get an Internal Server Error 500. In other cases you can get what you got. There are a few things you can try: Remove Browser Cache. You can press Shift + Ctrl + Supr. Or reload without cache with Ctrl + F5 Remove Cookies. If you are using chrome or chromium you can delete the cookies stored for the domain you are using as you can see in the images: web.base.url Parameter. Activate deleloper mode. Go to Settings > Parameters > System Parameters and check that the parameter web.base.url is correctly set. This parameter is updated each time you log in with the Administrator user, the value of the url bar is assigned to the parameter. But if you can get it to work with the private mode I assume this is well assigned.
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/85254832
downvote count: 0
has comment: http://stackoverflow.com/comment/85259010
answers question: http://stackoverflow.com/q/48960514

http://stackoverflow.com/q/48963039
favorite count: 0
has body: I started working out some problems to master python asyncio module. What I wanted to create is a 'clock' which basically just prints out the time after program started in Hour:Minute:Second format. I thought of making three async_generators and looping over those three async_generators using a for loop in a seperate async method. Using builtin zip() method for this gives me the following error. TypeError: zip argument #1 must support iteration code : import asyncio second = 1 async def seconds(): while True: for i in range(1,61): await asyncio.sleep(second) yield i async def minutes(): while True: for i in range(1,61): await asyncio.sleep(60*second) yield i async def hours(): while True: for i in range(1,61): await asyncio.sleep(60*60*second) yield i async def clock(): for s,m,h in zip(seconds(),minutes(),hours()): print('{0}:H{1}:M{2}:S'.format(h,m,s)) if __name__ == '__main__': loop = asyncio.get_event_loop() loop.run_until_complete(clock()) My question is, doesn't async_genertator objects support iteration? When I checked, i could see that async_generator object hours() has ____aiter____ method. Isn't ____aiter____ iterable? What is wrong with the code I wrote.
type: Question
has title: looping over multiple async_generator objects together
tagged with: python
upvote count: 1
type: UnansweredQuestion
answer count: 0
downvote count: 0
score: 1
tagged with: asynchronous

http://stackoverflow.com/a/48853039
has comment: http://stackoverflow.com/comment/84714896
has comment: http://stackoverflow.com/comment/84818686
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48851993
answers question: http://stackoverflow.com/q/48851993
has body: No. Technically you just got a single message, which happens to quote all previous messages back to possibly the first one. This is the last message of the thread, and you returned it correctly. Incidentally, the GMail web interface (and other mail clients since then) hides the quotes by scraping for cues (typically, indentation or '>' signs). If you wish to isolate the real contents of the last message from the appended quotes, you'll have to do something similar by parsing and transforming your string.

http://stackoverflow.com/q/48953848
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48955832
tagged with: django
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48955832
downvote count: 0
score: 1
has body: I'm pretty new to Django, so please make it newbie friendly :D. Its about a simple todo-list. I want every item to have three Buttons for deleting, editing or in this case checking. In the following code I wanna create a check-button which sets a boolean value to True. But instand of doing anything the code is just refreshing the side. No error-messages or further information in the command. So can you guys spot the mistake? Glad for your help. HTML: {% csrf_token %} {{do.task_title}} url: urlpatterns = [ # match list, url(r'^$', views.index, name='index'), url(r'^add/$', views.addTodo, name='add'), url(r'^(?P<pk>[0-9]+)/complete/$', views.completeTodo, name='complete'), .. ] view: def completeTodo(request, todo_id): if request.method =='POST': print('alive') todo = Task.objects.get(pk=todo_id) todo.complete = True todo.save() return redirect('index') Model: class Task(models.Model): task_title = models.CharField(max_length=50) task_explain = models.CharField(max_length=1500) complete = models.BooleanField(default=False) def get_absolute_url(self): return reverse('todo:detail', kwargs={'pk':self.pk}) def __str__(self): return self.task_title
type: Question
has title: Django checkbutton for todo
upvote count: 1
answer count: 1

http://stackoverflow.com/q/48891613
type: AnsweredQuestion
tagged with: numbers
score: 1
tagged with: math
possible better answer: http://stackoverflow.com/a/48892241
has body: How can I find all the numbers in a text file? Then I need to find the average and median of the numbers as well. def main(): file = open("grades.txt","r") i = file.readlines() numbers = file.findall(r'[+-]?\d+(?:\.\d+)?') print (numbers) main() Text file: Joe,Sammy,75 Gayle,Ujifusa,95 Bella,Luna,65 Bob,Jones,0 Alex,Fink,10 Nathan,Bono,0 Bob,Bono,0 Edith,Bono,0 Susie,Que,84 Arnold,George,80 Linda,Beth,100 Output: Average of the grades and who has the lowest and highest grade.
has answer: http://stackoverflow.com/a/48892241
has comment: http://stackoverflow.com/comment/84788999
has comment: http://stackoverflow.com/comment/84789000
answer count: 2
tagged with: printing
has comment: http://stackoverflow.com/comment/84789107
accepted answer: http://stackoverflow.com/a/48891942
downvote count: 0
has title: Find numbers in text file and after that add them but see where the lowest number is as well
has comment: http://stackoverflow.com/comment/84788646
has comment: http://stackoverflow.com/comment/84789361
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84788671
has answer: http://stackoverflow.com/a/48891942
tagged with: file
upvote count: 1
has comment: http://stackoverflow.com/comment/84788844
type: Question

http://stackoverflow.com/a/52116638
has body: Let show just part of the code as I do. I add XGBRegressor because I think you may predict housing price class MultiColumn(BaseEstimator, TransformerMixin): def __init__(self,columns = None): self.columns = columns # array of column names to encode def fit(self,X,y=None): return self def transform(self, X): return X[self.columns] NUMERIC = df'var1', 'var2' CATEGORICAL = df'var3', 'var4' class Imputation(BaseEstimator, TransformerMixin): def transform(self, X, y=None, **fit_params): return X.fillna(NUMERIC.median()) def fit_transform(self, X, y=None, **fit_params): self.fit(X, y, **fit_params) return self.transform(X) def fit(self, X, y=None, **fit_params): return self class Cat(BaseEstimator, TransformerMixin): def transform(self, X, y=None, **fit_params): enc = DictVectorizer(sparse = False) encc = enc.fit(CATEGORICAL.T.to_dict().values()) enc_data = encc.transform(X.T.to_dict().values()) enc_data[np.isnan(enc_data)] = 1 return enc_data def fit_transform(self, X, y=None, **fit_params): self.fit(X, y, **fit_params) return self.transform(X) def fit(self, X, y=None, **fit_params): return self And Pipeline pipeline = Pipeline([ # Use FeatureUnion to combine the features ('union', FeatureUnion( transformer_list=[ # numeric ('numeric', Pipeline([ ('selector', MultiColumn(columns=['var1', 'var2'])), ('imp', Imputation()), ('scaling', preprocessing.StandardScaler(with_mean = 0.)) ])), # categorical ('categorical', Pipeline([ ('selector', MultiColumn(columns=['var3', 'var4'])), ('one_hot', Cat()), (CategoricalImputer()) ])), ])), ('model_fitting', xgb.XGBRegressor()), ])
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48909334

http://stackoverflow.com/comment/84772929
score: 0
type: Comment
type: QuestionComment
has text: could you provide some code as well? Did you try to blur / erode to get rid of the tiny white characters inside the big red boxes? and why are your boxes triangular shaped?
comment on: http://stackoverflow.com/q/48884177

http://stackoverflow.com/a/48907637
type: Answer
has comment: http://stackoverflow.com/comment/84823642
downvote count: 0
score: 1
has body: I'd fill the window every frame and then render and blit the current text. The texts can be stored in a list and the current text can be accessed with an index variable that you increment in the event loop. import pygame pygame.init() white = (255, 255, 255) black = (0, 0, 0) window = pygame.display.set_mode((640, 600)) clock = pygame.time.Clock() # A clock to limit the frame rate. font = pygame.font.Font(None, 57) # Use the default font. texts = ['Hello', "what's", 'up?'] text_index = 0 done = False while not done: # Handle events. for event in pygame.event.get(): # Allow the user to quit by clicking on the 'X' button. if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: if event.key in (pygame.K_KP_ENTER, pygame.K_RETURN): # Make sure that we don't get an IndexError. if text_index &lt; len(texts)-1: # Increment the index. text_index += 1 # Insert additional game logic here. # Finally draw everything. window.fill(white) # Use fill to clear the window. what_I_say = font.render(texts[text_index], True, black) window.blit(what_I_say, (10, 150)) pygame.display.flip() clock.tick(30) # Limit the frame rate to 30 FPS. If you really only need to update the window when the user wants to switch to the next page (an event occurs), you could also use pygame.event.wait instead of pygame.event.get.
has comment: http://stackoverflow.com/comment/84823969
upvote count: 1
answers question: http://stackoverflow.com/q/48898263
has comment: http://stackoverflow.com/comment/84858341

http://stackoverflow.com/a/49371711
type: Answer
has body: There are a few approaches you can try: Make sure you're running TensorFlow with GPU enabled, if you have a compatible graphics card in your machine. If you're running on the CPU, enable Intel's MKL for x86 speedups. You can find a lot more general advice on improving performance at https://www.tensorflow.org/performance/performance_guide
answers question: http://stackoverflow.com/q/48942740
score: 0

http://stackoverflow.com/q/48883106
accepted answer: http://stackoverflow.com/a/48883288
upvote count: 1
has answer: http://stackoverflow.com/a/48883266
has body: How can I vectorise a replace, by looking for a value in the row. For a dataframe as follows: df = pd.DataFrame([(1, 2, 3, 4, np.NaN, np.NaN, 4), (1, 2, 3, 0, 0, np.NaN, 0), (1, 2, 3, 4, 5, np.NaN, 5)], columns = ['P0', 'P1', 'P2', 'P3', 'P4', 'P5', 'Last_not_NaN_value'], index = ['row1', 'row2', 'row3']) Output df: P0 P1 P2 P3 P4 P5 Last_not_NaN_value row1 1 2 3 4 NaN NaN 4 row2 1 2 3 0 0.0 NaN 0 row3 1 2 3 4 5.0 NaN 5 How can I do something like df.replace(df['Last_not_NaN_value'], 0 ) &lt;- which does nothing. How can I look for where the last_not_NaN_value is in the df, and replace that with a 0, e.g.: P0 P1 P2 P3 P4 P5 Last_not_NaN_value row1 1 2 3 *0* NaN NaN 4 row2 1 2 3 0 *0* NaN 0 row3 1 2 3 4 *0* NaN 5
type: Question
has answer: http://stackoverflow.com/a/48883288
answer count: 2
tagged with: pandas
downvote count: 0
favorite count: 0
tagged with: python
possible better answer: http://stackoverflow.com/a/48883266
type: AnsweredQuestion
has title: Pandas replace column by value in row
score: 1

http://stackoverflow.com/a/48939082
type: Answer
has body: Since I don't see the importance of order of entry into the list, I'd rather get rid of the list and use a dictionary in stead. That way I wouldn't have to iterate through the list and search for existence of a 'hash-val'. And assuming the hash_values are unique, I would have the structure as follows: { "hashlist": { "QmVZATT8jWoCsNKzy2V3kwBrGXBjuKfifvrE" : { "description": "Test Video", "url": "" }, "QmVqpEomPZBgQ8dU8cpNezxZHG2oc3xQi61P2n" : { "description": "Cat Photo", "url": "" }, "QmYdWbq65R4CdFqWGYnPA7V12bX7hf2zxv64AG" : { "description": "Test Dir", "url": "" } } } That way, while inserting a new entry, I can easily query on the dictionary if the hash-value or simply the 'key' exists or not. Something like: if new_hash_val not in data["hashlist"]: #proceed with adding entry data["hashlist"][new_hash_val] = {"description":"..." , "url":"..."}
has comment: http://stackoverflow.com/comment/84886723
has comment: http://stackoverflow.com/comment/84993951
score: 1
accepted answer of: http://stackoverflow.com/q/48932965
answers question: http://stackoverflow.com/q/48932965
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84885750

http://stackoverflow.com/q/48891748
answer count: 1
downvote count: 0
has body: Please see the image below I am attempting to grab the information from column 1 and column 7 and combine them together. I have done this kind of operation before but as you notice in the image above some of the information form column 1 is spread out over several rows while the information on column 7 is separated line by line. How am I able to group the appropriate information together? so that the desired result is as follows: x = [('1900ISR', 0), ('2800', 8000, 0), ('2900ISR', 0, 0), ('3900ISR', 0), ('800BB', 0),('ACEAPP',0),('AIR120A',899),('AIRCMN', 59), ('APP',7800),('ASAMID', 5000, 0, 0, 0, 0), ('C4500', 36990),('C6000', 297000, 70000, 12000,0,0, 60000)] My attempt to do as such was as follows: df1 = pd.read_excel("EXCELFILENAME", parse_cols = "B") df2 = pd.read_excel("EXCELFILENAME", parse_cols = "H") df1 = df1.values.tolist() df2 = df2.values.tolist() a = list(zip(df1,df2)) print(a) However the above code is incorrect as it outputs a list zipped together of the desired columns but it does not account for the multiple lines associated with certain inputs in the first column. To be more specific see below: SNIPPET OF OUPUT [(['1900ISR'], [0.0]), (['2800'], [8000.0]), (['2900ISR'], [0.0]), (['3900ISR'], [0.0]), (['800BB'], [0.0]), (['ACEAPP'], [0.0]), (['AIR120A'], [0.0]), (['AIRCMN'], [0.0]), (['APP'], [899.0])] Here in the ouput the entry AIR120A should have the associated number 899 however it has the incorrect 0.0 from previous entries that were not associated to their corresponding entries. Is there a way to achieve my desired result?
has answer: http://stackoverflow.com/a/48892370
favorite count: 0
has title: Python, Parsing Column Data, pandas
tagged with: python
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/20110170
score: 1
upvote count: 1
tagged with: excel
type: Question
has comment: http://stackoverflow.com/comment/84789314
accepted answer: http://stackoverflow.com/a/48892370
linked to: http://stackoverflow.com/q/20110170
tagged with: pandas

web-scraping
tags question: http://stackoverflow.com/q/48867899
tags question: http://stackoverflow.com/q/48867072
tags question: http://stackoverflow.com/q/48837007
tags question: http://stackoverflow.com/q/48882651
tags question: http://stackoverflow.com/q/48846700
tags question: http://stackoverflow.com/q/48843260
tags question: http://stackoverflow.com/q/48958010
tags question: http://stackoverflow.com/q/48827688
tags question: http://stackoverflow.com/q/48876458
tags question: http://stackoverflow.com/q/48875911
tags question: http://stackoverflow.com/q/48813150
tags question: http://stackoverflow.com/q/48950800
tags question: http://stackoverflow.com/q/48902469
tags question: http://stackoverflow.com/q/48812532
tags question: http://stackoverflow.com/q/48867450
tags question: http://stackoverflow.com/q/48875416
tags question: http://stackoverflow.com/q/48898704
tags question: http://stackoverflow.com/q/48865341
tags question: http://stackoverflow.com/q/48842893
tags question: http://stackoverflow.com/q/48861078
tags question: http://stackoverflow.com/q/48841435
tags question: http://stackoverflow.com/q/48901352
tags question: http://stackoverflow.com/q/48931459
tags question: http://stackoverflow.com/q/48850675
tags question: http://stackoverflow.com/q/48948161
tags question: http://stackoverflow.com/q/48921315
tags question: http://stackoverflow.com/q/48938552
tags question: http://stackoverflow.com/q/48857871
tags question: http://stackoverflow.com/q/48878844
tags question: http://stackoverflow.com/q/48850545
tags question: http://stackoverflow.com/q/48820947
tags question: http://stackoverflow.com/q/48854663
tags question: http://stackoverflow.com/q/48918137
tags question: http://stackoverflow.com/q/48943528
tags question: http://stackoverflow.com/q/48929331
tags question: http://stackoverflow.com/q/48850130
tags question: http://stackoverflow.com/q/48875305
tags question: http://stackoverflow.com/q/48956443
tags question: http://stackoverflow.com/q/48858167
tags question: http://stackoverflow.com/q/48874341
tags question: http://stackoverflow.com/q/48849183
tags question: http://stackoverflow.com/q/48898460
tag name: web-scraping
tags question: http://stackoverflow.com/q/48821832
tags question: http://stackoverflow.com/q/48951527
tags question: http://stackoverflow.com/q/48902955
tags question: http://stackoverflow.com/q/48862653
tags question: http://stackoverflow.com/q/48856479
tags question: http://stackoverflow.com/q/48878292
tags question: http://stackoverflow.com/q/48814375
tags question: http://stackoverflow.com/q/48874874
tags question: http://stackoverflow.com/q/48884889
tags question: http://stackoverflow.com/q/48916262
tags question: http://stackoverflow.com/q/48881292
tags question: http://stackoverflow.com/q/48865627
type: Tag
tags question: http://stackoverflow.com/q/48805210
tags question: http://stackoverflow.com/q/48945567
tags question: http://stackoverflow.com/q/48919935
tags question: http://stackoverflow.com/q/48891574
tags question: http://stackoverflow.com/q/48818431
tags question: http://stackoverflow.com/q/48914936
tags question: http://stackoverflow.com/q/48913101
tags question: http://stackoverflow.com/q/48932995
tags question: http://stackoverflow.com/q/48899783
tags question: http://stackoverflow.com/q/48827311
tags question: http://stackoverflow.com/q/48939089
tags question: http://stackoverflow.com/q/48858223
tags question: http://stackoverflow.com/q/48865290
tags question: http://stackoverflow.com/q/48957805
tags question: http://stackoverflow.com/q/48842585
tags question: http://stackoverflow.com/q/48856969
tags question: http://stackoverflow.com/q/48961552
tags question: http://stackoverflow.com/q/48898896

http://stackoverflow.com/q/48809126
upvote count: 0
has answer: http://stackoverflow.com/a/48809532
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84621406
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/84621496
has comment: http://stackoverflow.com/comment/84621463
has comment: http://stackoverflow.com/comment/84621468
tagged with: http://stackoverflow.com/tag/json
downvote count: 3
type: Question
has comment: http://stackoverflow.com/comment/84621505
has comment: http://stackoverflow.com/comment/84621514
has title: Json.dump() does not have the expected output
has comment: http://stackoverflow.com/comment/84621450
has body: I have a set of results in python and I want to convert them into a JSON file, so I use json.dump(), as below: with open('pass_blocked.json','w') as outPassBlocked: json.dump(pass_blocked_results,outPassBlocked, indent=4) However, the file that is created does not have the JSON format that I expected.How can I create a correct JSON file ? The one I get is this: [ 683, { "nightly_result": null, "current_result": "PASS", "testrail_id": "12645" }, 2056, { "nightly_result": null, "current_result": "BLOCK", "testrail_id": "13200" }, 1033, { "nightly_result": null, "current_result": "BLOCK", "testrail_id": "9713" }, 1036, { "nightly_result": null, "current_result": "PASS", "testrail_id": "1016748" } ] Any ideas ?

http://stackoverflow.com/comment/84783644
comment on: http://stackoverflow.com/a/48889118
score: 0
type: AnswerComment
has text: In the `demo` app provided (https://github.com/sshwsfc/xadmin/tree/master/demo_app), the *demo app* is called `app` (and registered under settings as such). In my project, there are no apps called `apps`. Hope that makes sense.
type: Comment

http://stackoverflow.com/a/48961543
type: Answer
answers question: http://stackoverflow.com/q/48956892
score: 0
has body: If I understand correctly and you want these columns: Name ID Age Address Email You can do that using dictionaries, You make a dictionary for the first file, key being the ID and value being the row. Then you can see what Ids you need and rebuild each row as you want. import csv # Make a dictionary from the first file (id, row) f1 = open ("file1.csv") file1 = csv.reader(f1) file1RowDict = {} for row in file1: file1RowDict[row[1]] = row f1.close() # Make a list of all the Ids in the second file f2 = open ("file2.csv") file2 = csv.reader(f2) file2Ids = [] for row in file2: file2Ids.append(row[1]) f2.close() # Find Ids which are only on the first file ids = [id for id in file1RowDict.keys() if id not in file2Ids] newFileRows = [] # Grab the header row and reorder as you want headerRow = file1RowDict['ID'] headerRow = [headerRow[0], headerRow[1], headerRow[3], headerRow[2], headerRow[5]] newFileRows.append(headerRow) # Grab each data row and reorder as you want for id in ids: row = file1RowDict[id] newRow = [row[0], row[1], row[3], row[2], row[5]] newFileRows.append(newRow) print(str(newFileRows)) Outputs: [ ['Name', 'ID', 'Age', 'Address', 'Email'], ['John', '123', '32', 'New York', 'email@something.some'] ]

http://stackoverflow.com/comment/84839857
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48916479
has text: Want to print stuff in order to learn what is happening and later build more complicated builds. Python 2 is used by a team so can not just decide myself to change to 3.
score: 0

http://stackoverflow.com/comment/84879814
score: 0
type: QuestionComment
has text: Ah! I've found another mistake as well. Please look at my answer.
comment on: http://stackoverflow.com/q/48936182
type: Comment

http://stackoverflow.com/q/48849497
has body: I am now getting used to python lists. But I encountered a complicated list and I have troubles parsing it. prediction=[('__label__inflation_today', 0.8),('__label__economic_outlook', 0.2)] I am trying to present this prediction in a better way, something like excel. predicted label probability Inflation_today 0.8 Economic_outlook 0.2
tagged with: dataframe
type: AnsweredQuestion
downvote count: 0
has title: Two tuples as one element in python list
accepted answer: http://stackoverflow.com/a/48849517
favorite count: 0
possible better answer: http://stackoverflow.com/a/48849523
type: Question
tagged with: pandas
has answer: http://stackoverflow.com/a/48849523
score: 1
answer count: 2
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48849517

http://stackoverflow.com/q/48897025
answer count: 2
upvote count: 1
favorite count: 0
tagged with: pandas
has answer: http://stackoverflow.com/a/48897068
accepted answer: http://stackoverflow.com/a/48897068
tagged with: python
possible better answer: http://stackoverflow.com/a/48897112
type: AnsweredQuestion
has title: Pandas: Perform boolean tests with values from table1 on table2
downvote count: 0
type: Question
has body: I have a question on Pandas. I have table1 and table2 with the following values. table2 basically contains a set of random values for each "name": table1 = pd.DataFrame([{'name': 'A', 'value': 10}, {'name': 'B', 'value': 12}, {'name': 'C', 'value': 13}]) table2 = pd.DataFrame.from_dict({'name': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'], 'value': [np.random.randint(0,20), np.random.randint(0,30), np.random.randint(0,30), np.random.randint(0,20), np.random.randint(0,30), np.random.randint(0,30), np.random.randint(0,20), np.random.randint(0,30), np.random.randint(0,30), np.random.randint(0,20), np.random.randint(0,30), np.random.randint(0,30), np.random.randint(0,20), np.random.randint(0,30), np.random.randint(0,30), np.random.randint(0,20), np.random.randint(0,30), np.random.randint(0,30), np.random.randint(0,20), np.random.randint(0,30), np.random.randint(0,30)]}) I want to: Create a new column in table2 called "Greater/Less Than" Take each "name" from table1 and check the rows that contain the corresponding name in table2 Check whether the value of "A", "B", or "C" in each row in table2 is less or greater than the value of "A", "B", or "C" specified in table1. Return a string of "Less than" or "Greater than" in the new column in table2. This can be generalized to N number of columns in table1, not just a "name" column. I've googled high and low but I am only able to find basic boolean operators "e.g. table2[table2[value] &lt;= 100]" but not by using a range of values from another table. I'm new to Python. Any help would be appreciated! Thank you!
score: 1
has answer: http://stackoverflow.com/a/48897112
tagged with: numpy

formatting
tags question: http://stackoverflow.com/q/48824919
tags question: http://stackoverflow.com/q/48951639
tag name: formatting
tags question: http://stackoverflow.com/q/48820188
tags question: http://stackoverflow.com/q/48890632
tags question: http://stackoverflow.com/q/48903559
type: Tag
tags question: http://stackoverflow.com/q/48926576

http://stackoverflow.com/a/48852816
type: AcceptedAnswer
type: Answer
has body: The problem was fixed by displaying the image after the the for loop terminates # loop over the contours for c in cnts: print("1") # compute the center of the contour M = cv2.moments(c) cX = int(M["m10"] / M["m00"]) cY = int(M["m01"] / M["m00"]) # draw the contour and center of the shape on the image cv2.drawContours(image, [c], -1, (0, 255, 0), 2) cv2.circle(image, (cX, cY), 7, (229, 83, 0), -1) cv2.putText(image, "center", (cX - 20, cY - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 59, 174), 2) # show the image cv2.imshow("Image", image) #displaying processed image cv2.waitKey(0)
answers question: http://stackoverflow.com/q/48849870
accepted answer of: http://stackoverflow.com/q/48849870
score: 0

http://stackoverflow.com/q/48864027
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84731549
has comment: http://stackoverflow.com/comment/84731195
tagged with: unit-testing
has title: How do I patch the `pathlib.Path.exists()` method?
type: Question
has answer: http://stackoverflow.com/a/48864266
upvote count: 18
has body: I want to patch the exists() method of a pathlib.Path object for a unit test but I have problems getting this to work. What I am trying to do is this: from unittest.mock import patch from pathlib import Path def test_move_basic(): p = Path('~/test.py') with patch.object(p, 'exists') as mock_exists: mock_exists.return_value = True But it fails with: AttributeError: 'PosixPath' object attribute 'exists' is read-only. Any ideas?
tagged with: mocking
accepted answer: http://stackoverflow.com/a/48864266
downvote count: 0
score: 18
answer count: 1
tagged with: pathlib
has comment: http://stackoverflow.com/comment/84731166
favorite count: 0

http://stackoverflow.com/comment/84764914
has text: Your solution is correct, however it appears my solution takes better advantage of the jumps because it does the last move by jumping rather than stepping (not that it matters for small values), If I didn't miss anything.
type: AnswerComment
comment on: http://stackoverflow.com/a/48880330
score: 0
type: Comment

http://stackoverflow.com/comment/84851387
comment on: http://stackoverflow.com/q/48911885
score: 0
type: Comment
type: QuestionComment
has text: @PiyushDoke Could you show me how do you copy that OS disk?

http://stackoverflow.com/a/48828726
downvote count: 0
type: Answer
upvote count: 2
has body: If you want a pure pandas solution: df.set_index([df.index % 3, df.index // 3])\ .unstack()\ .sort_index(level=1, axis=1)\ .set_axis(list('abcdefgh'), axis=1, inplace=False) Output: a b c d e f g h 0 0 1 2 3 12 13 14 15 1 4 5 6 7 16 17 18 19 2 8 9 10 11 20 21 22 23
score: 2
answers question: http://stackoverflow.com/q/48828484

http://stackoverflow.com/comment/84690768
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48824217
type: Comment
has text: I came up with a hack to solve my narrow problem (see below), but I'm accepting your answer because it's probably more generally applicable.

http://stackoverflow.com/comment/84702289
type: QuestionComment
has text: The meaning of this return expression is context-dependent. Please show the entire class containing this code. Or at least the relevant parts of the class.
score: 3
comment on: http://stackoverflow.com/q/48849274
type: Comment

http://stackoverflow.com/q/48930234
tagged with: function
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48930287
tagged with: matrix
has comment: http://stackoverflow.com/comment/84867256
score: 1
favorite count: 0
has title: python: list index out of range in matrix multiplication
type: Question
upvote count: 2
has comment: http://stackoverflow.com/comment/84867380
tagged with: python
has body: i'm new to python,so i'm sorry if this is a silly question. This is a legit program for matrix multiplication but i don't understand why it's throwing the error list index out of range for my input? def matmult(a,b): product=[[0 for i in range(len(a))] for j in range(len(b[0]))] for i in range(len(a)): for j in range(len(b[0])): for k in range(len(b)): product[i][j]+=a[i][k]*b[k][j] return product matmult([[1,1]],[[3,4],[5,6]])
has comment: http://stackoverflow.com/comment/84868571
tagged with: list
answer count: 1
downvote count: 1
tagged with: matrix-multiplication
has comment: http://stackoverflow.com/comment/84868815

http://stackoverflow.com/comment/84660665
has text: The file that i am trying to send is a simpe notepad file .txt around 2KB in size. The file contains the texts "Hello World"
comment on: http://stackoverflow.com/q/48828414
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84633449
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48813703
type: AnswerComment
has text: @ArvinthKumar yw :-)

http://stackoverflow.com/q/48912598
favorite count: 0
tagged with: python
answer count: 4
type: AnsweredQuestion
upvote count: 3
has body: I have a dataframe with NaN. I have to remove nan at the starting rows only, and wants to keeps NaN after real number starts: Suppose my data frame is something like: a = pd.DataFrame({'data':[np.nan,np.nan,np.nan,np.nan,4,5,6,2,np.nan,1,3,4,5,np.nan,4,5,np.nan,np.nan]}) a= data 0 NaN 1 NaN 2 NaN 3 NaN 4 4.0 5 5.0 6 6.0 7 2.0 8 NaN 9 1.0 10 3.0 11 4.0 12 5.0 13 NaN 14 4.0 15 5.0 16 NaN 17 NaN and I tried to remove NaN at the beginning and wants data-frame like this: data 4 4.0 5 5.0 6 6.0 7 2.0 8 NaN 9 1.0 10 3.0 11 4.0 12 5.0 13 NaN 14 4.0 15 5.0 16 NaN 17 NaN I tried to use this function but it is not working. for w in np.arange(len(a)): if a.iloc[w] == np.nan: a.drop(a.index[w])
has answer: http://stackoverflow.com/a/48912686
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48912884
has title: How to remove NaN from the columns
possible better answer: http://stackoverflow.com/a/48912686
tagged with: dataframe
has answer: http://stackoverflow.com/a/48913177
tagged with: pandas
score: 3
downvote count: 0
has answer: http://stackoverflow.com/a/48912699
accepted answer: http://stackoverflow.com/a/48912884

http://stackoverflow.com/a/48822950
has comment: http://stackoverflow.com/comment/84651867
has body: You can use the screen command, it works perfectly. Here is a very good link: https://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/
accepted answer of: http://stackoverflow.com/q/48822903
answers question: http://stackoverflow.com/q/48822903
upvote count: 3
type: AcceptedAnswer
downvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/84652587
score: 2

http://stackoverflow.com/comment/84674218
score: 0
type: QuestionComment
type: Comment
has text: I would start by googling the term "network centrality". There are lots ways to calculate different types of 'centrality', and probably a few of them are well-suited for what you're after.
comment on: http://stackoverflow.com/q/48831178

http://stackoverflow.com/comment/84867326
type: Comment
comment on: http://stackoverflow.com/a/48929301
has text: I am using python 3.6... still now working, after searching it looks like this solution is valid for python 2.7
type: AnswerComment
score: 0

http://stackoverflow.com/comment/85026323
has text: https://github.com/Microsoft/PTVS/issues/1847
score: 1
comment on: http://stackoverflow.com/q/48837554
type: Comment
type: QuestionComment

timer
tag name: timer
type: Tag
tags question: http://stackoverflow.com/q/48849577
tags question: http://stackoverflow.com/q/48905051

http://stackoverflow.com/a/48965682
answers question: http://stackoverflow.com/q/48812532
type: AcceptedAnswer
downvote count: 0
has body: This will help you log in. import platform import time from selenium import webdriver if platform.system() == 'Windows': PHANTOMJS_PATH = './phantomjs.exe' else: PHANTOMJS_PATH = './phantomjs' browser = webdriver.PhantomJS(PHANTOMJS_PATH) browser.set_window_size(1366, 768) browser.get("http://210.212.227.210/tkmce/index.aspx") browser.find_element_by_id("txtUserName").send_keys('170907') browser.find_element_by_id("txtPassword").send_keys('Caffeine@9') browser.find_element_by_id("btnLogin").click() time.sleep(5) html = browser.page_source if 'Welcome' in html: print("You're logged in!") else: print("Logging in failed. Perhaps, it was attempted with invalid credentials")
type: Answer
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48812532

http://stackoverflow.com/q/48946639
favorite count: 0
tagged with: jupyter-notebook
tagged with: terminal
has answer: http://stackoverflow.com/a/49033240
type: UnansweredQuestion
score: 58
has answer: http://stackoverflow.com/a/49096180
upvote count: 58
tagged with: python
has title: How to create and open a jupyter notebook ipynb file directly from terminal
has answer: http://stackoverflow.com/a/49119289
type: Question
has answer: http://stackoverflow.com/a/66965087
has answer: http://stackoverflow.com/a/78052316
has body: The command jupyter notebook will open the Jupyter directory tree page where you can create a ipynb file. Is there a way to skip that page and create and open the ipynb file directly on the browser? I was thinking something like jupyter notebook mynotebook.ipynb
has answer: http://stackoverflow.com/a/66428535
downvote count: 0
answer count: 7
has answer: http://stackoverflow.com/a/49106773

sqlalchemy
tags question: http://stackoverflow.com/q/48870227
tags question: http://stackoverflow.com/q/48939280
tags question: http://stackoverflow.com/q/48937154
tags question: http://stackoverflow.com/q/48951285
tags question: http://stackoverflow.com/q/48956316
tags question: http://stackoverflow.com/q/48886544
tags question: http://stackoverflow.com/q/48958612
tags question: http://stackoverflow.com/q/48926700
tags question: http://stackoverflow.com/q/48924834
tags question: http://stackoverflow.com/q/48846288
tags question: http://stackoverflow.com/q/48863734
tags question: http://stackoverflow.com/q/48946375
tags question: http://stackoverflow.com/q/48875419
tags question: http://stackoverflow.com/q/48944129
tags question: http://stackoverflow.com/q/48806710
tags question: http://stackoverflow.com/q/48951981
tags question: http://stackoverflow.com/q/48845022
tags question: http://stackoverflow.com/q/48851583
tags question: http://stackoverflow.com/q/48852513
tags question: http://stackoverflow.com/q/48946552
tags question: http://stackoverflow.com/q/48811239
tag name: sqlalchemy
tags question: http://stackoverflow.com/q/48839482
tags question: http://stackoverflow.com/q/48867212
tags question: http://stackoverflow.com/q/48894905
tags question: http://stackoverflow.com/q/48812971
tags question: http://stackoverflow.com/q/48819296
tags question: http://stackoverflow.com/q/48889473
tags question: http://stackoverflow.com/q/48874745
tags question: http://stackoverflow.com/q/48887007
tags question: http://stackoverflow.com/q/48817093
tags question: http://stackoverflow.com/q/48875086
tags question: http://stackoverflow.com/q/48937178
tags question: http://stackoverflow.com/q/48841505
tags question: http://stackoverflow.com/q/48901925
tags question: http://stackoverflow.com/q/48805333
tags question: http://stackoverflow.com/q/48837063
tags question: http://stackoverflow.com/q/48881691
tags question: http://stackoverflow.com/q/48932290
tags question: http://stackoverflow.com/q/48858449
tags question: http://stackoverflow.com/q/48872596
tags question: http://stackoverflow.com/q/48851097
tags question: http://stackoverflow.com/q/48913195
tags question: http://stackoverflow.com/q/48818884
type: Tag

http://stackoverflow.com/q/48911135
has title: Gtk-ERROR in Python
answer count: 2
upvote count: 1
has body: I tried to install this tool called pycontact from Pycontact today at my Uni's server, but after installation, it's fetching me this error: /usr/local/lib/python2.7/dist-packages/matplotlib-2.2.0rc1-py2.7-linux-x86_64.egg/matplotlib/backends/backend_gtk3.py:32: DeprecationWarning: Gdk.Cursor.new is deprecated cursors.MOVE : Gdk.Cursor.new(Gdk.CursorType.FLEUR), (pycontact:3296): Gtk-ERROR **: GTK+ 2.x symbols detected. Using GTK+ 2.x and GTK+ 3 in the same process is not supported Trace/breakpoint trap (core dumped) It seeems like there is an issue with Nvidia's graphics card or sort of. Is there any way we can sort out this problem
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48912308
has answer: http://stackoverflow.com/a/48924081
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
tagged with: gtk

http://stackoverflow.com/a/48839011
type: AcceptedAnswer
type: Answer
has body: As per the HTML you have shared I strongly believe the Locator Strategy find_element_by_xpath("span[@class='someId']") is too broad to identify an element uniquely. You may require to take help of a Locator Strategy which identifies the WebElement uniquely. For that you have to traverse the HTML DOM a bit up to construct a Locator which uniquely identifies the element. With the current HTML you have shared, to search for the text and print it you can use the following line of code : print(driver.find_element_by_xpath("span[@class='someId']").get_attribute("innerHTML"))
accepted answer of: http://stackoverflow.com/q/48838945
answers question: http://stackoverflow.com/q/48838945
score: 0

http://stackoverflow.com/a/48811041
has body: How can I make the frame &amp; image stay a consistent width &amp; height (320x180)? If you want the frame to be a specific size, start by giving it a specific size. Next, either use place to add widgets to it, or turn geometry propagation off if using grid or pack # if using pack: self.frame_ImageContainer.pack_propagate(False) # if using grid: self.frame_ImageContainer.grid_propagate(False) How can I center the Take Screenshot button both vertically and horizontally inside the Image frame? The easiest way is to use place, since it won't affect the size of its master, and you can provide relative coordinates. self.button_TakeScreenshot.place(relx=.5, rely=.5, anchor="center")
type: Answer
upvote count: 1
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48809312

http://stackoverflow.com/comment/84776735
has text: This is an opinion-oriented question. You look pretty concise here. Some might suggest stacking operations on a single line (i.e. `my_range = sorted(range(97, 123).append(32))` but as you see, while that makes it shorter, it adds complexity and difficulty reading it.
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48885974
type: QuestionComment

http://stackoverflow.com/comment/84726225
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48861268
has text: It's funny because I thought the same thing. I tried writing out to a file instead of doing the print statements and still no luck.
score: 0

http://stackoverflow.com/q/48856372
answer count: 1
has answer: http://stackoverflow.com/a/48858655
favorite count: 0
has body: I am trying to get the google map embed url using selenium. I am able to click the share button and the page shows a modal with share url and an embed url. However i am un able to switch the dialog box. Here is my code browser.get('https://www.google.com/maps/place/%s?hl=en'%(code)) time.sleep(3) share_class = "ripple-container" buttons = browser.find_elements_by_class_name(share_class) for but in buttons: x = but.text if x == 'SHARE': but.click() modal = browser.switch_to.active_element share = modal.find_element_by_id("modal-dialog") print(share.text) here is the image.
has title: Python selenium select modal
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48858655
downvote count: 1
type: Question
upvote count: 0
score: -1

http://stackoverflow.com/q/48842326
has comment: http://stackoverflow.com/comment/84688727
tagged with: python
answer count: 0
type: UnansweredQuestion
has body: Working on the following problem: Given integers L and t, a string p of length k forms an (L,t)-clump inside a (larger) string s if there is a length L interval of s in which p appears at least t times. Appearances of p are allowed to overlap in the interval. I came up with the following solution: from collections import Counter def clumpFinding(s, k, L, t): c = Counter() res = set() for e in range(k, len(s)+1): b = e-L-1 if b &gt; -1: c[s[b:b+k]] -= 1 tmp = s[e-k:e] c[tmp] += 1 if c[tmp] &gt;= t: res.add(tmp) return res short explanation: say S = "0123456789", L=4, t = 3, c = {}, k = 2 at the start we would add "01", "12", "23" to the counter after that we remove the oldest element before adding a new one: c:{01} | "123456789" -&gt; c{01,12} | "23456789" -&gt; ... -&gt; "01" | c{12,23,34} | "456789" -&gt; "012" | c{23,34,45} | "56789" each time a string is added to the counter we check if the count is greater or equal to t if so we add it to the result set I would like to make this code run faster, but i'm unsure about what parts i should/can optimize.
has comment: http://stackoverflow.com/comment/84690152
tagged with: optimization
type: Question
score: 0
has title: Optimization of some Python code
tagged with: string

indexing
tags question: http://stackoverflow.com/q/48866806
tags question: http://stackoverflow.com/q/48940537
tags question: http://stackoverflow.com/q/48923991
tags question: http://stackoverflow.com/q/48911071
type: Tag
tags question: http://stackoverflow.com/q/48845435
tags question: http://stackoverflow.com/q/48876162
tags question: http://stackoverflow.com/q/48896900
tags question: http://stackoverflow.com/q/48818691
tags question: http://stackoverflow.com/q/48949193
tags question: http://stackoverflow.com/q/48896516
tags question: http://stackoverflow.com/q/48953845
tags question: http://stackoverflow.com/q/48899270
tags question: http://stackoverflow.com/q/48804909
tag name: indexing
tags question: http://stackoverflow.com/q/48876063
tags question: http://stackoverflow.com/q/48855841
tags question: http://stackoverflow.com/q/48938086
tags question: http://stackoverflow.com/q/48956623
tags question: http://stackoverflow.com/q/48897868
tags question: http://stackoverflow.com/q/48858600
tags question: http://stackoverflow.com/q/48835864
tags question: http://stackoverflow.com/q/48955521
tags question: http://stackoverflow.com/q/48807297

http://stackoverflow.com/q/48808149
possible better answer: http://stackoverflow.com/a/48808215
type: Question
score: 9
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84620073
has title: Paradoxical behaviour of math.nan when combined with the 'in' operator
has answer: http://stackoverflow.com/a/48808602
has body: I have the following lines of code: import math as mt ... ... ... if mt.isnan (coord0): print (111111, coord0, type (coord0), coord0 in (None, mt.nan)) print (222222, mt.nan, type (mt.nan), mt.nan in (None, mt.nan)) It prints: 111111 nan &lt;class 'float'&gt; False 222222 nan &lt;class 'float'&gt; True I am baffled... Any explanation? Python 3.6.0, Windows 10 I have a rock solid confidence in the quality of the Python interpreter... And I know, whenever it seems the computer makes a mistake, it's actually me being mistaken... So what am I missing? [EDIT] (In reaction to @COLDSPEED) Indeed the ID's are different: print (111111, coord0, type (coord0), id (coord0), coord0 in (None, mt.nan)) print (222222, mt.nan, type (mt.nan), id (mt.nan), mt.nan in (None, mt.nan)) Prints: 111111 nan &lt;class 'float'&gt; 2149940586968 False 222222 nan &lt;class 'float'&gt; 2151724423496 True Maybe there's a good reason whey nan isn't a true singleton. But I do not yet get it. This behavior is rather error prone in my view. [EDIT2] (In reaction to @Sven Marnach) Carefully reading the answer of @Sven Marnach makes it understandable to me. It is indeed a compromise of the kind one encounters when designing things. Still the ice is thin: Having a in (b,) return True if id (a) == id (b) seems to be at odds with the IEEE-754 standard that nan should be unequal to nan. The conclusion would have to be that while a is in an aggregate, at the same time it isn't, because the thing in the aggregate, namely b has to be considered unequal to a by IEEE standards. Think I'll use isnan from now on...
favorite count: 0
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48808215
upvote count: 9
accepted answer: http://stackoverflow.com/a/48808602
has comment: http://stackoverflow.com/comment/84619480

http://stackoverflow.com/comment/84636142
has text: must numpy be used to solve your problem? because something like `pandas`, which works alongside numpy, could handle this well.
comment on: http://stackoverflow.com/q/48816109
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48841706
possible better answer: http://stackoverflow.com/a/48850097
linked to: http://stackoverflow.com/q/7574759
has body: Hi guys I'm new to django, now I'm facing problem that the already loaded bootstrap css template gave no effect on the page. I have read several post of this problem in this site, but none of it work. I use python 3.6.4 and django 2.0. Here is my settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static"), ] settings.installed_apps : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rango' ] my index.html : {% load staticfiles %} Rango the command prompt said : [17/Feb/2018 20:06:14] "GET /static/css/bootstrap.css HTTP/1.1" 200 178152 When I copy paste all the bootastrap css style to the head it work When I call an image from same static folder, it also can show the picture My debug set True and i use virtual environment I also check on chrome developer tools>network>css. It said the css run My folder structure: tango | static | css | bootstrap.css Can anyone help me to solve this?
has title: django-why bootstrap already loaded but gave no effect on the page?
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/49000907
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/49000907
has answer: http://stackoverflow.com/a/48850097
has comment: http://stackoverflow.com/comment/84687765
has comment: http://stackoverflow.com/comment/84687958

http://stackoverflow.com/comment/84803880
comment on: http://stackoverflow.com/a/48899231
score: 0
type: Comment
has text: `number` was defined in the 5th line, please see the code again.
type: AnswerComment

yowsup
tags question: http://stackoverflow.com/q/48839474
tag name: yowsup
type: Tag

ply
tags question: http://stackoverflow.com/q/48813779
tag name: ply
type: Tag

http://stackoverflow.com/comment/84888805
has text: Thanks for the help
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48940848

http://stackoverflow.com/a/48878565
score: 2
has comment: http://stackoverflow.com/comment/84761536
accepted answer of: http://stackoverflow.com/q/48878482
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48878482
downvote count: 0
has body: You are running the command using ssh so it is running on the server. But you are trying to access on your local machine. But the project is not running on the local machine and hence it is not reachable on the browser using localhost ip(127.0.0.1). If you want to run on the server. You need to access like: http://server-ip:8000/
upvote count: 2
has comment: http://stackoverflow.com/comment/84761513
has comment: http://stackoverflow.com/comment/84761317
type: Answer

http://stackoverflow.com/a/48958454
score: 1
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48958379
type: Answer
answers question: http://stackoverflow.com/q/48958379
has body: That can be done with a comprehension, but it is a bit convoluted: Code: totd_list = [2] * 15 an_iter = iter(totd_list) sums = [sum((next(an_iter) for j in range(i+1))) for i in range(5)] print(sums) avg = [s / (i+1) for i, s in enumerate(sums)] print(avg) Results: [2, 4, 6, 8, 10] [2, 2, 2, 2, 2]
downvote count: 0
has comment: http://stackoverflow.com/comment/85133445

http://stackoverflow.com/q/48855998
type: Question
possible better answer: http://stackoverflow.com/a/62173400
tagged with: python
tagged with: knn
upvote count: 3
has comment: http://stackoverflow.com/comment/84716177
answer count: 2
accepted answer: http://stackoverflow.com/a/48856489
has body: When I use pd.crosstab to build confusion matrices, it keeps showing AssertionError: arrays and names must have the same length import pandas as pd import numpy as np from sklearn.metrics import confusion_matrix import random df = pd.read_csv('C:\\Users\\liukevin\\Desktop\\winequality-red.csv',sep=';', usecols=['fixed acidity','volatile acidity','citric acid','residual sugar','chlorides','free sulfur dioxide','total sulfur dioxide','density','pH','sulphates','alcohol','quality']) Q=[] for i in range(len(df)): if df['quality'][i]&lt;=5: Q.append('Low') else: Q.append('High') del df['quality'] test_number=sorted(random.sample(xrange(len(df)), int(len(df)*0.25))) train_number=[] temp=[] for i in range(len(df)): temp.append(i) train_number=list(set(temp)-set(test_number)) distance_all=[] for i in range(len(test_number)): distance_sep=[] for j in range(len(train_number)): distance=pow(df['fixed acidity'][test_number[i]]-df['fixed acidity'][train_number[j]],2)+\ pow(df['volatile acidity'][test_number[i]]-df['volatile acidity'][train_number[j]],2)+\ pow(df['citric acid'][test_number[i]]-df['citric acid'][train_number[j]],2)+\ pow(df['residual sugar'][test_number[i]]-df['residual sugar'][train_number[j]],2)+\ pow(df['chlorides'][test_number[i]]-df['chlorides'][train_number[j]],2)+\ pow(df['free sulfur dioxide'][test_number[i]]-df['free sulfur dioxide'][train_number[j]],2)+\ pow(df['total sulfur dioxide'][test_number[i]]-df['total sulfur dioxide'][train_number[j]],2)+\ pow(df['density'][test_number[i]]-df['density'][train_number[j]],2)+\ pow(df['pH'][test_number[i]]-df['pH'][train_number[j]],2)+\ pow(df['sulphates'][test_number[i]]-df['sulphates'][train_number[j]],2)+\ pow(df['alcohol'][test_number[i]]-df['alcohol'][train_number[j]],2) distance_sep.append(distance) distance_all.append(distance_sep) for round in range(5): K=2*round+1 select_neighbor_all=[] for i in range(len(test_number)): select_neighbor_sep=np.argsort(distance_all[i])[:K] select_neighbor_all.append(select_n…
has comment: http://stackoverflow.com/comment/84715559
has comment: http://stackoverflow.com/comment/84715948
has comment: http://stackoverflow.com/comment/84715544
tagged with: pandas
type: AnsweredQuestion
score: 3
has comment: http://stackoverflow.com/comment/84715966
downvote count: 0
has answer: http://stackoverflow.com/a/62173400
has answer: http://stackoverflow.com/a/48856489
favorite count: 0
has title: When I use pd.crosstab it keeps showing AssertionError

http://stackoverflow.com/q/48902562
has body: I have a pandas dataframe (df) where there are duplicating rows for some of the rows. Some columns in these repeating rows have NaN values while similar columns in the duplicated rows have values. I would like to merge the duplicating rows such that the missing values are replaced with the values from the duplicating rows and then dropping the duplicated rows. For examples the following are duplicated rows: id col1 col2 col3 0 01 abc 123 9 01 xy The result should be like: id col1 col2 col3 0 01 abc xy 123 I tried .combine_first by using df.iloc[0:1,].combine_first(df.iloc[9:10,]) but no success. Can anybody help me with this? Thanks!
tagged with: pandas
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48902598
type: AnsweredQuestion
score: 3
upvote count: 3
has title: .combine_first for merging multiple rows
type: Question
accepted answer: http://stackoverflow.com/a/48902598
downvote count: 0

http://stackoverflow.com/q/48958745
upvote count: 3
has comment: http://stackoverflow.com/comment/84952723
linked to: http://stackoverflow.com/q/32680081
type: Question
has title: import boto3 error on Mac OS
answer count: 2
tagged with: boto3
has comment: http://stackoverflow.com/comment/84952696
has answer: http://stackoverflow.com/a/54644215
has comment: http://stackoverflow.com/comment/84952945
has comment: http://stackoverflow.com/comment/84952895
downvote count: 0
has body: I'm trying to install boto3 on my mac (high sierra 10.13.3) and tried to follow : https://github.com/boto/boto3. I had already installed python 3 using homebrew before, but when I tried to see pip --version, I get error. So, I did 1) modify .bash_profile to add alias pip=pip3 2) verify $ pip --version pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6) 3) $ pip install boto3 Collecting boto3 Downloading boto3-1.5.36-py2.py3-none-any.whl (128kB) 100% |████████████████████████████████| 133kB 474kB/s Collecting botocore&lt;1.9.0,&gt;=1.8.50 (from boto3) Downloading botocore-1.8.50-py2.py3-none-any.whl (4.1MB) 100% |████████████████████████████████| 4.1MB 376kB/s Requirement already satisfied: s3transfer&lt;0.2.0,&gt;=0.1.10 in ./Library/Python/3.6/lib/python/site-packages (from boto3) Requirement already satisfied: jmespath&lt;1.0.0,&gt;=0.7.1 in ./Library/Python/3.6/lib/python/site-packages (from boto3) Requirement already satisfied: python-dateutil&lt;3.0.0,&gt;=2.1 in ./Library/Python/3.6/lib/python/site-packages (from botocore&lt;1.9.0,&gt;=1.8.50-&gt;boto3) Requirement already satisfied: docutils&gt;=0.10 in ./Library/Python/3.6/lib/python/site-packages (from botocore&lt;1.9.0,&gt;=1.8.50-&gt;boto3) Requirement already satisfied: six&gt;=1.5 in ./Library/Python/3.6/lib/python/site-packages (from python-dateutil&lt;3.0.0,&gt;=2.1-&gt;botocore&lt;1.9.0,&gt;=1.8.50-&gt;boto3) Installing collected packages: botocore, boto3 Found existing installation: botocore 1.8.20 Uninstalling botocore-1.8.20: Successfully uninstalled botocore-1.8.20 Successfully installed boto3-1.5.36 botocore-1.8.50 4) just to make sure this was fine, I ran $ pip3 install boto3 Requirement already satisfied: boto3 in /usr/local/lib/python3.6/site-packages Requirement already satisfied: jmespath&lt;1.0.0,&gt;=0.7.1 in /Users/ond983/Library/Python/3.6/lib/python/site-packages (from boto3) Requirement already satisfied: s3transfer&lt;0.2.0,&gt;=0.1.10 in /Users/ond983/Library/Python/3…
has answer: http://stackoverflow.com/a/77699294
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84930070
type: UnansweredQuestion
tagged with: aws-sdk
tagged with: pip
tagged with: python
has comment: http://stackoverflow.com/comment/84952775
score: 3

http://stackoverflow.com/comment/84686365
score: 1
comment on: http://stackoverflow.com/q/48841074
type: Comment
type: QuestionComment
has text: Please post your full STATIC_* settings. I suspect you are confused between STATIC_ROOT and STATIC_URL.

http://stackoverflow.com/q/48897947
has body: I am a newbie to django and djangocms , when i try to install djangocms's addon aldyrn_bootstrap3 ,my command is python manage.py migrate aldryn_bootstrap3 the following error shows es\aldryn_bootstrap3\models.py", line 26, in &lt;module&gt; from . import model_fields, constants File "C:\Users\shikw\AppData\Local\Programs\Python\Python36-32\lib\site- packages\aldryn_bootstrap3\model_fields.py", line 26, in &lt;module&gt; from . import fields, constants File "C:\Users\shikw\AppData\Local\Programs\Python\Python36-32\lib\site- packages\aldryn_bootstrap3\fields.py", line 8, in &lt;module&gt; from . import widgets, constants File "C:\Users\shikw\AppData\Local\Programs\Python\Python36-32\lib\site- packages\aldryn_bootstrap3\widgets.py", line 10, in &lt;module&gt; class ContextRenderer(django.forms.widgets.RadioFieldRenderer): AttributeError: module 'django.forms.widgets' has no attribute 'RadioFieldRender er' Django (1.11.10) django-cms (3.5.0) i seems that 'RadioFieldRender' has been removed. can somebody help me
upvote count: 2
has answer: http://stackoverflow.com/a/49424269
answer count: 2
has answer: http://stackoverflow.com/a/48898450
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 2
downvote count: 0
has title: why "django.forms.widgets has no attribute RadioFileRender" excetpion occured?
favorite count: 0
type: Question

http://stackoverflow.com/a/48904626
has body: The default User-Agent set by requests is 'User-Agent': 'python-requests/2.7.6'. Try to simulate as it is coming from a browser and not a script. Try simulating a User-Agent as follows: import requests url = "http://example.com/" headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36', 'Content-Type': 'text/html', } response = requests.get(url, headers=headers) html = response.text
answers question: http://stackoverflow.com/q/48904495
score: 0
type: Answer

http://stackoverflow.com/a/48838696
type: Answer
answers question: http://stackoverflow.com/q/48838613
score: 0
has body: You cannot import submodules from a package unless you list them within the __all__ list within the __init__.py file within your package. https://docs.python.org/3/tutorial/modules.html#importing-from-a-package At some point, you need to know the modules names. This could work for you, but it could have some unintended consequences.

http://stackoverflow.com/comment/84854379
type: QuestionComment
has text: of course it will enter it, `'United States of America'.lower() != 'usa'`
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48924007

http://stackoverflow.com/comment/84766732
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48880922
score: 1
has text: Get a GPU with more RAM, reduce the batch size, or train on CPU (with more RAM).

http://stackoverflow.com/a/48885918
type: Answer
accepted answer of: http://stackoverflow.com/q/48885281
answers question: http://stackoverflow.com/q/48885281
type: AcceptedAnswer
has body: So you need to save that information. there is no way around it. Either as a field on that model or a new one that only contains this information. for example. class VacationEdit(models.Model): user = models.ForeignKey(...) edited_year = models.IntegerField() and in your signal do for item in queryset: if VacationEdit.objects.filter(user=user, edited_year=current_year).exists(): continue item.calculconge = item.calculVacation + item.VacationDays VacationEdit.objects.create(...) item.save() But i would actually suggest to not edit old vacation data with new days but to make some kind of YearlyVacation-model and have one entry per year and just add new ones each year and save the old data.
score: 0

http://stackoverflow.com/q/48834100
score: 1
type: Question
tagged with: network-programming
has title: Convert IP in text file to Hostname
upvote count: 1
has body: I'm trying to get hostnames using IPs from text file, but I'm unable to read all IPs from text file and the output shows only one IP. Below is my COde, import os import socket with open('ips.txt', 'r') as f: for line in f.read().strip('\n'): ip = line.strip() b = socket.getfqdn(ip) print b Thanks.
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48834149

http://stackoverflow.com/q/48958072
tagged with: flask
linked to: http://stackoverflow.com/q/32214983
has title: Storing images through a Flask app. Images in Postgres or S3 filepaths in Postgres table?
tagged with: postgresql
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84923206
accepted answer: http://stackoverflow.com/a/48958197
downvote count: 1
type: AnsweredQuestion
duplicate of: http://stackoverflow.com/q/32214983
has body: I'm working on a flask backend app. There are some profile images coming in from the android frontend to the flask API endpoint. I want to store these images. Tech stack : Android app, Flask API/backend, Postgres, AWS services. What would be the best idea? I thought of the following ideas. Do let me know if any of these ideas make sense! Storing the images directly in the Postgres database. ( i think this is bad as it will put a load on the database). Storing the images in Amazon S3 buckets and S3 file paths as one of the values in the Postgres table. An improvement for 2 i thought would be - Have the arrangement like 2, and have a CDN such as Amazon Cloudfront for CDN and faster distribution to other services requesting the images. How does it sound? Any other ideas? Thanks! :)
tagged with: amazon-s3
has answer: http://stackoverflow.com/a/48958197
score: -1
type: Question
upvote count: 0
answer count: 1
tagged with: database-design

http://stackoverflow.com/q/48902627
tagged with: python
tagged with: regex
accepted answer: http://stackoverflow.com/a/48903082
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48902911
downvote count: 2
has comment: http://stackoverflow.com/comment/84810623
type: Question
tagged with: regex-greedy
upvote count: 0
score: -2
has body: My question is quite simple I'm trying to come up with a RE to select any set of words or statement in between two characters. For example is the strings are something like this : ') as whatever ' and it can also look like ') as whatever\r\n' So i need to extract 'whatever' from this string. The Regex I came up with is this : \)\sas\s(.*?)\s It works fine and extracts 'whatever' but this will only work for the first example not the second. What should i do in case of the second statement I'm basically looking for an OR condition kind of thing! Any help would be appreciated Thanks in advance
tagged with: sql-parser
has answer: http://stackoverflow.com/a/48903082
answer count: 2
has title: Python Regex matcher until two characters like a OR condition
favorite count: 0
has comment: http://stackoverflow.com/comment/84810549
has answer: http://stackoverflow.com/a/48902911

http://stackoverflow.com/a/48859661
type: Answer
has comment: http://stackoverflow.com/comment/84723086
has body: Django is resolving the convo_identification variable as a URL parameter, not part of the request object. The value is set as an argument when the views.py is referred by the urls.py. When you try to get the convo_identification from the request.GET dictionary, it doesn't exist so there is nothing to return with the get method. This will not cause an error but silently set a null value. To verify that there is no key in your request.GET dictionary that matches convo_identification you can print the contents of the request.GET dictionary: print(request.GET) Also the since the variable is initialized when the view is reference, there isn't really a need to re-declare the variable unless you are just changing the name.
has comment: http://stackoverflow.com/comment/84723051
has comment: http://stackoverflow.com/comment/84723136
upvote count: 1
has comment: http://stackoverflow.com/comment/84723053
has comment: http://stackoverflow.com/comment/84722921
score: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84722998
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48858610
answers question: http://stackoverflow.com/q/48858610
has comment: http://stackoverflow.com/comment/84723123

http://stackoverflow.com/comment/84700611
score: 0
type: Comment
has text: Once you've converted the string to json data, I find it can be helpful to pprint.pprint(json_data) to see the structure of the data.
comment on: http://stackoverflow.com/a/48848385
type: AnswerComment

http://stackoverflow.com/q/48849701
type: Question
tagged with: flask-migrate
has comment: http://stackoverflow.com/comment/84704596
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84703052
tagged with: flask
tagged with: flask-sqlalchemy
favorite count: 0
has comment: http://stackoverflow.com/comment/84703030
has title: Flask-Migration with one-to-many relationship
tagged with: python
has body: I have a working blog system. I want to add it to comment system. I completed migrations with post model with id, title and body. Now I add comments and create new model named Comment. When I run migrations: INFO [alembic.runtime.migration] Context impl MySQLImpl. INFO [alembic.runtime.migration] Will assume non-transactional DDL. INFO [alembic.env] No changes in schema detected. from run import db class Post(db.Model): __tablename__ = 'blog.post' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) body = db.Column(db.Text, nullable=False) comments = db.relationship('Comment', backref='blog.post') from run import db class Comment(db.Model): __tablename__ = 'blog.comment' id = db.Column(db.Integer, primary_key=True) body = db.Column(db.Text, nullable=False) post_id = db.Column(db.Integer, db.ForeignKey('blog.post.id'), nullable=False) I dont know what is wrong with my code. I get relationship from documentation and edit it. There aren't any comment table in db before. EDIT 1: I call comment inside run like below: from model.comment import Comment After that I can create migration but migration got error like below: sqlalchemy.exc.InternalError: (pymysql.err.InternalError) (1005, 'Can\'t create table blog_db.blog.comment (errno: 150 "Foreign key constraint is incorrectly formed")') [SQL: '\nCREATE TABLE blog.comment (\n\tid INTEGER NOT NULL AUTO_INCREMENT, \n\tname VARCHAR(255) NOT NULL, \n\tbody TEXT NOT NULL, \n\tcreated DATETIME DEFAULT now(), \n\tstatus INTEGER NOT NULL, \n\tpost_id INTEGER NOT NULL, \n\tPRIMARY KEY (id), \n\tFOREIGN KEY(post_id) REFERENCES blog.post (id)\n)\n\n'] (Background on this error at: http://sqlalche.me/e/2j85)
downvote count: 0
type: UnansweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48860850
tagged with: sqlalchemy-migrate

http://stackoverflow.com/q/48895582
type: UnansweredQuestion
tagged with: python
downvote count: 0
score: 1
has title: Calculate Color Between 2 RGB Values Based on Int Value Between 0-500
has body: I don't know if this is the right place to ask this, so if it is, good, if not, maybe I can be directed to the right place? Anyway, I am trying to take 2 user inputs that are RGB values in tuple form. Then, given an integer value between 0 and 500, I want to calculate an in-between RGB tuple. So, a much lower integer value would lead to an RGB tuple that is closer to the FIRST user-given RGB tuple, and a higher integer value would lead to a tuple closer to the SECOND user-given RGB tuple. That is, I want a final RGB tuple that falls somewhere in between the two user-given RGB tuples that varies based on the integer value in the 0-500 range. I CANNOT, however, seem to get my mind around the math/logic necessary to make this work! If this is the wrong place to ask, I apologize. Otherwise, thank you in advance!
has comment: http://stackoverflow.com/comment/84797709
type: Question
upvote count: 1
has comment: http://stackoverflow.com/comment/84796970
answer count: 1
favorite count: 0
tagged with: pygame
has answer: http://stackoverflow.com/a/48895661
tagged with: python-3.x

http://stackoverflow.com/comment/84830338
type: AnswerComment
comment on: http://stackoverflow.com/a/48910843
type: Comment
has text: "operator won't work with them if I make it "Buttons.operator" - I do understand why you can't reference `Buttons.operator` wherever you need it. Just add the import statement in each file that needs to reference it. Am I misunderstanding something?
score: 0

http://stackoverflow.com/comment/103904579
type: AnswerComment
type: Comment
has text: @Vaishali- Is there away to do this without transposing the data? Because, if the dataframe is huge then transposing takes a lot of time.
comment on: http://stackoverflow.com/a/48815267
score: 0

http://stackoverflow.com/comment/84688715
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48841371
has text: Or that is just another layer of obfuscation perhaps.

string
tags question: http://stackoverflow.com/q/48817141
tags question: http://stackoverflow.com/q/48876018
tags question: http://stackoverflow.com/q/48881196
tags question: http://stackoverflow.com/q/48910448
tags question: http://stackoverflow.com/q/48851337
tags question: http://stackoverflow.com/q/48932659
tags question: http://stackoverflow.com/q/48884926
tags question: http://stackoverflow.com/q/48914090
tags question: http://stackoverflow.com/q/48930609
tags question: http://stackoverflow.com/q/48928370
tags question: http://stackoverflow.com/q/48855841
tags question: http://stackoverflow.com/q/48919279
tags question: http://stackoverflow.com/q/48842639
tags question: http://stackoverflow.com/q/48807015
tags question: http://stackoverflow.com/q/48870253
tags question: http://stackoverflow.com/q/48907626
tags question: http://stackoverflow.com/q/48814581
tags question: http://stackoverflow.com/q/48918771
tags question: http://stackoverflow.com/q/48887424
tags question: http://stackoverflow.com/q/48825753
tags question: http://stackoverflow.com/q/48835481
tags question: http://stackoverflow.com/q/48828586
tags question: http://stackoverflow.com/q/48850339
tags question: http://stackoverflow.com/q/48813922
tags question: http://stackoverflow.com/q/48950695
tags question: http://stackoverflow.com/q/48933800
tags question: http://stackoverflow.com/q/48934246
tags question: http://stackoverflow.com/q/48841672
tags question: http://stackoverflow.com/q/48894093
tags question: http://stackoverflow.com/q/48946323
tags question: http://stackoverflow.com/q/48842326
tags question: http://stackoverflow.com/q/48877620
tag name: string
tags question: http://stackoverflow.com/q/48909036
tags question: http://stackoverflow.com/q/48874719
tags question: http://stackoverflow.com/q/48849632
tags question: http://stackoverflow.com/q/48958184
tags question: http://stackoverflow.com/q/48917405
tags question: http://stackoverflow.com/q/48881713
tags question: http://stackoverflow.com/q/48874786
tags question: http://stackoverflow.com/q/48948539
tags question: http://stackoverflow.com/q/48943640
tags question: http://stackoverflow.com/q/48862619
tags question: http://stackoverflow.com/q/48815921
type: Tag
tags question: http://stackoverflow.com/q/48826322
tags question: http://stackoverflow.com/q/48843876
tags question: http://stackoverflow.com/q/48827207
tags question: http://stackoverflow.com/q/48805069
tags question: http://stackoverflow.com/q/48953171
tags question: http://stackoverflow.com/q/48889465
tags question: http://stackoverflow.com/q/48858912
tags question: http://stackoverflow.com/q/48936188
tags question: http://stackoverflow.com/q/48923170
tags question: http://stackoverflow.com/q/48856504
tags question: http://stackoverflow.com/q/48917121
tags question: http://stackoverflow.com/q/48834842
tags question: http://stackoverflow.com/q/48934520
tags question: http://stackoverflow.com/q/48844953
tags question: http://stackoverflow.com/q/48898690
tags question: http://stackoverflow.com/q/48886359
tags question: http://stackoverflow.com/q/48903079
tags question: http://stackoverflow.com/q/48892414
tags question: http://stackoverflow.com/q/48897200
tags question: http://stackoverflow.com/q/48838701
tags question: http://stackoverflow.com/q/48952467
tags question: http://stackoverflow.com/q/48918639
tags question: http://stackoverflow.com/q/48855725
tags question: http://stackoverflow.com/q/48899041
tags question: http://stackoverflow.com/q/48924007
tags question: http://stackoverflow.com/q/48890397
tags question: http://stackoverflow.com/q/48927318
tags question: http://stackoverflow.com/q/48892831
tags question: http://stackoverflow.com/q/48888637
tags question: http://stackoverflow.com/q/48861824
tags question: http://stackoverflow.com/q/48953331
tags question: http://stackoverflow.com/q/48874708
tags question: http://stackoverflow.com/q/48917460
tags question: http://stackoverflow.com/q/48893256
tags question: http://stackoverflow.com/q/48885192

http://stackoverflow.com/q/48914098
has answer: http://stackoverflow.com/a/48914954
score: -1
has comment: http://stackoverflow.com/comment/84836296
has comment: http://stackoverflow.com/comment/84836210
tagged with: pyqt
has comment: http://stackoverflow.com/comment/84835543
answer count: 1
favorite count: 0
has body: I have a GUI class for the main window of my system. I have linked the button called "viewEvidenceButton" to a function called "openReportViewer" so that when the button is clicked it opens the report viewer window. I have noticed that on the main window, it creates a square-like widget, much like a push button with no text in the top left hand corner of the window when I run the program. Why is it doing this and how can I stop this from happening. Here is my main GUI window code. # import Statements from PyQt5 import QtCore, QtGui, QtWidgets from reportViewerWindow import Ui_reportViewerWindow # Main Class that holds User Interface Objects class Ui_MainWindow(object): # Function for Opening Report Viewer Window From Main Window by clicking View Reports def openReportViewer(self): self.window = QtWidgets.QMainWindow() self.ui = Ui_reportViewerWindow() self.ui.setupUi(self.window) MainWindow.hide() self.window.show() def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.setFixedSize(834, 428) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(12) font.setBold(True) font.setWeight(75) MainWindow.setFont(font) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") # Sim Card Button self.simCardButton = QtWidgets.QPushButton(self.centralwidget) self.simCardButton.setGeometry(QtCore.QRect(30, 200, 211, 30)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(14) self.simCardButton.setFont(font) self.simCardButton.setObjectName("simCardButton") # Call Logs Button self.callLogButton = QtWidgets.QPushButton(self.centralwidget) self.callLogButton.setGeometry(QtCore.QRect(30, 300, 211, 30)) font = Qt…
accepted answer: http://stackoverflow.com/a/48914954
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84835127
tagged with: pyqt5
downvote count: 1
type: Question
has title: Creating a Widget Unintentionally
upvote count: 0

http://stackoverflow.com/q/48931479
has comment: http://stackoverflow.com/comment/84869674
linked to: http://stackoverflow.com/q/2835559
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48931560
favorite count: 0
has title: regex getting url link
has comment: http://stackoverflow.com/comment/84869671
tagged with: python
tagged with: regex
duplicate of: http://stackoverflow.com/q/2835559
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48931560
has body: I am trying to extract the link I am getting from a curl command. Curl command throws back of type string. {"success":true,"key":"Syv77d","link":"https://file.io/Syv77d","expiry":"14 days"} In my below code this gets https://file.io/Syv77d","expiry":"14 days"} link = re.search('https://.*$',fileIO) What I wanted was just https://file.io/Syv77d The link would vary so i would need the url without the double-qoutes. I think I am missing something in my regex.

http://stackoverflow.com/q/48918407
downvote count: 0
has title: Django URL with parameters not working
has comment: http://stackoverflow.com/comment/84853755
tagged with: url
favorite count: 0
has comment: http://stackoverflow.com/comment/84843287
type: UnansweredQuestion
tagged with: django
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84844016
has body: I'm trying to use pass a parameter to a URL in Django, but I keep getting this error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/%7B%25%20url%20review%20review_id%3D3%20%25%7D Using the URLconf defined in soundclinic.urls, Django tried these URL patterns, in this order: [name='index'] login/ [name='login'] register/ [name='register'] create_user [name='create_user'] &lt;int:review_id&gt;/review/ [name='review'] admin/ main/ The current path, {% url review review_id=3 %}, didn't match any of these. The link I am follow has a tag like above: {% url review review_id=3 %} I'm not sure what I'm not including right, as it looks like I'm writing out the url tag correctly and urls.py seems to be configured correcely as well. Manually entering in the URL calls the correct views.py function, so it only has to do with my urls.py file.
score: 1
tagged with: tags
type: Question
has answer: http://stackoverflow.com/a/58765564
answer count: 1

http://stackoverflow.com/q/48955262
type: Question
accepted answer: http://stackoverflow.com/a/48955717
has answer: http://stackoverflow.com/a/48955664
has comment: http://stackoverflow.com/comment/84917513
has title: Counting the number of rows according to values in two different columns using Pandas
answer count: 2
tagged with: pandas
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84917914
favorite count: 0
has body: I have this dataframe, called "dem": code CBO SEXO \ 47 58 NaN F 48 58 Ajudante de motorista F 49 58 Ajudante de motorista M 50 58 Ajudante de motorista M 51 58 Brasador NaN 52 58 Brasador M 53 58 Brasador M FAIXA_IDADE ESCOLARIDADE 47 DE 21 A 30 ANOS Superior completo 48 MAIS DE 50 ANOS NaN 49 DE 21 A 30 ANOS Ginasial completo, ou Fundamental completo 50 DE 41 A 50 ANOS Colegial incompleto, ou Médio incompleto 51 DE 41 A 50 ANOS Colegial completo, ou Médio completo 52 DE 41 A 50 ANOS Colegial completo, ou Médio completo 53 DE 41 A 50 ANOS Ginasial completo, ou Fundamental completo I want to know how many rows contain in the CBO column the words "motorista" or "Motorista" AND in the ESCOLARIDADE column contains the words "Fundamental completo". So, the result should be 1 (there are three rows where CBO contains "motorista" but in only one ESCOLARIDADE contains "Fundamental completo"). I tried: try: mot_fund_comp=dem.loc[dem.CBO.str.contains('motorista|Motorista')].ESCOLARIDADE.str.contains['Fundamental completo'].count() except: mot_fund_comp=0 I was always getting 0. And: When I apply this same line in the below dataframe, it brings me the result 1, when it should be ZERO... dem: code CBO SEXO \ 89 59 Alimentador de linha de produção NaN 90 59 Alimentador de linha de produção M 91 59 Alimentador de linha de produção M 92 59 Alimentador de linha de produção M 93 59 Assistente de laboratório industrial F 94 59 Auxiliar de escritório M 95 59 Auxiliar de manutenção predial F 96 59 Balanceiro M 97 59 Comprador M 98 59 Desidratador de alimentos M 99 59 Desidratador de alimentos M 100 59 Desidratador de alimentos M 101 59 Desidratador de alimentos M 102 59 Mecânico de manutenção de máquinas, em geral M 103 59 Motorista de caminhão (rotas regionais e inter... M 104 59 Operador de filtro-prensa (tratamentos químico... M 105 59 Soldador M 106 59 Soldador M 107 59 Soldador M FAIXA_IDADE ESCOLARIDADE 89 MAIS DE 50 ANOS Colegial completo, ou Médio completo 90 DE 21 A 30 ANOS Na…
upvote count: 2
tagged with: count
tagged with: python
has comment: http://stackoverflow.com/comment/84917475
linked to: http://stackoverflow.com/q/26577516
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48955717
possible better answer: http://stackoverflow.com/a/48955664

http://stackoverflow.com/comment/84804429
type: AnswerComment
has text: How do I create a version that satisfies the requirement?
type: Comment
comment on: http://stackoverflow.com/a/48893047
score: 0

http://stackoverflow.com/comment/84629545
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48812979
has text: Do you mean *host* as in server, or *host* as in VM Host? Where are you running this? (VM Guest or VM Host?) Which IP address are you trying to get? (VM Guest or VM Host?)

regex
tags question: http://stackoverflow.com/q/48865605
tags question: http://stackoverflow.com/q/48875871
tags question: http://stackoverflow.com/q/48848594
tags question: http://stackoverflow.com/q/48810018
tags question: http://stackoverflow.com/q/48947759
tags question: http://stackoverflow.com/q/48916226
tags question: http://stackoverflow.com/q/48909309
tags question: http://stackoverflow.com/q/48898256
tags question: http://stackoverflow.com/q/48834842
tags question: http://stackoverflow.com/q/48898690
tags question: http://stackoverflow.com/q/48914705
tag name: regex
tags question: http://stackoverflow.com/q/48881713
tags question: http://stackoverflow.com/q/48825940
tags question: http://stackoverflow.com/q/48884352
tags question: http://stackoverflow.com/q/48874898
tags question: http://stackoverflow.com/q/48896912
tags question: http://stackoverflow.com/q/48859811
tags question: http://stackoverflow.com/q/48804543
tags question: http://stackoverflow.com/q/48883647
tags question: http://stackoverflow.com/q/48867072
tags question: http://stackoverflow.com/q/48899831
tags question: http://stackoverflow.com/q/48886886
tags question: http://stackoverflow.com/q/48930736
tags question: http://stackoverflow.com/q/48879706
tags question: http://stackoverflow.com/q/48809799
tags question: http://stackoverflow.com/q/48873936
tags question: http://stackoverflow.com/q/48882651
tags question: http://stackoverflow.com/q/48812559
tags question: http://stackoverflow.com/q/48899041
tags question: http://stackoverflow.com/q/48895642
tags question: http://stackoverflow.com/q/48847268
tags question: http://stackoverflow.com/q/48939152
tags question: http://stackoverflow.com/q/48848330
tags question: http://stackoverflow.com/q/48871211
tags question: http://stackoverflow.com/q/48860897
tags question: http://stackoverflow.com/q/48896147
tags question: http://stackoverflow.com/q/48949604
tags question: http://stackoverflow.com/q/48959969
tags question: http://stackoverflow.com/q/48846867
tags question: http://stackoverflow.com/q/48832018
tags question: http://stackoverflow.com/q/48919003
tags question: http://stackoverflow.com/q/48938108
tags question: http://stackoverflow.com/q/48897396
tags question: http://stackoverflow.com/q/48859181
tags question: http://stackoverflow.com/q/48858357
tags question: http://stackoverflow.com/q/48895057
tags question: http://stackoverflow.com/q/48957099
tags question: http://stackoverflow.com/q/48882196
tags question: http://stackoverflow.com/q/48854387
tags question: http://stackoverflow.com/q/48838505
tags question: http://stackoverflow.com/q/48846950
tags question: http://stackoverflow.com/q/48913036
tags question: http://stackoverflow.com/q/48870253
tags question: http://stackoverflow.com/q/48856775
tags question: http://stackoverflow.com/q/48933407
tags question: http://stackoverflow.com/q/48819569
tags question: http://stackoverflow.com/q/48853555
tags question: http://stackoverflow.com/q/48936202
tags question: http://stackoverflow.com/q/48817143
tags question: http://stackoverflow.com/q/48953985
tags question: http://stackoverflow.com/q/48835481
tags question: http://stackoverflow.com/q/48878848
tags question: http://stackoverflow.com/q/48909748
tags question: http://stackoverflow.com/q/48834270
tags question: http://stackoverflow.com/q/48820386
tags question: http://stackoverflow.com/q/48826204
tags question: http://stackoverflow.com/q/48831730
tags question: http://stackoverflow.com/q/48859380
tags question: http://stackoverflow.com/q/48859725
tags question: http://stackoverflow.com/q/48906947
tags question: http://stackoverflow.com/q/48837582
tags question: http://stackoverflow.com/q/48935143
tags question: http://stackoverflow.com/q/48903177
tags question: http://stackoverflow.com/q/48957035
tags question: http://stackoverflow.com/q/48896593
tags question: http://stackoverflow.com/q/48940160
tags question: http://stackoverflow.com/q/48902627
tags question: http://stackoverflow.com/q/48853213
tags question: http://stackoverflow.com/q/48836620

http://stackoverflow.com/q/48886648
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/84778024
has answer: http://stackoverflow.com/a/48886838
score: 0
has comment: http://stackoverflow.com/comment/84778074
accepted answer: http://stackoverflow.com/a/48886773
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48886838
tagged with: python
has answer: http://stackoverflow.com/a/48886773
has title: Count values in numpy array and return index by result
has comment: http://stackoverflow.com/comment/84778316
type: AnsweredQuestion
has body: I have a 2d numpy array my_array that starts out like this: array([[1., 2., 3., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 6., 7., 8., 9.]]) But after some processing which is irrelevant now looks like this: array([[1., 2., 0., 4., 5., 6., 0., 8., 9.], [0., 2., 0., 0., 5., 6., 7., 8., 9.], [0., 2., 0., 4., 5., 0., 7., 0., 9.], [1., 2., 0., 4., 5., 6., 7., 8., 9.], [1., 2., 3., 4., 5., 0., 7., 8., 9.], [0., 2., 0., 4., 5., 6., 0., 8., 9.], [1., 2., 0., 4., 5., 6., 7., 8., 9.], [1., 2., 0., 4., 5., 6., 7., 8., 9.], [1., 2., 0., 4., 5., 6., 7., 8., 0.]]) As you can see, some of the items have been "zeroed out" quite randomly, but only the value of 3 was left with only 1 item that isn't zero. I'm looking for a function that takes this array and returns the index / row number that has the value 3 (or any other value that only appears once and only once in the array). To explain this differently: I first have to figure out if there is such an item that only appears once (in this example the answer is yes and that item is the number 3), and then I need to return its row number (in this case 4 since the only line with 3 in it is: my_array[4]) I have successfully done that with iterating over the array, item by item, and counting the number of times each number appears (and returning only the item whose count is 1) and then iterating over everything a second time to find the correct index / row number of where that item is located. This seems very inefficient, especially if the array will be larger. Is there a better way in numpy to do this? EDIT: if the number that appears only once is 0 that shouldn't count, i'm only looking for the "column" that was zeroed-out completely except 1 item in it

http://stackoverflow.com/q/48932590
tagged with: list-comprehension
has comment: http://stackoverflow.com/comment/84878327
type: Question
has comment: http://stackoverflow.com/comment/84872352
has title: List comprehension and seemingly equivalent Python for loop returning slightly different lists
favorite count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48932967
downvote count: 2
upvote count: 1
tagged with: python
type: AnsweredQuestion
has body: Below I try to generate the same list using list comprehension active_apps_reported and a Python for loop active_apps_reported_2. The list I am generating is derived from a 2D list of applications active_apps and a 2D list of applications that have submitted reports reported_apps. My goal is to identify active applications that have submitted a report. The two final lists report the same 4482 unique values; however, len(active_apps_reported) == 5875 and len(active_apps_reported_2) == 5880. The difference seems minor, but I am confused as to how it is possible given that both lists were generated from the same two 2D lists. active_apps_reported = [app for app in active_apps if any(app[0:2] == other[0:2] for other in reported_apps)] active_apps_reported_2 = [] for app in active_apps: for other_app in reported_apps: if app[0:2] == other_app[0:2]: active_apps_reported_2.append(app) else: continue
has comment: http://stackoverflow.com/comment/84872489
accepted answer: http://stackoverflow.com/a/48932967
score: -1
has comment: http://stackoverflow.com/comment/84872148

http://stackoverflow.com/a/48869818
has comment: http://stackoverflow.com/comment/84743711
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48868904
has comment: http://stackoverflow.com/comment/84744495
has comment: http://stackoverflow.com/comment/84745516
score: 1
has comment: http://stackoverflow.com/comment/84745426
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84743522
has comment: http://stackoverflow.com/comment/84743624
type: Answer
has body: You always need an access token to upload a file with the Slack API. But you can install your Slack app to your own Slack workspace without going through the OAuth process yourself. Just create your Slack app and go to the "Install App" page your app. Which you find under Manage your apps. Example screenshot: Another option (although not recommended) is to us a legacy token. You can create it here: https://api.slack.com/custom-integrations/legacy-tokens
answers question: http://stackoverflow.com/q/48868904

http://stackoverflow.com/comment/84710304
type: Comment
type: QuestionComment
has text: @tabbek looked at the steps you provided and I don't think they will help. I ran "softwareupdate --list" and there is nothing to update. I do notice that when trying to install scrapy lxml resources are being found. bombs out on building wheels "Running setup.py bdist_wheel for lxml ... error"
score: 0
comment on: http://stackoverflow.com/q/48847375

http://stackoverflow.com/q/48945163
has answer: http://stackoverflow.com/a/48945195
type: Question
has body: Question 1 : Can we convert list of float values to sets DATA : A B 1 [1212.0, 2121.0, 323.0] 2 [2222.0, 2222.0, 323.0] 3 [3232.0, 2323.0, 323.0] dtype(B) = object Expected output: A B 1 {121, 2121, 323} 2 {2222, 2222, 323} 3 {3232, 2323,323} Question 2 : I have a dataframe where I am merging the clusters with songs, in cluster one if there is a null value, it should ignore that and consider only the values which have numbers. Data : cluster songs 1 11 2 22 1 22 2 3 22 1 3 11 4 Output : cluster songs 1 [11, 22, ] 2 [22, ] 3 [22,11] 4 [] Expected output : cluster songs 1 [11, 22] 2 [22] 3 [22,11] 4 []
has title: converting list of floats to a set of values
tagged with: pandas
upvote count: 1
answer count: 1
tagged with: python
favorite count: 0
type: UnansweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/q/48837365
accepted answer: http://stackoverflow.com/a/48875921
has comment: http://stackoverflow.com/comment/84679555
tagged with: python
has answer: http://stackoverflow.com/a/48875921
tagged with: biopython
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/34145861
tagged with: anaconda
type: Question
has title: Getting error parsing sys.version when try to run BioPython tests
has body: Installed BioPython 1.70 on a machine that has python 2.7.14. Want to validate setup by running tests. $ python run_tests.py Traceback (most recent call last): File "run_tests.py", line 148, in &lt;module&gt; if is_numpy(): File "run_tests.py", line 63, in is_numpy if is_pypy(): File "run_tests.py", line 54, in is_pypy if platform.python_implementation() == 'PyPy': File "/home/foo/python/lib/python2.7/platform.py", line 1460, in python_implementation return _sys_version()[0] File "/home/foo/python/lib/python2.7/platform.py", line 1422, in _sys_version repr(sys_version)) ValueError: failed to parse CPython sys.version: '2.7.14 |Anaconda, Inc.| (default, Dec 7 2017, 17:05:42) \n[GCC 7.2.0]' Do I have to edit /home/foo/python/lib/python2.7/platform.py if I want to run any tests?
score: 0
answer count: 1

http://stackoverflow.com/comment/84859862
type: AnswerComment
score: 0
type: Comment
has text: great answer @tobias_k
comment on: http://stackoverflow.com/a/48926744

http://stackoverflow.com/comment/84810205
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48902303
has text: Add your `Restaurant` model code snippet. `restaurant` is a foreign key attribute in the `Restaurant` model itself?
score: 0

http://stackoverflow.com/comment/84665068
type: QuestionComment
comment on: http://stackoverflow.com/q/48812097
has text: No it won't. I tried importing `from cars.lib.email import send_email` and then `send_email = MagicMock()` in the test file but it also gets not called error.
score: 0
type: Comment

http://stackoverflow.com/a/48879688
answers question: http://stackoverflow.com/q/48878855
downvote count: 0
has body: You are interested in the data being encoded not the list itself being encoded. Therefore I suggest the following: use struct to pack the data. x = range(10) import struct y = struct.pack('&lt;{}i'.format(len(x)), *x) import base64 z = base64.b64encode(y) z will now be an encoding of the data in the list. You can decode it back and retrieve the list as follows: y = base64.b64decode(z) list(struct.unpack('&lt;{}i'.format(len(y)/4), y))
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/48814481
answer count: 1
has body: Part of a large project I have includes a section, in python, like this: failcount = 0 done = False while done == False: try: result = subprocess.check_output(program) done = True except subprocess.CalledProcessError as e: failcount += 1 logwrite('logfile.txt', 'Failed. Counter = {0}\nError message: {1}\n-'.format(failcount, e.returncode)) if failcount == 20: print 'It failed 20 times, aborting...' quit() What this is meant to do is run "program" from the command line. "program" is a large computational chemistry package which fails sometimes, so I run it in a loop here. If it fails 20 times, then my python script terminates. This works just fine and it does what is intended. However, my issue is that my chemistry package takes about three hours for each attempt and I want to monitor it as it's going. If I run it from the command line manually I can simply do "program > logfile" and then tail -f the logfile to watch it go. However it seems you can't do something in python like: subprocess.check_output(['program', '&gt;', 'logfile']) Is there a way to have python print out the contents of subprocess.check_output as it is being filled? I think subprocess.check_output just contains whatever is in stdout. Can I clone it between python and a pipe somehow? Possible workaround: I made a bash script called run_program.sh which just does program > logfile as I listed above, and then I used python's subprocess to execute run_program.sh. This way I can monitor is as desired but now the output of program is in a file, instead of in python, so I would have to have python read a large logfile, and capture error messages if needed, so I would prefer if I could avoid something like this.
downvote count: 0
accepted answer: http://stackoverflow.com/a/48815743
tagged with: python
favorite count: 0
has answer: http://stackoverflow.com/a/48815743
tagged with: subprocess
linked to: http://stackoverflow.com/q/32684119
has title: Real-time piping with python subprocess.check_output or workaround?
score: 2
type: AnsweredQuestion
tagged with: pipe
type: Question
upvote count: 2

http://stackoverflow.com/a/59690798
has body: You can tell pyinstaller to look in the virtual env created by pipenv when searching for the required modules. $ pipenv --venv path\to\.virtualenvs\project $ pipenv run pyinstaller --paths path\to\.virtualenvs\project project.py
answers question: http://stackoverflow.com/q/48875894
type: Answer
score: 5
upvote count: 5
downvote count: 0

tkinter
tags question: http://stackoverflow.com/q/48894822
tags question: http://stackoverflow.com/q/48893180
tags question: http://stackoverflow.com/q/48933964
tags question: http://stackoverflow.com/q/48923003
tags question: http://stackoverflow.com/q/48846317
tags question: http://stackoverflow.com/q/48847652
tags question: http://stackoverflow.com/q/48957469
tags question: http://stackoverflow.com/q/48867800
tags question: http://stackoverflow.com/q/48891302
tags question: http://stackoverflow.com/q/48928370
tags question: http://stackoverflow.com/q/48941928
tags question: http://stackoverflow.com/q/48914833
tags question: http://stackoverflow.com/q/48917403
tags question: http://stackoverflow.com/q/48952272
tags question: http://stackoverflow.com/q/48862699
tags question: http://stackoverflow.com/q/48897355
tags question: http://stackoverflow.com/q/48814864
tags question: http://stackoverflow.com/q/48889170
tags question: http://stackoverflow.com/q/48837909
tags question: http://stackoverflow.com/q/48833763
tags question: http://stackoverflow.com/q/48812893
tag name: tkinter
tags question: http://stackoverflow.com/q/48948948
tags question: http://stackoverflow.com/q/48833908
tags question: http://stackoverflow.com/q/48924590
tags question: http://stackoverflow.com/q/48887475
tags question: http://stackoverflow.com/q/48862240
tags question: http://stackoverflow.com/q/48911812
tags question: http://stackoverflow.com/q/48950665
tags question: http://stackoverflow.com/q/48809312
tags question: http://stackoverflow.com/q/48849994
tags question: http://stackoverflow.com/q/48847491
tags question: http://stackoverflow.com/q/48937748
tags question: http://stackoverflow.com/q/48922679
tags question: http://stackoverflow.com/q/48877086
tags question: http://stackoverflow.com/q/48817749
tags question: http://stackoverflow.com/q/48838335
tags question: http://stackoverflow.com/q/48804621
tags question: http://stackoverflow.com/q/48840403
tags question: http://stackoverflow.com/q/48945460
tags question: http://stackoverflow.com/q/48848671
tags question: http://stackoverflow.com/q/48817792
tags question: http://stackoverflow.com/q/48854656
tags question: http://stackoverflow.com/q/48935072
tags question: http://stackoverflow.com/q/48916759
tags question: http://stackoverflow.com/q/48930355
tags question: http://stackoverflow.com/q/48817876
tags question: http://stackoverflow.com/q/48861856
tags question: http://stackoverflow.com/q/48808420
tags question: http://stackoverflow.com/q/48841215
tags question: http://stackoverflow.com/q/48846586
tags question: http://stackoverflow.com/q/48841190
tags question: http://stackoverflow.com/q/48891038
tags question: http://stackoverflow.com/q/48816552
tags question: http://stackoverflow.com/q/48840448
tags question: http://stackoverflow.com/q/48814937
tags question: http://stackoverflow.com/q/48834741
tags question: http://stackoverflow.com/q/48815731
tags question: http://stackoverflow.com/q/48938991
tags question: http://stackoverflow.com/q/48879883
tags question: http://stackoverflow.com/q/48858446
tags question: http://stackoverflow.com/q/48875474
tags question: http://stackoverflow.com/q/48849704
tags question: http://stackoverflow.com/q/48865455
tags question: http://stackoverflow.com/q/48863227
tags question: http://stackoverflow.com/q/48874072
tags question: http://stackoverflow.com/q/48910844
tags question: http://stackoverflow.com/q/48900721
tags question: http://stackoverflow.com/q/48898080
tags question: http://stackoverflow.com/q/48886085
tags question: http://stackoverflow.com/q/48856920
tags question: http://stackoverflow.com/q/48839155
tags question: http://stackoverflow.com/q/48862213
tags question: http://stackoverflow.com/q/48958695
tags question: http://stackoverflow.com/q/48890382
tags question: http://stackoverflow.com/q/48876039
tags question: http://stackoverflow.com/q/48843149
tags question: http://stackoverflow.com/q/48819658
tags question: http://stackoverflow.com/q/48921635
tags question: http://stackoverflow.com/q/48910513

http://stackoverflow.com/a/48909382
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48908102
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/84867367
upvote count: 1
has comment: http://stackoverflow.com/comment/84867588
has body: You can do this by overriding the get_form method in you ModelAdmin: class StepModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(StepModelAdmin, self).get_form(request, obj, **kwargs) if Step.objects.count() &gt; 1: # this will hide the null option for the parent field form.base_fields['parent'].empty_label = None return form
answers question: http://stackoverflow.com/q/48908102
type: AcceptedAnswer

http://stackoverflow.com/q/48916181
upvote count: 1
tagged with: python
has title: Import file from top of hierarchy folder
score: 1
type: Question
has body: I can't import variable "Base" from file (dataBase.py) of top of hierarchy structure like this: Structure and file dataBase.py Content of Store.py: from sqlalchemy import Column, String, Integer from dataBase import Base class Store(Base): __tablename__ = 'stores' id = Column(Integer, primary_key=True) name = Column(String(50)) def __init__(self, name): self.name = name line: "from dataBase import Base" doesn't work - I'm getting: File "Store/Store.py", line 2, in &lt;module&gt; from dataBase import Base ImportError: No module named 'dataBase' I tried to add to all folders a file: __init__.py but the error is still the same like before.
answer count: 2
has answer: http://stackoverflow.com/a/48916379
downvote count: 0
has answer: http://stackoverflow.com/a/48916480
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/q/48894385
favorite count: 0
has answer: http://stackoverflow.com/a/48894960
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84794959
score: 1
has body: Given a numpy matrix: input = np.array([ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]) I want to add an extra element to each row at a specific location. For example after coordinate (0, 0) add 100, after (1,1) add 101 and after (0, 2) add 102 so my final will look like this: output = np.array([ [1, 100, 2, 3], [4, 5, 101, 6], [7, 102, 8, 9] ]) How would you do this?
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48894813
has comment: http://stackoverflow.com/comment/84794770
has comment: http://stackoverflow.com/comment/84795165
has comment: http://stackoverflow.com/comment/84795256
has title: Insert values into arbitrary 2d coordinate numpy matrix
tagged with: numpy
answer count: 3
has answer: http://stackoverflow.com/a/48895284
has comment: http://stackoverflow.com/comment/84794999
downvote count: 0

http://stackoverflow.com/a/48954570
has body: This isn't working because when you do: D = [dictionary for i in range(10)] You create a list with 10 references to the same object. Once the first iteration succesfully does: i['c'] = tuple(i['c'].items()) The next one is guaranteed to fail, since it is the same object you dealt with on the previous iteration, so the 'c' value is a tuple! Note: In [10]: dictionary = { "a" : "100", "b" : "200", "c" : {"a":"f","b":"4"} } ...: D = [dictionary for i in range(10)] ...: print([hex(id(x)) for x in D]) ...: ['0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088', '0x105c59088'] Instead, do something like: In [11]: dictionary = { "a" : "100", "b" : "200", "c" : {"a":"f","b":"4"} } ...: D = [dictionary.copy() for i in range(10)] ...: print([hex(id(x)) for x in D]) ...: ['0x105c592c8', '0x105c59e48', '0x105cfd848', '0x105c9af48', '0x105d06c48', '0x105c59708', '0x105d06cc8', '0x105c59488', '0x105c59e08', '0x105c593c8'] And now it will work: In [12]: for i in D: ...: i['c'] = tuple(i['c'].items()) ...: In [13]: D Out[13]: [{'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}, {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}, {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}, {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}, {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}, {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}, {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}, {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}, {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}, {'a': '100', 'b': '200', 'c': (('b', '4'), ('a', 'f'))}]
accepted answer of: http://stackoverflow.com/q/48954446
upvote count: 1
answers question: http://stackoverflow.com/q/48954446
score: 1
has comment: http://stackoverflow.com/comment/84915966
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/48847285
answers question: http://stackoverflow.com/q/48847146
type: Answer
has body: Firstly, the range returned by numpy.arange is not inclusive, so for i in numpy.arange(0, 5): print i will print 0 1 2 3 4 but not 5. In order to get it to print the 5, you want to increment it by the step, which is 1 in the case of the outer loop (by default) and 0.01 in the case of the inner one. After the first execution of the inner loop, lopt is 0.03, which means that the arguments to the inner numpy.arange are (0.03, 0.04, 0.01) which results in only one loop. What you really want is lopt = 0 dwl = 0.04 Dt = 0.01 for i in numpy.arange(0, 5): for t in numpy.arange(lopt, dwl + lopt + Dt, Dt): print 't = ', t, 'row = ', i lopt = t + 0.001 because that way the second evaluation of that inner numpy.arange will have arguments of (0.041, 0.09, 0.01), and the third will be (0.082, 0.131, 0.01) and so on.
score: 0

http://stackoverflow.com/q/48823152
tagged with: data-cleaning
tagged with: python
possible better answer: http://stackoverflow.com/a/48824861
linked to: http://stackoverflow.com/q/35491274
has answer: http://stackoverflow.com/a/48823193
has comment: http://stackoverflow.com/comment/84649965
upvote count: 7
downvote count: 1
has comment: http://stackoverflow.com/comment/84649680
score: 6
accepted answer: http://stackoverflow.com/a/48823193
tagged with: pandas
has title: python pandas: split comma-separated column into new columns - one per value
type: AnsweredQuestion
has body: I have a dataframe like this: data = np.array([["userA","event2, event3"], ['userB',"event3, event4"], ['userC',"event2"]]) data = pd.DataFrame(data) 0 1 0 userA "event2, event3" 1 userB "event3, event4" 2 userC "event2" now I would like to get a dataframe like this: 0 event2 event3 event4 0 userA 1 1 1 userB 1 1 2 userC 1 can anybody help please?
favorite count: 0
has answer: http://stackoverflow.com/a/48824861
type: Question
answer count: 2

http://stackoverflow.com/q/48872885
accepted answer: http://stackoverflow.com/a/48873129
type: AnsweredQuestion
upvote count: 2
downvote count: 2
tagged with: pip
has comment: http://stackoverflow.com/comment/84749925
type: Question
has comment: http://stackoverflow.com/comment/84749631
has comment: http://stackoverflow.com/comment/84749608
linked to: http://stackoverflow.com/q/47640554
has title: How to upgrade Django to 2.0 version
has body: I've been traying to upgrade my django versión and I've coudnt. xxx@yyyyyy:~# python Python 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import django &gt;&gt;&gt; django.VERSION (1, 11, 10, u'final', 0) xxxx@yyyyyyy:~# pip install -U Django The directory '/home/user/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/user/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Requirement already up-to-date: Django in /usr/local/lib/python2.7/dist-packages Requirement already up-to-date: pytz in /usr/local/lib/python2.7/dist-packages (from Django) xxxx@yyyyyy:~# pip --no-cache-dir install -U Django Requirement already up-to-date: Django in /usr/local/lib/python2.7/dist-packages Requirement already up-to-date: pytz in /usr/local/lib/python2.7/dist-packages (from Django) How it coud be up-to-date my django version if enter code hereit is not 2.0 it is (1, 11, 10, u'final', 0) And If I do an ls -s to know the files owners: xxxx@yyyyyyy:~# ls -s /home/gechichure/.cache/pip total 12 4 http 4 selfcheck.json 4 wheels Not root or my useradmin ?!?!?! I do not understand how django it works and how pip it really works :( I need to upgrade to 2.0 versión !! Please any suggestions would be apprecciate. Regards !!!
duplicate of: http://stackoverflow.com/q/47640554
has answer: http://stackoverflow.com/a/48873129
score: 0
has comment: http://stackoverflow.com/comment/84749701
answer count: 1
favorite count: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/84749742
tagged with: django
tagged with: python

http://stackoverflow.com/q/48844119
linked to: http://stackoverflow.com/q/17373118
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84692608
type: UnansweredQuestion
tagged with: python
has body: Here's a sample code with open('somefile.txt', 'r') as file: for line in file: find = 'some string' if find in line: if previous line is the same as this line: #how to write this ? pass else: print(line) How to write line 5 in this code ?
type: Question
has title: While reading a text file, using a for line in file loop, how to select the previous line?
score: 0
has answer: http://stackoverflow.com/a/48844155
duplicate of: http://stackoverflow.com/q/17373118
answer count: 1

http://stackoverflow.com/comment/84863579
type: Comment
comment on: http://stackoverflow.com/q/48897786
type: QuestionComment
score: 0
has text: I am able to achieve the task with the help of pandas.

http://stackoverflow.com/comment/84656404
comment on: http://stackoverflow.com/a/48824021
score: 0
type: AnswerComment
type: Comment
has text: Oh, I didn’t know this is possible. I will see if it works as expected and get back to you.

http://stackoverflow.com/q/48870273
tagged with: python
favorite count: 0
tagged with: google-groups-api
answer count: 0
type: UnansweredQuestion
tagged with: google-api
upvote count: 1
score: 1
type: Question
has title: Google Groups API : Setting Google Groups spam moderation parameters
downvote count: 0
has body: I'm trying to change the "spamModerationLevel" parameter on all groups (~375 groups) on my company's google mail, and am struggling with the script i use. I have managed to get the list of groups with a script inspired from this doc. What I can't do, however, is update the required parameter. body={'spamModerationLevel': 'ALLOW'} editResult=service.groups().update(groupKey=*groupID*, body=body).execute() This request doesn't return any error, but the moderation level isn't updated. If I change the body of the request to something like body={'description': 'test2'} The request runs fine, and the group's description is updated. Is there anything I missed? Using the API Explorer here, I can change any parameter I want, so I assume I should be able to do so in a script.

http://stackoverflow.com/q/48835714
answer count: 1
has body: I'm currently trying to announce when the client initially connects to the server and to print out a simple message like "you are connected". Its my first program with python so i'm sure they're many easier ways to do what i've accomplished and i'm open to tips The server successfully responds to the commands "HELO" "REQIP" "REQDATE" "REQTIME" "ECHO" and "BYE" Here is my tcp server import socket import time host = '127.0.0.1' port = 8008 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host,port)) s.listen(1) c, addr = s.accept() def Main(): #print("Server Listening") while True: data = c.recv(1024).decode('utf-8') if not data: break if data =='HELO': Hello(data) elif data == 'REQTIME': REQTIME(data) elif data == 'REQDATE': REQDATE(data) elif data == 'REQIP': IP(data) elif data =='BYE': BYE() elif data[:4] == 'ECHO': ECHO(data) else: message = ("Invalid command") c.send(message.encode('utf-8')) def Hello(data): if data !='HELO': message = ("Server: 510 Sorry i can not service your request. \n Connection Closed") c.send(message.encode('utf-8')) c.close() message = ("Server: 210 Hello " + host + " pleased to meet you.") c.send(message.encode('utf-8')) Main() def REQTIME(data): if data !='REQTIME': message = ("Server: 520 Sorry, time is not available right now") c.send(message.encode('utf-8')) message = ("Server: 220 " + (time.strftime('%H:%M:%S'))) c.send(message.encode('utf-8')) Main() def REQDATE(data): if data !='REQDATE': message =("Server: 530 Sorry, date is not available right now") c.send(message.encode('utf-8')) message = ("Server: 230 " + (time.strftime("%Y/%m/%d"))) c.send(message.encode('utf-8')) Main() def ECHO(data): if data[:4] !='ECHO': message =("Server: 5350 Cant seem to echo") c.send(message.encode('utf-8')) text = ("Server: 240 " ) message = text + data[4:] c.send(message.encode('utf-8')) Main() def IP(data): if data !='REQIP': message = ("Server: 550 Sorry i can not get your IP Address.") message =("Server: 250 " + host) c.send(message…
type: UnansweredQuestion
tagged with: python
tagged with: client
has answer: http://stackoverflow.com/a/48835927
tagged with: tcp
type: Question
tagged with: server
has title: Announcing a server connection to client automatically TCP/IP Python
score: 0

http://stackoverflow.com/comment/84832665
type: QuestionComment
comment on: http://stackoverflow.com/q/48913031
has text: @juanpa.arrivillaga In fact, I am supposed to add new list to fixed matrix `M` in various position inside a loop based on my algorithm. That's why I thought so
score: 0
type: Comment

http://stackoverflow.com/comment/84795919
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48889473
has text: Can you post the relevant SQL definitions of the two tables, and the desired SQL queries?
score: 0

http://stackoverflow.com/a/74914944
answers question: http://stackoverflow.com/q/48912253
score: 1
has comment: http://stackoverflow.com/comment/132214673
has body: This usually happens if you had missed something to add to your lambda Layers. I tried replicating one of my lambda functions and forgot to import the lambda layer that I was having in my old lambda function, so after importing the file into layers, the API started working fine. May be this might help anyone.
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84773469
type: QuestionComment
comment on: http://stackoverflow.com/q/48882225
score: 0
has text: Try a self-contained complete example, http://sscce.org/
type: Comment

http://stackoverflow.com/q/48868464
downvote count: 1
type: Question
score: -1
tagged with: paramiko
has body: I am able to doing ssh to cisco devices and its working fine. I am able to run EXEC mode commands but I am not able to execute privileged commands. It looks like I need to enter into enable mode but I am not sure about the arguments that needs to be passed in ssh. My code is as below. Can you please help me? Thank you for any help. import os import getpass import paramiko import xlsxwriter import socket import re import sys import smtplib username = 'username' password = 'password' print "Running the tests..this might take some time.." # Opens file in read mode f1 = open('hostfile','r') f2 = open('commandfile','r') # Creates list based on f1 devices = f1.readlines() commands = f2.readlines() ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) data = [] for device in devices: column = device.split() data.append([column[0]]) print column[0] for command in commands: try: conn=ssh.connect(column[0], username=username, password=password, timeout=4) if conn is None: stdin, stdout, stderr = ssh.exec_command(command) x=stdout.readlines() print '*****************************************************************' print ' Output of ' + command + ' on ' + device print '*****************************************************************' raw_input("Press any key to continue.") for j in x: print j data[-1].append(stdout.read()) ssh.close() except paramiko.AuthenticationException: output = "Authentication Failed" data[-1].append(output) break except paramiko.SSHException: output = "Issues with SSH service" data[-1].append(output) break except socket.error, e: output = "Connection Error" data[-1].append(output) break data[-1] = tuple(data[-1]) f1.close() f2.close()
tagged with: cisco
upvote count: 0
answer count: 1
favorite count: 0
has title: Issue with entering in enable mode in Cisco devices when connected with SSH
type: UnansweredQuestion
tagged with: ssh
tagged with: python
has answer: http://stackoverflow.com/a/48903056

http://stackoverflow.com/q/48959391
has answer: http://stackoverflow.com/a/48960714
answer count: 2
score: 2
has answer: http://stackoverflow.com/a/48960868
downvote count: 0
has body: I'm fairly new to Django and am currently trying to go through and modify a preexisting website. I'm trying to understand the syntax involved with creating a chart based on certain parameters. Currently the site takes account types as an argument and spits out a plot of account values vs. years. As shown in the first picture: Picture of Plot The part of the code I'm confused about is here: tag_ids = [56, 123, 15, 21, 82] if categories_1: tag_ids = categories_1.split(',') tags = [] funding_announced_min = minyear+'-01-01' funding_announced_max = maxyear+'-12-31' business_list = [] for d in tag_ids: tag1 = Tag_objs.objects.get(pk=int(d)) tags.append(tag1) business_1 = tag1.buisiness.filter( company__founded_date__gte=funding_announced_min, company__founded_date__lte=funding_announced_max, entity_type=0, ) business_list.append(business1) tag is a table of account types, and my confusion comes from the business_1 = tag1.business.filter section. What exactly is this doing? I have a model called biz that looks like this: class biz(Ent): founded_date = models.DateField(blank=True, null=True) employee_amount = models.IntegerField('Number of Employees',blank=True, null=True) employee_amount_range = models.CharField(max_length=64, blank=True, null=True) biz_status = models.CharField(choices=BIZ_STATUS_CHOICES, max_length=32, default='operating', blank=True, null=True) zipcode = models.CharField(max_length=64, blank=True, null=True) address = models.CharField(max_length=255, blank=True, null=True) funding_rounds = models.IntegerField(default=0, blank=True, null=True) funding_total_usd = models.BigIntegerField(default=0, blank=True, null=True) first_funding_on = models.DateField(blank=True, null=True) last_funding_on = models.DateField(blank=True, null=True) closed_on = models.DateField(blank=True, null=True) employee_count_min = models.IntegerField(default=0, blank=True, null=True) employee_count_max = models.IntegerField(default=0, blank=True, null=True) def __str__(self): re…
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: models
has title: Explanation of Django Table Relations and How they are Being Called
tagged with: mysql
type: Question
tagged with: class

http://stackoverflow.com/a/48943944
upvote count: 1
has comment: http://stackoverflow.com/comment/84896162
answers question: http://stackoverflow.com/q/48943285
downvote count: 0
type: Answer
has body: As I understand, you have a specific sequence of states: S -> B -> S -> N -> B -> N -> [begin again] This could be solved with a generator such as: import itertools state = itertools.cycle(['S', 'B', 'S', 'N', 'B', 'N']) Subsequent calls of next(state) will yield the list in sequence, starting at the beginning when it reaches the end. Example: &gt;&gt;&gt; next(state) 'S' &gt;&gt;&gt; next(state) 'B' &gt;&gt;&gt; next(state) 'S' &gt;&gt;&gt; next(state) 'N' &gt;&gt;&gt; next(state) 'B' &gt;&gt;&gt; next(state) 'N' &gt;&gt;&gt; next(state) 'S' &gt;&gt;&gt; next(state) 'B' &gt;&gt;&gt; next(state) 'S' &gt;&gt;&gt; next(state) 'N' &gt;&gt;&gt; next(state) 'B'
score: 1

http://stackoverflow.com/a/48890595
score: 0
answers question: http://stackoverflow.com/q/48890532
type: Answer
has body: Your code is iterating over the keys in the dict. So, first, you print the key. Then, you look up the value of that key in the dict with prices[x].

http://stackoverflow.com/comment/84757442
type: AnswerComment
score: 0
type: Comment
has text: I'm getting an invalid syntax error at `csrfmiddlewaretoken=csrftoken` isn't that supposed to be a dictionary?
comment on: http://stackoverflow.com/a/48876624

http://stackoverflow.com/comment/84737009
has text: Thank you. I thought about shift but then got stuck. The idea that the cumulative sum is the same for each cluster is great.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48865887

recreate
type: Tag
tag name: recreate
tags question: http://stackoverflow.com/q/48857725

http://stackoverflow.com/comment/84820548
comment on: http://stackoverflow.com/q/48907175
score: 0
type: Comment
type: QuestionComment
has text: I have tried doing.....mapping={'Pave':1,'Lvl':2,'LandContour':3,'Utilities':4,'SaleCondition':5} #df.replace('Street',0) df.replace({'Street': mapping, 'LotShape': mapping, 'LandContour': mapping, 'Utilities': mapping, 'SaleCondition': mapping},True)...but that didn't work either

http://stackoverflow.com/a/48929301
has comment: http://stackoverflow.com/comment/84868188
type: Answer
has comment: http://stackoverflow.com/comment/84865762
has comment: http://stackoverflow.com/comment/84867326
has comment: http://stackoverflow.com/comment/84865316
score: 1
upvote count: 1
has body: twitter returns information about tweet language, check 'lang' param in response and filter tweets by response['lang'] == 'ar', where 'ar' means arabic
answers question: http://stackoverflow.com/q/48929106
downvote count: 0
has comment: http://stackoverflow.com/comment/84865669

http://stackoverflow.com/a/48927967
upvote count: 1
has comment: http://stackoverflow.com/comment/84867127
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84866614
type: Answer
answers question: http://stackoverflow.com/q/48927671
has body: Use sets for comparison. Setup df1 # user song # 0 A 11 # 1 A 22 # 2 B 99 # 3 B 11 # 4 C 11 # 5 D 44 # 6 C 66 # 7 E 66 # 8 D 33 # 9 E 55 # 10 F 11 # 11 F 77 df2 # user cluster # 0 A 1 # 1 B 2 # 2 C 3 # 3 D 1 # 4 E 2 # 5 F 3 df3 # cluster songs # 0 1 [11, 22, 33, 44] # 1 2 [11, 99, 66, 55] # 2 3 [11, 66, 88, 77] Calculation df = df1.groupby('user')['song'].apply(set)\ .reset_index().rename(columns={'song': 'heard'}) df['all'] = df['user'].map(df2.set_index('user')['cluster'])\ .map(df3.set_index('cluster')['songs'])\ .map(set) df['not heard'] = df.apply(lambda row: row['all'] - row['heard'], axis=1) Result user heard all not heard 0 A {11, 22} {33, 11, 44, 22} {33, 44} 1 B {11, 99} {99, 66, 11, 55} {66, 55} 2 C {66, 11} {88, 66, 11, 77} {88, 77} 3 D {33, 44} {33, 11, 44, 22} {11, 22} 4 E {66, 55} {99, 66, 11, 55} {11, 99} 5 F {11, 77} {88, 66, 11, 77} {88, 66} Extract any columns you need; conversion to list is trivial, i.e. df[col] = df[col].map(list). Explanation There are 3 steps: Convert lists to sets and aggregate heard songs by user to sets. Perform mappings to put all data in one table. Add a column which calculates the difference between 2 sets.

http://stackoverflow.com/q/48853213
has answer: http://stackoverflow.com/a/48853801
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48853268
accepted answer: http://stackoverflow.com/a/48853801
has answer: http://stackoverflow.com/a/48853268
type: Question
answer count: 2
has title: Split by regex of new line and capital letter
downvote count: 0
has body: I've been struggling to split my string by a regex expression in Python. I have a text file which I load that is in the format of: "Peter went to the gym; he worked out for two hours Kyle ate lunch at Kate's house. Kyle went home at 9. Some other sentence here •Here's a bulleted line" I'd like to get the following output: ['Peter went to the gym; he worked out for two hours','Kyle ate lunch at Kate's house. He went home at 9.', 'Some other sentence here', '•Here's a bulleted line'] I'm looking to split my string by a new line and a capital letter or a bullet point in Python. I've tried tackling the first half of the problem, splitting my string by just a new line and capital letter. Here's what I have so far: print re.findall(r' [A-Z][a-z]+',str,re.M) This just gives me: [u' Kyle', u' Some'] which is just the first word. I've tried variations of that regex expression but I don't know how to get the rest of the line. I assume that to also split by the bullet point, I would just include an OR regex expression that is in the same format as the regex of splitting by a capital letter. Is this the best way? I hope this makes sense and I'm sorry if my question is in anyway unclear. :)
has comment: http://stackoverflow.com/comment/84710009
tagged with: regex
favorite count: 0

http://stackoverflow.com/comment/84843852
score: 0
type: AnswerComment
has text: It's actually very similar to what you were trying to do with your second attempt (the loop), but in a more pandas-like (vectorized) fashion. As far as your apply method, you were calling `.apply` as a method on the index of your dataframe, which doesn't have such a method. `.apply` is good for applying a simple function to a dataframe or series, where the arguments can be implied easily. Your function was just returning "Before Migration" if `x` is True, but there wasn't even any indication of what `x` was, nor where the "Before Migration" was meant to be returned to.
type: Comment
comment on: http://stackoverflow.com/a/48918674

http://stackoverflow.com/comment/84792734
score: 0
type: Comment
type: QuestionComment
has text: Can you show how you did the normalization? Because that is the biggest trick in the numpy function for achieving numerical stability. I remember having the same problem for a fitting function I was writing, and the normalization pretty much fixed everything if I recall correctly.
comment on: http://stackoverflow.com/q/48892547

http://stackoverflow.com/a/48816675
upvote count: 2
has comment: http://stackoverflow.com/comment/84638890
has comment: http://stackoverflow.com/comment/84637912
accepted answer of: http://stackoverflow.com/q/48816636
answers question: http://stackoverflow.com/q/48816636
has comment: http://stackoverflow.com/comment/84638062
type: AcceptedAnswer
downvote count: 0
has body: You can do the exact same thing you're already doing. Python has -=, *=, and /= operators that work the same way as the += you're already using.
type: Answer
has comment: http://stackoverflow.com/comment/84637444
score: 2

http://stackoverflow.com/comment/84903626
comment on: http://stackoverflow.com/a/48948566
has text: I don't use selectors generated by browser built-in tools - just created my own. Note that XPath is not something unique - there might be dozens of different ways to match same node using XPath...
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84884303
comment on: http://stackoverflow.com/a/48937723
type: AnswerComment
score: 0
has text: I accept your answer although refers to java and not in C, thank you
type: Comment

http://stackoverflow.com/comment/84796519
type: QuestionComment
comment on: http://stackoverflow.com/q/48837554
has text: Did you try this: https://donjayamanne.github.io/pythonVSCodeDocs/docs/unittests/ ?
score: 1
type: Comment

http://stackoverflow.com/comment/84850267
comment on: http://stackoverflow.com/a/48916445
score: 0
type: AnswerComment
has text: Sorry, I probably got it mixed up something from clojure, in Python it is `itertools.chain` indeed.
type: Comment

http://stackoverflow.com/q/48913943
favorite count: 0
upvote count: 1
type: UnansweredQuestion
has body: Can you decompress a BZ2 file on the fly line by line through hadoop? Currently, I am doing this for local files file = bz2.BZ2File(file_loc) for l in file.readlines(): print(l) Would it be possible to do this while accessing a file in a hadoop file system?
tagged with: hadoop
answer count: 0
downvote count: 0
has title: Stream decompression of bz2 file from hadoop to python
type: Question
tagged with: python
score: 1

http://stackoverflow.com/comment/84647810
has text: As you said, the problem was that I was using sigmoid instead of softmax. Now, the loss function keeps decreasing. But I don't understand well what you say about the mini batches. Do you mean that I have to select only few data to calculate the loss? Which part of data should I select? Thank you very much! @Andrey
type: Comment
comment on: http://stackoverflow.com/a/48810115
score: 0
type: AnswerComment

http://stackoverflow.com/a/48857574
answers question: http://stackoverflow.com/q/48857309
has comment: http://stackoverflow.com/comment/84718833
score: 0
has comment: http://stackoverflow.com/comment/84718724
type: Answer
has body: Make sure the do folder has an __init__.py file inside. 2. Add 'do' to the packages= kwarg in your setup.py Looks like you are handling that ok with find_packages() Working Example + app |+ do |+ __init__.py |+ do.py setup.py from setuptools import setup setup( name="cliapp", version='0.1', packages=['do'], entry_points=''' [console_scripts] do=do.do:run ''', ) do.py def run(): print('Completed') From app/ folder, install and run: &gt;&gt;&gt; pip install . &gt;&gt;&gt; do Completed Update I ran your code locally and looks like it might just be a python relative/absolute import issues inside your code. If you use full absolute imports it should work: do.py Instead of import skeleton import licenses import setup_config You need to use absolute or relative package imports # Absolute from do import skeleton from do import licenses from do import setup_config # Relative from . import skeleton from . import licenses from . import setup_config
has comment: http://stackoverflow.com/comment/84719428
has comment: http://stackoverflow.com/comment/84724914
accepted answer of: http://stackoverflow.com/q/48857309
type: AcceptedAnswer

http://stackoverflow.com/comment/84910045
comment on: http://stackoverflow.com/q/48951409
score: 0
type: Comment
type: QuestionComment
has text: Change your models first layer to this `model.add(LSTM(32, return_sequences=True, input_shape=(X.values.shape[1],)))` and try.

http://stackoverflow.com/q/48861872
type: AnsweredQuestion
favorite count: 0
type: Question
has title: how to extract a value from database using python
has comment: http://stackoverflow.com/comment/84726814
has body: I want to get a value from a database table using python. I am sending a query and getting value like this: conn = pymysql.connect(rds_host, user=name, passwd=password,db=db_name, connect_timeout=10) with conn.cursor() as cur: cur.execute("SELECT id FROM user_details WHERE email='{}'".format(email) for row in cur: id = row[0] Is there a way to get the value without using for loop.
tagged with: python
upvote count: 2
has answer: http://stackoverflow.com/a/48861945
score: 0
downvote count: 2
answer count: 1
tagged with: database
tagged with: mysql
accepted answer: http://stackoverflow.com/a/48861945

http://stackoverflow.com/q/48962594
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48963758
upvote count: 6
has comment: http://stackoverflow.com/comment/84933188
tagged with: python-2.7
answer count: 2
possible better answer: http://stackoverflow.com/a/48963810
has answer: http://stackoverflow.com/a/48963758
has answer: http://stackoverflow.com/a/48963810
favorite count: 0
has title: Unable to plot Double Bar, Bar plot using pyplot for ndarray
has body: I have got these 2 {ndarray} which has 3 values of Positive, Negative and Neutral score. &gt;&gt;&gt;y1 array([82, 80, 63]) &gt;&gt;&gt;y2 array([122, 73, 30]) For same I need y1[0] and y2[0] to be plotted together as they are corresponding as positive values, same goes with other 2 values from each array. I tried this: import matplotlib.pyplot as plt import numpy as np def biplt(groundTruth, predictedValues, plt_name='&lt;name&gt;'): gt = groundTruth pr = predictedValues x = np.arange(2) y1, y2 = gt.values, pr.values fig, axes = plt.subplots(ncols=1, nrows=1) width = 0.20 plt.title('%s\n Accuracy Score' % plt_name) plt.xlabel('Parameters') plt.ylabel('Score') axes.bar(x, y1, width, label="Algorithm 1") axes.bar(x + width, y2, width, color=list(plt.rcParams['axes.prop_cycle'])[2]['color'], label="Algorithm 2") axes.set_xticks(x + width) axes.set_xticklabels(['Positive', 'Negative']) plt.legend() plt.show() Which has resulted into ValueError, check below: ValueError: shape mismatch: objects cannot be broadcast to a single shape I'm unable to diagnose with possible shape is of problem I'm expecting a similar o/p:
score: 6
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84933138
downvote count: 0
tagged with: matplotlib

http://stackoverflow.com/q/48883809
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84791162
type: Question
has body: Hello i want to retrieve data from mysql database and i want to add that in my pyqt5 tablewidget but it is giving me error that int object is not iterable this is my code def LoadData(self): conn = mdb.connect("localhost", "root", "", "pyqt5") with conn: query = "SELECT * FROM data" cur = conn.cursor() result = cur.execute(query) self.tableWidget.setRowCount(0) for row_number, row_data in enumerate(): self.tableWidget.insertRow(row_number) for col_number, data in enumerate(row_data): self.tableWidget.setItem(row_number, col_number, QtWidgets.QTableWidgetItem(str(data)))
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48886428
has comment: http://stackoverflow.com/comment/84785587
favorite count: 0
has title: pyqt5 tablewidgets retrieving data
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84777272
has answer: http://stackoverflow.com/a/67051897
tagged with: mysql
tagged with: pyqt5

http://stackoverflow.com/q/48858357
accepted answer: http://stackoverflow.com/a/48874159
upvote count: 9
possible better answer: http://stackoverflow.com/a/48858806
has comment: http://stackoverflow.com/comment/84720277
score: 9
has answer: http://stackoverflow.com/a/48858806
answer count: 2
has title: Extract named group regex pattern from a compiled regex in Python
downvote count: 0
favorite count: 0
tagged with: python-3.x
has body: I have a regex in Python that contains several named groups. However, patterns that match one group can be missed if previous groups have matched because overlaps don't seem to be allowed. As an example: import re myText = 'sgasgAAAaoasgosaegnsBBBausgisego' myRegex = re.compile('(?P&lt;short&gt;(?:AAA))|(?P&lt;long&gt;(?:AAA.*BBB))') x = re.findall(myRegex,myText) print(x) Produces the output: [('AAA', '')] The 'long' group does not find a match because 'AAA' was used-up in finding a match for the preceding 'short' group. I've tried to find a method to allow overlapping but failed. As an alternative, I've been looking for a way to run each named group separately. Something like the following: for g in myRegex.groupindex.keys(): match = re.findall(***regex_for_named_group_g***,myText) Is it possible to extract the regex for each named group? Ultimately, I'd like to produce a dictionary output (or similar) like: {'short':'AAA', 'long':'AAAaoasgosaegnsBBB'} Any and all suggestions would be gratefully received.
has comment: http://stackoverflow.com/comment/84736719
tagged with: python
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84720134
has answer: http://stackoverflow.com/a/48874159
has comment: http://stackoverflow.com/comment/84725860
type: Question

http://stackoverflow.com/comment/84728990
type: AnswerComment
score: 0
type: Comment
has text: Can default manager in Django 2.0 handle spatial queries? I don't need to override it?
comment on: http://stackoverflow.com/a/48840336

http://stackoverflow.com/a/48882199
has body: use itertools.chain: import itertools, gzip files = ['path2zipfile1', 'path2zipfile2'] it = (gzip.open(f, 'rt') for f in files) for line in itertools.chain.from_iterable(it): print(line) another version without itertools: def gen(files): for f in files: fo = gzip.open(f, 'rt') while True: line = fo.readline() if not line: break yield line files = ['path2zipfile1', 'path2zipfile2'] for line in gen(files): print(line)
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48881167
accepted answer of: http://stackoverflow.com/q/48881167
has comment: http://stackoverflow.com/comment/84771184
type: Answer
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/84769407
has comment: http://stackoverflow.com/comment/84769637
has comment: http://stackoverflow.com/comment/84771238
has comment: http://stackoverflow.com/comment/84769262
score: 4

http://stackoverflow.com/comment/84840355
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48816873
has text: @EvanWeissburg in the second example `W` values barely change, `distance` does not get smaller and in the inference loop `estimate0` barely changes value with different inputs. In first example `W` change, `distance` become of the order of 1e-5 in a hundred steps and `estimate0` closely tracks the input value

http://stackoverflow.com/a/48853565
has comment: http://stackoverflow.com/comment/84710588
score: 0
answers question: http://stackoverflow.com/q/48853535
has body: could it be that you're walking on a folder while renaming it so that it can't be found? looks like you first need to rename the files and only then the dirs (and even then - make sure it's bottom up)
type: Answer

http://stackoverflow.com/a/48887522
type: Answer
has body: You can use tobytes for a raw image This method returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use save(), with a BytesIO parameter for in-memory data. im = Image.open(original) region = im.crop((160, 340, 1024, 650)) ls_f = base64.b64encode(region.tobytes()) s = bytes.decode(ls_f) If it is a png or jpg, you need to use BytesIO, perhaps like this: im = Image.open(original) region = im.crop((160, 340, 1024, 650)) with io.BytesIO() as temp_file: region.save(temp_file) ls_f = base64.b64encode(temp_file.getvalue()) s = bytes.decode(ls_f) it depends on the format of the input image. If it is not compressed, like a bitmap bmp, it's raw. Examples of compressed formats are png, jpeg, gif. Easiest way is to look at the extension, or to try it out. If you try the first approach on a compressed image, it'll probably raise an Exception, or return a distorted image
score: 1
accepted answer of: http://stackoverflow.com/q/48886637
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48886637
downvote count: 0

http://stackoverflow.com/a/48937093
accepted answer of: http://stackoverflow.com/q/48937018
has body: The transformation you want is called the Kronecker product. Numpy has this function as numpy.kron: In [1]: m = np.array([[1,4],[2,5],[3,6]]) In [2]: c = np.array([200,400]) In [3]: np.kron(c, m) Out[3]: array([[ 200, 800, 400, 1600], [ 400, 1000, 800, 2000], [ 600, 1200, 1200, 2400]])
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 11
answers question: http://stackoverflow.com/q/48937018
upvote count: 11

http://stackoverflow.com/q/48943688
tagged with: python-3.x
has title: Parent module '' not loaded, cannot perform relative import
type: UnansweredQuestion
upvote count: 1
tagged with: django
tagged with: django-views
score: 1
type: Question
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48943773
has body: This is the project structure. --KP --app --api --views --mpg.py --gtt.py mpg.py: def cmcid(): ..... ..... gtt.py: from .mpg import cmcid def main(): variable = cmcid() if __name__ == "__main__": main() when I run from views directory, i.e kp/app/api/views$python gtt.py I get an error as: Parent module '' not loaded, cannot perform relative import Any help is appreciated. Thanks..
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/84804600
type: QuestionComment
has text: Yes a dict would serve the purpose
score: 0
comment on: http://stackoverflow.com/q/48897016
type: Comment

http://stackoverflow.com/q/48863186
score: -2
tagged with: ceil
accepted answer: http://stackoverflow.com/a/48863258
has body: I'm getting a number in my software and I would like to apply a process if this number is a decimal number. I would like to round my number to the upper entire number. For example : Get number --&gt; expected 1.3 --&gt; 2 1.7 --&gt; 2 2.0 --&gt; 2 2.1 --&gt; 3 Is it possible to create something like this ? I'm looking for splitting function : x = 3.4 x1 = int(round(x)) returns : 3 and not 4 Thank you by advance, I'm looking if I don't find a solution to my issue.
favorite count: 0
has comment: http://stackoverflow.com/comment/84729475
has comment: http://stackoverflow.com/comment/84729508
has answer: http://stackoverflow.com/a/48863620
linked to: http://stackoverflow.com/q/4518641
upvote count: 1
tagged with: python
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48863620
has comment: http://stackoverflow.com/comment/84729476
has comment: http://stackoverflow.com/comment/84729584
has comment: http://stackoverflow.com/comment/84729488
downvote count: 3
has comment: http://stackoverflow.com/comment/84729490
type: Question
has title: Python : round a decimal number
answer count: 2
has answer: http://stackoverflow.com/a/48863258

http://stackoverflow.com/q/48862002
tagged with: python
tagged with: python-3.x
has body: I am segregating object type columns as below: non_num_cols = df.select_dtypes(['object']).columns Now, my non_num_cols contain values like ['education', 'capital-gain', 'race', 'sex', 'classification'] I want to convert these with cat.codes() as in the below example: df.education = df.education.astype('category').cat.codes However, I want to do this using a "for" loop. The closest I've been able to get to this is: df[non_num_cols] = df[non_num_cols].apply(lambda x: x.astype('category')) But, I cannot use the .cat.codes() with this. It throws TypeError: ("'Series' object is not callable", 'occurred at index education') Any suggestions?
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84727028
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84727966
has answer: http://stackoverflow.com/a/53197113
has title: using .cat.codes() within a for loop
type: Question

http://stackoverflow.com/q/48927232
has comment: http://stackoverflow.com/comment/84895168
tagged with: python
tagged with: excel
has comment: http://stackoverflow.com/comment/84865595
has title: Python: Reproduce nested Excel Pivot table in python
downvote count: 1
has comment: http://stackoverflow.com/comment/84889596
type: UnansweredQuestion
tagged with: pandas
upvote count: 0
answer count: 1
has body: Question: Is it possible to display pandas report in exactly same format like excel? Current situation: I am trying to automate excel report using python. Excel report is in following format: I am using below code to generate pivot table in pandas: import pandas as pd import numpy as np df = pd.read_excel("sales-funnel.xlsx") table = pd.pivot_table(df,index=["Manager","Rep","Product"], values=["Price","Quantity"], aggfunc=[np.sum],fill_value=0)` I would like to get report similar to excel due to huge size of data. Pandas report will be difficult to analyze in excel. Thanks
has answer: http://stackoverflow.com/a/48937506
favorite count: 0
score: -1
type: Question
tagged with: pivot-table

http://stackoverflow.com/comment/84620041
comment on: http://stackoverflow.com/q/48808277
type: Comment
type: QuestionComment
score: 0
has text: @user8072518 PM77-1's "solution" is the worst possible solution. Don't do that, read the doc for the sqlite3 module and the two answers below (and Stev's comment). Use placeholders and your db-api connector will take care of sanitizing, escaping etc.

list
type: Tag
tags question: http://stackoverflow.com/q/48961268
tags question: http://stackoverflow.com/q/48853391
tags question: http://stackoverflow.com/q/48857500
tags question: http://stackoverflow.com/q/48871785
tags question: http://stackoverflow.com/q/48957150
tags question: http://stackoverflow.com/q/48853277
tags question: http://stackoverflow.com/q/48919015
tags question: http://stackoverflow.com/q/48961284
tags question: http://stackoverflow.com/q/48938505
tags question: http://stackoverflow.com/q/48855415
tags question: http://stackoverflow.com/q/48816854
tags question: http://stackoverflow.com/q/48919882
tags question: http://stackoverflow.com/q/48884147
tags question: http://stackoverflow.com/q/48895796
tags question: http://stackoverflow.com/q/48844489
tags question: http://stackoverflow.com/q/48898913
tags question: http://stackoverflow.com/q/48866017
tags question: http://stackoverflow.com/q/48918175
tags question: http://stackoverflow.com/q/48808193
tags question: http://stackoverflow.com/q/48896856
tags question: http://stackoverflow.com/q/48807953
tags question: http://stackoverflow.com/q/48854634
tags question: http://stackoverflow.com/q/48856989
tags question: http://stackoverflow.com/q/48810557
tags question: http://stackoverflow.com/q/48907446
tags question: http://stackoverflow.com/q/48915456
tags question: http://stackoverflow.com/q/48954408
tags question: http://stackoverflow.com/q/48815303
tags question: http://stackoverflow.com/q/48911063
tags question: http://stackoverflow.com/q/48916154
tags question: http://stackoverflow.com/q/48903079
tags question: http://stackoverflow.com/q/48845560
tags question: http://stackoverflow.com/q/48858072
tags question: http://stackoverflow.com/q/48829494
tags question: http://stackoverflow.com/q/48857491
tags question: http://stackoverflow.com/q/48953042
tags question: http://stackoverflow.com/q/48909056
tags question: http://stackoverflow.com/q/48842890
tags question: http://stackoverflow.com/q/48849334
tags question: http://stackoverflow.com/q/48942243
tags question: http://stackoverflow.com/q/48860654
tags question: http://stackoverflow.com/q/48930068
tags question: http://stackoverflow.com/q/48816332
tags question: http://stackoverflow.com/q/48901347
tags question: http://stackoverflow.com/q/48932732
tags question: http://stackoverflow.com/q/48820866
tags question: http://stackoverflow.com/q/48820459
tags question: http://stackoverflow.com/q/48955868
tags question: http://stackoverflow.com/q/48962205
tags question: http://stackoverflow.com/q/48845435
tags question: http://stackoverflow.com/q/48935831
tags question: http://stackoverflow.com/q/48835397
tags question: http://stackoverflow.com/q/48902830
tags question: http://stackoverflow.com/q/48959796
tags question: http://stackoverflow.com/q/48959183
tags question: http://stackoverflow.com/q/48811213
tags question: http://stackoverflow.com/q/48919034
tag name: list
tags question: http://stackoverflow.com/q/48922334
tags question: http://stackoverflow.com/q/48843120
tags question: http://stackoverflow.com/q/48835428
tags question: http://stackoverflow.com/q/48894087
tags question: http://stackoverflow.com/q/48820909
tags question: http://stackoverflow.com/q/48927318
tags question: http://stackoverflow.com/q/48929610
tags question: http://stackoverflow.com/q/48873107
tags question: http://stackoverflow.com/q/48898319
tags question: http://stackoverflow.com/q/48939904
tags question: http://stackoverflow.com/q/48847966
tags question: http://stackoverflow.com/q/48827614
tags question: http://stackoverflow.com/q/48928882
tags question: http://stackoverflow.com/q/48943425
tags question: http://stackoverflow.com/q/48829227
tags question: http://stackoverflow.com/q/48944290
tags question: http://stackoverflow.com/q/48945506
tags question: http://stackoverflow.com/q/48941964
tags question: http://stackoverflow.com/q/48902905
tags question: http://stackoverflow.com/q/48805035
tags question: http://stackoverflow.com/q/48848888

http://stackoverflow.com/q/48921374
downvote count: 1
accepted answer: http://stackoverflow.com/a/48921448
favorite count: 0
possible better answer: http://stackoverflow.com/a/48921407
has answer: http://stackoverflow.com/a/48921743
has answer: http://stackoverflow.com/a/48921407
tagged with: python
has answer: http://stackoverflow.com/a/48921448
answer count: 4
has title: Round() not working
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84849022
type: Question
has answer: http://stackoverflow.com/a/48921410
has comment: http://stackoverflow.com/comment/84849017
tagged with: rounding
upvote count: 2
tagged with: numpy
has body: D1_inv Out[23]: [0.024799999999999999, 0.029600000000000001, 0.035799999999999998] I'm trying to round these figures upto 4 decimal places. I've used this: for i in D1_inv: round(i,4) But the output remains the same as above. Can somebody help me here?
tagged with: arrays

http://stackoverflow.com/comment/84795267
type: QuestionComment
comment on: http://stackoverflow.com/q/48865801
score: 0
has text: There is no deviations in this regards with pandas between both engines.. is it different for dask ?
type: Comment

http://stackoverflow.com/q/48812198
has comment: http://stackoverflow.com/comment/86856784
score: 11
answer count: 2
has title: calculate Exponential Moving Average with pandas
tagged with: pandas
downvote count: 0
has body: I try to calculate ema with pandas but the result is not good. I try 2 techniques to calculate : The first technique is the panda's function ewn: window = 100 c = 2 / float(window + 1) df['100ema'] = df['close'].ewm(com=c).mean() But the last result of this function gives. 2695.4 but the real result is 2656.2 The second technique is window = 100 c = 2 / float(window + 1) df['100sma'] = df['close'].rolling(window).mean() df['100ema'] = (c * df['close']) + ((1 - c) * df['100sma']) The result is 2649.1 it's closer than first technique but is always not good The sma function give the good result ** EDIT ** The response is df['100ema'] = pd.Series.ewm(df['close'], span=window).mean()
favorite count: 0
has answer: http://stackoverflow.com/a/49700271
tagged with: python
upvote count: 11
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49700271
type: Question
possible better answer: http://stackoverflow.com/a/57724750
has answer: http://stackoverflow.com/a/57724750

http://stackoverflow.com/comment/107580622
type: Comment
has text: @JanPisl: Like I said, it's pointless and incompatible with Python 3, and jbch has already pointed out better alternatives.
type: AnswerComment
comment on: http://stackoverflow.com/a/48835377
score: 0

http://stackoverflow.com/a/48937765
answers question: http://stackoverflow.com/q/48937592
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: I recommend you to use elif function right = 0 left = 0 if(left &gt; right): print 'doing task 1' elif left ==0 and right == 0: print 'doing task 1' else: print 'doing task2'

http://stackoverflow.com/q/48903221
answer count: 2
downvote count: 0
favorite count: 0
tagged with: hash
tagged with: python
has body: I want to create an app where if a person would like to apply working for my company, I'll create an entry in my app and I'll send them a unique URL where it lead to a form page, I wanted the URL to be hashed, but I'm not quite sure how to do this. Below is my code : view.py : def applicant_email_view(request): form = ApplicantEmailForm(request.POST or None) if form.is_valid(): inst = form.save(commit=False) subject = 'Applicant Form' text_content = 'Hola' html_content = """ http://127.0.0.1:8080/hiring/application_form/ """ to = [inst.applicant_email] send_email(subject, text_content, html_content, to) inst.save() return render(request, 'hiring/applicant_email.html', {'form': form}) def application_form_view(request): form = JobApplicationForm(request.POST or None, request.FILES or None) if form.is_valid(): inst = form.save(commit=False) inst.save() context = {'form': form} return render(request, 'hiring/application_form.html', context=context) def send_email(subject, text_content, html_content, to): from_email = 'test@testing.studio' footer = """ Do not reply to this email. This is automated email notification from LemonCORE. """ email_body = html_content + footer msg = EmailMultiAlternatives(subject, text_content, from_email, to) msg.attach_alternative(email_body, "text/html") msg.send() url.py: url(r'^hiring/application_email/$', applicant_email_view, name='application_email_view'), url(r'^hiring/application_form/$', application_form_view, name='application_form_view'),
upvote count: 3
has answer: http://stackoverflow.com/a/48903869
type: UnansweredQuestion
tagged with: django
score: 3
tagged with: sha1
has answer: http://stackoverflow.com/a/48903821
has title: Python create a unique hash/encrypted url
type: Question

http://stackoverflow.com/a/65939280
score: 3
has comment: http://stackoverflow.com/comment/122514137
upvote count: 4
has comment: http://stackoverflow.com/comment/116586770
has comment: http://stackoverflow.com/comment/116586419
answers question: http://stackoverflow.com/q/48829993
type: Answer
downvote count: 1
has body: just want to add scala spark version of @ndricca´s answer in case anyone needs it: val data = Seq(("a", 5,"c"), ("a",8,"d"),("a",7,"e"),("b",1,"f"),("b",3,"g")) val df = data.toDF("A","B","C") df.show() +---+---+---+ | A| B| C| +---+---+---+ | a| 5| c| | a| 8| d| | a| 7| e| | b| 1| f| | b| 3| g| +---+---+---+ val rightdf = df.groupBy("A").max("B") rightdf.show() +---+------+ | A|max(B)| +---+------+ | b| 3| | a| 8| +---+------+ val resdf = df.join(rightdf, df("B") === rightdf("max(B)"), "leftsemi") resdf.show() +---+---+---+ | A| B| C| +---+---+---+ | a| 8| d| | b| 3| g| +---+---+---+

http://stackoverflow.com/comment/96228924
score: 0
type: AnswerComment
has text: @MehrdadPedramfar I don't know about his code so I just want give some info related to his code and I don't want to add something additional in it..... And he is inheriting AbstractUser class so, that username field will directly make an impact on the Django username field.... This is it
comment on: http://stackoverflow.com/a/54720080
type: Comment

http://stackoverflow.com/a/48952179
accepted answer of: http://stackoverflow.com/q/48907523
upvote count: 1
has comment: http://stackoverflow.com/comment/84929419
answers question: http://stackoverflow.com/q/48907523
has body: I don't think it's unsafe to have stamp.save() in PUT method because by definition it supposes to alter object's value. For returning only relevant stampcards, you could just add stampcard to a set like this class StampUpdateView(APIView): def get_object(self, uuid): try: return Stamp.objects.get(uuid=uuid) except Stamp.DoesNotExist(): raise Http404 def put(self, request, *args, **kwargs): stampcard_set = set() for stamp_data in request.data: stamp = self.get_object(stamp_data['stamp_uuid']) user_stampcard = request.user.stampcard_set.exclude(done=True).filter(stampcardformat=stamp.stampcardformat) if user_stampcard.exists(): stampcard = user_stampcard.earliest('timestamp') else: stampcard = Stampcard(stampcardformat=stamp.stampcardformat, user=request.user) stampcard.save() stamp.stampcard = stampcard stamp.save() if stampcard.stamp_set.count() == stampcard.stampcardformat.limit: stampcard.done = True stampcard.save() stampcard_set.add(stampcard) stampcard_serializer = StampcardSerializer(stampcard_set, many=True) return Response(stampcard_serializer.data) This way it doesn't matter if returning stampcards are already done or not. Also note that I move down limit checking lines in your code to be after when stamp was saved because if limit was set to 1, stampcard will have to be set as done immediately after a stamp was added.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/a/48835782
has comment: http://stackoverflow.com/comment/84676590
has comment: http://stackoverflow.com/comment/84676684
has comment: http://stackoverflow.com/comment/84784428
type: Answer
has comment: http://stackoverflow.com/comment/84676711
has comment: http://stackoverflow.com/comment/84676913
has comment: http://stackoverflow.com/comment/84784345
score: 2
upvote count: 3
has comment: http://stackoverflow.com/comment/84676413
accepted answer of: http://stackoverflow.com/q/48835481
has comment: http://stackoverflow.com/comment/84785617
downvote count: 1
answers question: http://stackoverflow.com/q/48835481
has comment: http://stackoverflow.com/comment/84677037
has comment: http://stackoverflow.com/comment/84677010
has body: This method uses finditer to find all locations of \d+\.\d+, then tests whether the match was numerically greater than the previous. If the test is true it appends the index to the indices array. The last line uses list comprehension as taken from this answer to split the string on those given indices. Original Method This method ensures the previous match is smaller than the current one. This doesn't work sequentially, instead, it works based on number size. So assuming a string has the numbers 1.1, 1.2, 1.4, it would split on each occurrence since each number is larger than the last. See code in use here import re indices = [] string = "1.3 Hello how are you 1.4 I am fine, thanks 1.2 Hi There 1.5 Great!" regex = re.compile(r"\d+\.\d+") lastFloat = 0 for m in regex.finditer(string): x = float(m.group()) if lastFloat &lt; x: lastFloat = x indices.append(m.start(0)) print([string[i:j] for i,j in zip(indices, indices[1:]+[None])]) Outputs: ['1.3 Hello how are you ', '1.4 I am fine, thanks 1.2 Hi There ', '1.5 Great!'] Edit Sequential Method This method is very similar to the original, however, on the case of 1.1, 1.2, 1.4, it wouldn't split on 1.4 since it doesn't follow sequentially given the .1 sequential separator. The method below only differs in the if statement, so this logic is fairly customizable to whatever your needs may be. See code in use here import re indices = [] string = "1.3 Hello how are you 1.4 I am fine, thanks 1.2 Hi There 1.5 Great!" regex = re.compile(r"\d+\.\d+") lastFloat = 0 for m in regex.finditer(string): x = float(m.group()) if (lastFloat == 0) or (x == round(lastFloat + .1, 1)): lastFloat = x indices.append(m.start(0)) print([string[i:j] for i,j in zip(indices, indices[1:]+[None])])
has comment: http://stackoverflow.com/comment/84676731
type: AcceptedAnswer

http://stackoverflow.com/a/48958519
has body: You need to do integer division like: Code: prod // a Why: The construct: int(prod / a) does a floating point division, then converts to an int. This loses some precision. Test Code: a, b = 226553150, 1023473145 prod = a * b while b: a, b = b, a % b print(int(prod / a)) print(prod // a) Results: 46374212988031352 46374212988031350
answers question: http://stackoverflow.com/q/48958492
score: 0
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48958492

http://stackoverflow.com/comment/84703611
has text: @Deadlock It doesn't change text in Label
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48849704
type: QuestionComment

http://stackoverflow.com/q/48914050
tagged with: discord.py
has title: Keep getting syntax error around async def on_ready(): whilst making discord bot
score: 5
has answer: http://stackoverflow.com/a/51576570
has comment: http://stackoverflow.com/comment/86306070
answer count: 1
tagged with: discord
has comment: http://stackoverflow.com/comment/84835157
has body: I've been learning python for a little bit and decided to take what I've learnt and build a discord bot to test my abilities. I've coded everything and it looks fine to me (which doesn't mean much, I'm sure) but I get a code for syntax error every time I try to run it. So, I scaled it back to the bare minimum and it still won't work. I've looked through a lot of questions and I see that this usually happens when you're not using an updated version of Python, but I've triple checked that I am, indeed, running Python 3.6.4. Here's what I have: import discord import discord.ext.commands from discord.ext.commands import Bot import asyncio bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print ("Bot Online!") print (bot.user.name) bot.run("token was here") and when I run it through Python Launcher, this is my error: Kalyns-MacBook-Air:~ kalynwoodbury$ cd '/Users/kalynwoodbury/Desktop/bot2/' &amp;&amp; '/usr/bin/pythonw' '/Users/kalynwoodbury/Desktop/bot2/Bot1.py' &amp;&amp; echo Exit status: $? &amp;&amp; exit 1 File "/Users/kalynwoodbury/Desktop/bot2/Bot1.py", line 9 async def on_ready(): ^ SyntaxError: invalid syntax Kalyns-MacBook-Air:bot2 kalynwoodbury$ What am I doing wrong? EDIT: The application says Python 3.6. Yesterday I uninstalled it and downloaded it again, making sure to press 3.6.4 and the installer said Python 3.6.4. I have never been so sure of anything in my life. Making sure I had the right version was the absolute first thing I looked for. EDIT: If I try to use python3 bot.py it gives me the same error code, but for that line.
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84836488
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/84835077
tagged with: bots
downvote count: 1
linked to: http://stackoverflow.com/q/43948454
type: Question
has comment: http://stackoverflow.com/comment/84834750

http://stackoverflow.com/comment/84702578
has text: ok it works if i saved my file with utf-8 encoding , but how can works if i saved it with ANSI encoding ?
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48849448

http://stackoverflow.com/a/48872089
type: AcceptedAnswer
upvote count: 2
has comment: http://stackoverflow.com/comment/84748460
type: Answer
has comment: http://stackoverflow.com/comment/84748424
score: 2
accepted answer of: http://stackoverflow.com/q/48872025
has comment: http://stackoverflow.com/comment/84748905
answers question: http://stackoverflow.com/q/48872025
has comment: http://stackoverflow.com/comment/84748578
has comment: http://stackoverflow.com/comment/84748507
has comment: http://stackoverflow.com/comment/84748661
downvote count: 0
has comment: http://stackoverflow.com/comment/84748341
has comment: http://stackoverflow.com/comment/84748459
has body: I think you are trying to call a string as a function here, and that isn't possible. Specifically, 'CmSelectionCriteria'() Isn't valid. "abc"() causes the same error. You can't execute a call on a string. If CmSelectionCriteria is a function you have defined somewhere else, remove the quotes.
has comment: http://stackoverflow.com/comment/84748133

http://stackoverflow.com/q/48889144
has comment: http://stackoverflow.com/comment/84784636
has comment: http://stackoverflow.com/comment/84786082
tagged with: python
answer count: 0
tagged with: global-variables
tagged with: import
type: Question
has comment: http://stackoverflow.com/comment/84784313
has body: My project has the following structure: A coordinator script that imports 2 modules and makes a thread for the main function of each. I have a variable I need to share between the two imported modules. Module 1 writes it, and Module 2 reads it (asynchronically). Since read and write are atomic, it should be thread safe. In Python though, global variables are module scoped, therefore, a global variable approach does not work. My intention is to add this shared variable to my config module and have both modules import it (it's probably super dirty, but my Python knowledge is limited). I think this would at least let me work around scoping, but I don't know if atomicity is maintained if the shared variable is imported. Thanks!
has comment: http://stackoverflow.com/comment/84786194
tagged with: python-2.7
score: 0
has title: Python2.7 - Is writing to an imported variable atomic?
tagged with: atomic
type: UnansweredQuestion

http://stackoverflow.com/a/49061241
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48922679
accepted answer of: http://stackoverflow.com/q/48922679
type: AcceptedAnswer
downvote count: 0
has body: The elements in ttk use the flyweight pattern and do not store values themselves. Instead the style contains all the values used by the elements associated with the widget layout. So all elements that use a background configuration value read the same value out of the current widget style. In cases where a custom color is supported a different option name is used. Hence the trough background color is read from the troughcolor option. For buttons there is a field for the button itself as background gets used for the area behind the button under the focus ring (if visible). If you really wanted to get finer control you either have to code a new theme element engine or you can use the image element engine to define a new element using images. There are some tcl examples of image based themes imported to github if you want to try that. However, the point of the ttk themeing is to try and use the system provided look and feel as much as possible and avoid having programmers customise the heck out of the UI. The more customisation you make the more likely it is to look crap on someone else's system as a general rule.
type: Answer

http://stackoverflow.com/q/48882366
has answer: http://stackoverflow.com/a/48882604
type: Question
score: 1
upvote count: 2
downvote count: 1
answer count: 1
favorite count: 0
has title: how to read xml files in python if the encoding is different than UTF-8
tagged with: python
tagged with: file-handling
has comment: http://stackoverflow.com/comment/84769034
linked to: http://stackoverflow.com/q/5963269
has body: I am trying to read an xml file with different encoding. In case of UTF-8 it is working fine but in case of other formats like GB18030 or BIG5, it is throwing error like multi-byte encoding are not supported. Please suggest a solution for this. Thanks in advance.
type: UnansweredQuestion

http://stackoverflow.com/comment/84693450
type: AnswerComment
has text: @JNg ty, I just read that with `df = pd.read_csv('test.csv')`
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48843769

http://stackoverflow.com/comment/84716768
comment on: http://stackoverflow.com/a/48855655
type: AnswerComment
score: 0
type: Comment
has text: Typing just set path, followed by restarting my computer worked!!! The file converted! Thank you so much; I've been working on this for quite a while. Thank you!

http://stackoverflow.com/comment/121511967
has text: I understand that the question does not refer to exogenous variables. I think it refers to the case the time serie to predict is trucated, so instead of a long time series you have a set of shorter time series. Example: Imagine data each minute in a machine that is operating 9AM-5PM and then it is switched off, in this case the jump between afternoon and morning does not fit as a single time series since there isn't continuity.
comment on: http://stackoverflow.com/a/49747390
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48822061
tagged with: pandas
has comment: http://stackoverflow.com/comment/84647359
favorite count: 0
possible better answer: http://stackoverflow.com/a/48822207
tagged with: python
accepted answer: http://stackoverflow.com/a/48822092
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84647361
has body: I have a problem with an if statement with my data from the dataframe. Somehow performing an if statement for years > 3years somehow all values larger than 9Y are not showing up and it is not clear why. The output looks like the following: 4Y 5Y 6Y 7Y 8Y 9Y 4Y 5Y 6Y 7Y 8Y 9Y My code looks like the following: import pandas as pd df = pd.DataFrame([ ['2015-02-09', '1Y', 2.241], ['2015-02-09', '1Y', 2.413], ['2015-02-09', '2Y', 2.228], ['2015-02-09', '2Y', 2.289], ['2015-02-09', '3Y', 2.263], ['2015-02-09', '3Y', 2.371], ['2015-02-09', '4Y', 2.413], ['2015-02-09', '5Y', 2.487], ['2015-02-09', '6Y', 2.578], ['2015-02-09', '7Y', 2.655], ['2015-02-09', '8Y', 2.74959], ['2015-02-09', '9Y', 2.81729], ['2015-02-09', '10Y', 2.853], ['2015-02-09', '12Y', 2.942], ['2015-02-09', '15Y', 3.047], ['2015-02-09', '20Y', 3.165], ['2015-02-09', '25Y', 3.225], ['2015-02-09','30Y', 3.225], ['2015-02-09', '1Y', 9.5], ['2015-02-09', '2Y', 8.75], ['2015-02-09', '3Y', 8.5], ['2015-02-09', '4Y', 8.13], ['2015-02-09', '5Y', 7.75], ['2015-02-09', '6Y', 7.63], ['2015-02-09', '7Y', 7.5], ['2015-02-09', '8Y', 7.45], ['2015-02-09','9Y', 7.25], ['2015-02-09', '10Y', 7.125], ['2015-02-09', '12Y', 7.08], ['2015-02-09', '15Y', 7.04], ['2015-02-09', '20Y', 6.435], ['2015-02-09', '25Y', 5.83], ['2015-02-09', '30Y', 5.45] ], columns=['date', 'year', 'values']) for index, row in df.iterrows(): if row['year'] &gt; '3Y': print(row['year'])
downvote count: 2
upvote count: 1
tagged with: loops
has answer: http://stackoverflow.com/a/48822092
type: Question
has answer: http://stackoverflow.com/a/48822207
tagged with: dataframe
score: -1
has title: If statement string data from dataframe does not work for larger years
has comment: http://stackoverflow.com/comment/84647429
answer count: 2

http://stackoverflow.com/q/48832344
has comment: http://stackoverflow.com/comment/84668926
answer count: 1
accepted answer: http://stackoverflow.com/a/50609180
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84668875
has title: How to remove the remains of python 3.7?
type: AnsweredQuestion
tagged with: uninstallation
has comment: http://stackoverflow.com/comment/84669159
has comment: http://stackoverflow.com/comment/88223585
type: Question
has answer: http://stackoverflow.com/a/50609180
has body: I have accidentally removed several parts of python and now am trying to start again... The installer says that 57 files are still on my PC and I cannot find them. Does anyone know how to get a copy of the uninstaller? As it should find the remaining files.

http://stackoverflow.com/q/48891854
tagged with: tensorflow
type: Question
tagged with: tensorflow-transform
has body: Whenever I try to import tensorflow-transform on an mlengine job I get the following issue: Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "main", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/root/.local/lib/python2.7/site-packages/trainer/task.py", line 15, in from tensorflow.contrib.boosted_trees.python.ops import quantile_ops ImportError: No module named boosted_trees.python.ops Tensorflow transform runs fine on dataflow but when I try to train the model the above error appears. Tensorflow in general seems to work fine on mlengine, but I do run into issues if I try to just import boosted_trees.python.ops. I'm using tf 1.4 and tft 0.4.0. The code that I am running is a slightly modified version of the cloudml-samples reddit_tft example.
has title: Issues importing tf Transform on cloud ml
has answer: http://stackoverflow.com/a/49080698
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84790698
favorite count: 0
tagged with: google-cloud-ml
type: UnansweredQuestion
tagged with: python
score: 1
upvote count: 1

http://stackoverflow.com/a/58731540
has body: Here's a way to do it with the new version of the SDK (12.0.0): from azure.storage.blob import BlobClient blob = BlobClient(account_url="https://&lt;account_name&gt;.blob.core.windows.net" container_name="&lt;container_name&gt;", blob_name="&lt;blob_name&gt;", credential="&lt;account_key&gt;") with open("example.csv", "wb") as f: data = blob.download_blob() data.readinto(f) See here for details.
downvote count: 0
has comment: http://stackoverflow.com/comment/133886833
has comment: http://stackoverflow.com/comment/106322211
type: Answer
has comment: http://stackoverflow.com/comment/108597007
upvote count: 13
score: 13
answers question: http://stackoverflow.com/q/48881228
has comment: http://stackoverflow.com/comment/108580306
has comment: http://stackoverflow.com/comment/106287902

http://stackoverflow.com/q/48846257
has comment: http://stackoverflow.com/comment/84697745
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48846304
favorite count: 0
tagged with: python-3.x
tagged with: python
has title: Mapping function across numpy matrix
upvote count: 6
linked to: http://stackoverflow.com/q/35215161
score: 6
has answer: http://stackoverflow.com/a/48846304
type: AnsweredQuestion
has body: Is there a way to map a function to every value in a numpy array easily? I've done it before by splitting it into lists, using list comprehension and remaking the matrix but it seems there must be an easier way.
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84712812

http://stackoverflow.com/q/48883843
tagged with: python
has comment: http://stackoverflow.com/comment/84772679
answer count: 0
linked to: http://stackoverflow.com/q/48049087
has body: I am trying use a NLTK function convert Text data into numerical form for SKlearn.The data that I am using Basically short txt data . Input NO 6 JALAN ASTAKA U8/82 SEKSYEN U8 BUKIT JELUTONG MST GOLF PLAZA NO 8 JALAN SS13/5 Expected Output no jalan astaka u seksyen u bukit jelutong mst golf plaza no jalan ss My code user_defined_stop_words = ['kwun','tong'] i = nltk.corpus.stopwords.words('english') j = list(string.punctuation) + user_defined_stop_words newstopwords = set(i).union(j) def preprocess(x): x = re.sub('[^a-z\s]', '', x.lower()) # get rid of noise x = [w for w in x.split() if w not in set(newstopwords)] # remove stopwords return ' '.join(x) data['Clean_addr'] = data['Adj_Addr'].apply(preprocess) Error ~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\series.py in apply(self, func, convert_dtype, args, **kwds) 2353 else: 2354 values = self.asobject -&gt; 2355 mapped = lib.map_infer(values, f, convert=convert_dtype) 2356 2357 if len(mapped) and isinstance(mapped[0], Series): pandas/_libs/src\inference.pyx in pandas._libs.lib.map_infer() &lt;ipython-input-55-3e3b1d8472ed&gt; in preprocess(x) 5 6 def preprocess(x): ----&gt; 7 x = re.sub('[^a-z\s]', '', x.lower()) # get rid of noise 8 x = [w for w in x.split() if w not in set(newstopwords)] # remove stopwords 9 return ' '.join(x) AttributeError: 'float' object has no attribute 'lower' How to fix this.
has comment: http://stackoverflow.com/comment/84772535
has comment: http://stackoverflow.com/comment/84772240
has comment: http://stackoverflow.com/comment/84772619
type: Question
has comment: http://stackoverflow.com/comment/84772070
duplicate of: http://stackoverflow.com/q/48049087
tagged with: nltk
score: 0
tagged with: pandas
has title: Getting 'float' object has no attribute 'lower' Error while using NLTK
has comment: http://stackoverflow.com/comment/84772291
type: UnansweredQuestion

http://stackoverflow.com/comment/84685717
type: AnswerComment
score: 0
type: Comment
has text: It says list of out range. I have updated the way my dataset looks
comment on: http://stackoverflow.com/a/48840788

http://stackoverflow.com/q/48934246
possible better answer: http://stackoverflow.com/a/48934466
has comment: http://stackoverflow.com/comment/84875118
has answer: http://stackoverflow.com/a/48934466
type: Question
has comment: http://stackoverflow.com/comment/84875177
score: 3
has comment: http://stackoverflow.com/comment/84875337
has comment: http://stackoverflow.com/comment/84875251
has comment: http://stackoverflow.com/comment/84875182
has answer: http://stackoverflow.com/a/48934598
has comment: http://stackoverflow.com/comment/84875695
has comment: http://stackoverflow.com/comment/84875145
downvote count: 1
has answer: http://stackoverflow.com/a/48934474
accepted answer: http://stackoverflow.com/a/48934474
has answer: http://stackoverflow.com/a/48934687
tagged with: string
has title: Split Python string into two on newline nearest the middle
favorite count: 0
has comment: http://stackoverflow.com/comment/84875238
tagged with: python
has comment: http://stackoverflow.com/comment/84875132
upvote count: 4
answer count: 4
type: AnsweredQuestion
has body: I have a string in python which is about 3900 character long. The string has multiple chars including new lines a bunch of times. For simplicity consider he following string: s = "this is a looooooooooooooooooooooooooong string which is \n split into \n a lot of \n new lines \n and I need to split \n it into roughly \n two halves on the new line\n" I would like to split the above string into roughly two halves on \n so expected result would be something like this : first part = "this is a looooooooooooooooooooooooooong string which is \n split into \n a lot of " second part = " new lines \n and I need to split \n it into roughly \n two halves on the new line\n" I have this python code : firstpart, secondpart = s[:len(s)/2], s[len(s)/2:] but obviously this splits the string into exact half on whatever char happens to be at that position.

http://stackoverflow.com/a/48843499
answers question: http://stackoverflow.com/q/48843335
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
score: 2
has body: I want to convert this time '23:59:05.823Z' to this format like '10:00 AM' looks like you are using ISO date time format. You could do something like this. &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; d = datetime.strptime("23:59:05.823Z", "%H:%M:%S.%fZ") &gt;&gt;&gt; d.strftime("%I:%M %p") '11:59 PM'
accepted answer of: http://stackoverflow.com/q/48843335

http://stackoverflow.com/comment/84734292
type: QuestionComment
has text: @MaxPowers, I'm also on 2.1.2. Maybe your machine is stronger? Would it matter if you increase the number of points to be plotted?
comment on: http://stackoverflow.com/q/48865396
score: 0
type: Comment

http://stackoverflow.com/a/48903320
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84812520
answers question: http://stackoverflow.com/q/48902955
has body: Split your search query and the title of your search result link into keywords. Starting from the tag search for maximum matches. Then hierarchically enter into the body tag until matches in parent== matches in child. Then pick up the child. Continue process until the matches in parent > matches in every child. Then extract the text in that element. Try using ranks with keywords and see the performance. If you are ok with information from single source you can use Wikipedia Api. Good Luck!
has comment: http://stackoverflow.com/comment/84813182
has comment: http://stackoverflow.com/comment/84813936

http://stackoverflow.com/comment/84732506
comment on: http://stackoverflow.com/q/48822897
score: 0
has text: Python 3.6.3, Ubuntu 16.04 & '0.22.0' please check if my answer seems like a plausible reason. Thanks!!@smci
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48816882
type: Answer
has comment: http://stackoverflow.com/comment/84638104
has comment: http://stackoverflow.com/comment/84639510
answers question: http://stackoverflow.com/q/48816693
upvote count: 2
has comment: http://stackoverflow.com/comment/84638331
has comment: http://stackoverflow.com/comment/84639313
score: 2
has comment: http://stackoverflow.com/comment/84638754
has comment: http://stackoverflow.com/comment/84639526
downvote count: 0
has body: Your code is much more complex than what it needs to be. You can use a for loop to achieve what you want. guess = ['1', '2', '3', '4'] answer = 2245 answer = str(answer) corr_place, wrong_place = 0, 0 for i, g in enumerate(guess): if g in answer: if g == answer[i]: corr_place += 1 else: wrong_place += 1 print("Correct position:", corr_place) print("Wrong position:", wrong_place) But a more Pythonic solution would be something that uses list comprehensions: guess = ['1', '2', '3', '4'] answer = 2245 answer = str(answer) results = [g == d for g, d in zip(guess, answer) if g in answer] corr = sum(results) print("Correct position:", corr) print("Wrong position:", len(results) - corr)
has comment: http://stackoverflow.com/comment/84639332
has comment: http://stackoverflow.com/comment/84639414
has comment: http://stackoverflow.com/comment/84637970

http://stackoverflow.com/q/48942454
tagged with: twitter
has comment: http://stackoverflow.com/comment/84891559
tagged with: social-networking
score: 0
has comment: http://stackoverflow.com/comment/84892363
has title: How to analyze/visualize twitter network of specific area?
tagged with: python
tagged with: python-3.x
answer count: 0
linked to: http://stackoverflow.com/q/5963269
type: UnansweredQuestion
tagged with: network-analysis
has body: I want to analyze or visualize overall twitter network of specific area(country or state). I know There are ways to analyze or visualize network of specific people through the method of who he/she is following and who are following back but i want to analyze overall twitter network of specific area. Background Research: There are ways to visualize your twitter network like discussed in this article: http://allthingsgraphed.com/2014/11/02/twitter-friends-network/ Moreover, you can also generate a network graph of twitter followers using python and networkX: http://mark-kay.net/2014/08/15/network-graph-of-twitter-followers/ There are also tools like Tweepsmap(http://tweepsmap.com/partners/Garin) available to get your twitter network of specific area But still the question is how to analyze/visualize overall twitter network of specific area ?
type: Question
has comment: http://stackoverflow.com/comment/84892025

http://stackoverflow.com/a/48819320
score: 0
has body: You have a lot of issues going on with your code. The equipo class seems good, although my spanish isn't good enough to figure out what most of the fields and functions do. For the Division class, I would recommend creating a dictionary with the teams as keys and their division points and total goals as a list for items. Once all the games are played you would convert it to a list, then sort it. You can also get rid of your matches field and just user itertools.combinations. It makes every unique combination of 2 teams. The class would look something like this: class Division: equipos = {equipo1: [0,0], equipo2: [0,0], equipo3: [0,0], equipo4: [0,0]} def __init__(self, e1, e2, e3, e4): self.equipo1 = e1 self.equipo2 = e2 self.equipo3 = e3 self.equipo4 = e4 def get1(self): return self.places[0] def get2(self): return self.places[1] def winner(self): #itertools.combinations(self.equipos.keys(), 2) basically makes a list of every unique pair of equipos. for m in itertools.combinations(self.equipos.keys(), 2): p = Partido(m[0], m[1]) p.tiempoPartido() p.scoreGoles() #increase the winners score by 1 equipos[p.getGanador()][0]+=1 #increase the winners goal count by goals scored equipos[p.getGanador()][1]+=p.getGoals(0) #increase the losers goal count by goals scored equipos[p.getVencido()][1]+=p.getGoals(1) self.places = equipos.items() #sorts by division points self.places.sort(key = lambda x: -x[0][0]) #sorts by goals scored self.places.sort(key = lambda x: -x[0][1]) You would need to implement a getGoals function in Partido to get the number of goals. I assumed you would do getGoals(0) for the winner's number of goals and getGoals(1) for loser's number of goals. You also need a getVencido (I think that is loser in Spanish?) function to return the losing team.
type: Answer
answers question: http://stackoverflow.com/q/48818659

amazon-mws
tags question: http://stackoverflow.com/q/48868480
type: Tag
tag name: amazon-mws

http://stackoverflow.com/q/48907107
has answer: http://stackoverflow.com/a/48907394
has answer: http://stackoverflow.com/a/48907338
has body: I want to extract several value using regular expression in python The string is id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld "NAA1, 4, WJQ, 13, HelloWorld" is the value what I want. At first time, I tried like that import re msg = "id : NAA1, priority : 4, location : WJQ, director : 13, text : HelloWorld" _id = re.search('id : (.*?),', msg) But I want all value using just one re pattern matching.
type: Question
has answer: http://stackoverflow.com/a/48907303
score: 0
has answer: http://stackoverflow.com/a/48907435
has comment: http://stackoverflow.com/comment/84819852
accepted answer: http://stackoverflow.com/a/48907303
favorite count: 0
has answer: http://stackoverflow.com/a/48907310
upvote count: 2
answer count: 5
downvote count: 2
tagged with: python
tagged with: regex
has comment: http://stackoverflow.com/comment/84819861
possible better answer: http://stackoverflow.com/a/48907310
type: AnsweredQuestion
has title: extract several value using Regular Expression in Python

http://stackoverflow.com/a/48929034
has comment: http://stackoverflow.com/comment/84864804
has comment: http://stackoverflow.com/comment/84864679
accepted answer of: http://stackoverflow.com/q/48928947
answers question: http://stackoverflow.com/q/48928947
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4
has body: Option 2 Use this for a list of numeric columns in an existing dataframe: cols = ['col1', 'col2', 'col3'] df1[cols] = df1[cols].apply(pd.to_numeric, errors='ignore', downcast='integer') The standard astype(int) is sub-optimal since it doesn't downcast by default. Option 1 As @AntonvBR mentions, ideally you want to read in series as downcasted integers, if at all possible. Then this separate conversion would not be necessary. For example, the dtype parameter of pd.read_excel takes a dictionary input: df = pd.read_excel('file.xlsx', dtype={'Col1': np.int8}) This will only work if you know your columns in advance.
downvote count: 0

http://stackoverflow.com/comment/115752939
comment on: http://stackoverflow.com/q/48960633
has text: @JosefZ Thanks for the sharing. Since I have updated the Python version already, the module seems not needed any more(see the "issue" in the github).
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84631118
type: Comment
comment on: http://stackoverflow.com/q/48813572
has text: ["Can Someone Help Me?" is not a valid SO question](https://meta.stackoverflow.com/questions/284236/why-is-can-someone-help-me-not-an-actual-question). This usually suggests that what you need is half an hour with a local tutor or walk through a tutorial, rather than Stack Overflow. The problem is one of problem analysis, not programming. How would you do it without a computer? Write down that process. When you get to converting those steps to code and get stuck, *then* you might have a Stack Overflow posting.
score: 4
type: QuestionComment

http://stackoverflow.com/q/48830968
tagged with: python
has title: Why does gdalinfo --version show different outputs when run on terminal as compared to when run through python?
type: AnsweredQuestion
score: 0
type: Question
has body: Why does gdalinfo --version show different outputs when run on terminal as compared to when run through python? Terminal: $ gdalinfo --version GDAL 2.2.3, released 2017/11/20 Python: import os os.system('gdalinfo --version') gives 6
has answer: http://stackoverflow.com/a/48924297
tagged with: gdal
answer count: 1
accepted answer: http://stackoverflow.com/a/48924297
tagged with: version

http://stackoverflow.com/a/48897279
upvote count: 1
has comment: http://stackoverflow.com/comment/84800356
has comment: http://stackoverflow.com/comment/84800192
score: -1
answers question: http://stackoverflow.com/q/48897252
has body: Since S,B, and m are integers, you want to put the correct formatting parameters like so: '{:d}'.format(S) Or in your case, print("Strike: {:d} Ball: {:d} Try: {:d} \n".format(S, B, m)) The :d is telling the format method that you want to convert an integer to a string. And since you put the numbers in order anyway, there's no need for the 0,1, and 2 you put into the brackets. Happy Coding!
downvote count: 2
type: Answer

http://stackoverflow.com/comment/84885747
has text: @wim I think that would be fine. Because I am then converting the list to a dictionary and only access the dictionary from code throughout the program since its values are seldom changed. So I want to populate it once and then access it many many times without hitting the DB again.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48939280
score: 0

http://stackoverflow.com/comment/84687791
type: QuestionComment
type: Comment
has text: [this](https://stackoverflow.com/questions/36484184/python-make-a-post-request-using-python-3-urllib) question may looks similar with this questions
comment on: http://stackoverflow.com/q/48841889
score: 0

http://stackoverflow.com/a/48892802
has body: You should be using shutil.rmtree to recursively delete directory: import shutil shutil.rmtree('/path/to/your/dir/') Answer to your question: Is os.removedirs and os.rmdir only used to delete empty directories? Yes, they can only be used to delete empty directories. Below is the description from official Python document which clearly stats that. os.rmdir(path, *, dir_fd=None) Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised. In order to remove whole directory trees, shutil.rmtree() can be used. os.removedirs(name) Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example, os.removedirs('foo/bar/baz') will first remove the directory 'foo/bar/baz', and then remove 'foo/bar' and 'foo' if they are empty. Raises OSError if the leaf directory could not be successfully removed.
answers question: http://stackoverflow.com/q/48892772
accepted answer of: http://stackoverflow.com/q/48892772
type: Answer
upvote count: 43
type: AcceptedAnswer
score: 43
downvote count: 0

http://stackoverflow.com/q/48891334
tagged with: date
has comment: http://stackoverflow.com/comment/84788589
type: Question
downvote count: 0
has title: python date not recognize with xlsxwriter
favorite count: 0
has comment: http://stackoverflow.com/comment/84788344
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84788420
upvote count: 1
tagged with: python
has body: I wonder how to do to write a date in a cell and make excel recognize it as a date. With the following Python code, using xlsxwriter module, I write dates in cells formatDate = workbook.add_format({'num_format': 'dd/mm/yy'}) if re.match('\d{2}\/\d{2}\/\d{4}', data): #print 'date:',data worksheet.write(row,col,data,formatDate) else: worksheet.write(row,col,data) But when I open Excel all the values are at the left of the cell. If I edit the value and press enter without any modification then its recognized as a date and Excel write it on the right of the cell. No calculation can be made while dates are not recognized. Can anyone help me on this issue ? Thanks
score: 1
tagged with: xlsxwriter

http://stackoverflow.com/comment/84645581
has text: Btw. I think you want to swap arguments of `append` and more importantly **reassign** to a. `np.append` does not work in-place.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48820876

http://stackoverflow.com/comment/84869881
comment on: http://stackoverflow.com/a/48931560
has text: yes i have done exactly like this. thanks as well
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84795265
has text: @DSM I take back everything I said above. Using `low` and `high` constant arrays instead of scalar values results in an almost 2x slowdown in the original `method2()`. Probably I was not careful and used the code from here as it was posted.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48888971

http://stackoverflow.com/comment/84634303
has text: "i'm trying to use list comprehension when possible" that is a bad idea. You should learn to use list-comprehensions *when appropriate*. I.E., when you are building a list with **no side effecs**, and perhaps most importantly, when it maintains/improves readability.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48815046

http://stackoverflow.com/q/48833488
answer count: 1
has comment: http://stackoverflow.com/comment/84671432
favorite count: 0
tagged with: python-3.x
has body: I would like to filter items out of one dictionary where that dictionary contains items of another dictionary. So, say that I have two dictionary's dict1 and dict2 where dict1 = { 1:{'account_id':1234, 'case':1234, 'date': 12/31/15, 'content': 'some content'}, 2:{'account_id':1235, 'case':1235, 'date': 12/15/15, 'content': 'some content'} } dict2 = { 1:{'account_id':1234, 'case':1234, 'date': 12/31/15, 'content': 'some different content'}, 2:{'account_id':4321, 'case':4321, 'date': 6/12/15, 'content': 'some different content'}, 3:{'account_id':1235, 'case':1235, 'date': 12/15/15, 'content': 'some different content'} } I would like to match on account_id, case and date and have the output be a third dictionary with matched entries from dict2 being 1 and 3. out = { 1:{'account_id':1234, 'case':1234, 'date': 12/31/15, 'content': 'some different content'}, 2:{'account_id':1235, 'case':1235, 'date': 12/15/15, 'content': 'some different content'} } How would I accomplish this? I am using Python 3.5
downvote count: 5
score: -4
tagged with: python
has comment: http://stackoverflow.com/comment/84671532
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84671705
type: Question
accepted answer: http://stackoverflow.com/a/48833837
has title: Filtering Items in dictionary
upvote count: 1
has answer: http://stackoverflow.com/a/48833837

http://stackoverflow.com/q/48898156
linked to: http://stackoverflow.com/q/39072433
tagged with: nuke
answer count: 1
downvote count: 0
tagged with: maya
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48902452
score: 2
type: AnsweredQuestion
upvote count: 2
has body: I'm developing universal tools that work across various CG software packages such as Maya, Houdini, Nuke, etc., and I'm wondering if there's a workflow for merging each software's custom interpreter into a single master interpreter inside a virtual environment? To elaborate: I know how create a custom environment for Maya development in PyCharm, but this only works with mayapy.exe as the interpreter. I'd ideally like to use a clean python.exe as my master interpreter, then add packages for each software in order to get completion working. Here's a gist of the script I've been working with. All it needs is PySide and Qt.py installed into a Python 2.7 venv to run. If I do all the steps from the first link (Maya dev in PyCharm) EXCEPT use mayapy.exe as the interpreter and instead use python.exe I've found that autocompletion actually works, but the script will not execute unless I'm using the mayaypy.exe as the interpreter. I guess my main problem is I'm not sure if this is even possible. And if it is possible I'm not sure what packages to use or how to find out what packages I need.
type: Question
tagged with: interpreter
tagged with: houdini
has title: Is it possible to develop across multiple software packages (Maya, Houdin, Nuke, etc) from a single master interpreter?
has answer: http://stackoverflow.com/a/48902452

http://stackoverflow.com/comment/84720659
type: QuestionComment
has text: Please read the answers in that question more carefully. There are multiple detailed and thoughtful answers besides the accepted one.
score: 0
comment on: http://stackoverflow.com/q/48858177
type: Comment

http://stackoverflow.com/q/48832639
has answer: http://stackoverflow.com/a/48833756
type: Question
tagged with: flask
has title: Render jupyter ipynb int html in Flask
answer count: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48834415
favorite count: 0
tagged with: jupyter-notebook
upvote count: 2
accepted answer: http://stackoverflow.com/a/48834415
has body: I'm a graduate student researcher, and I want to make a read-only index of all of my ipynb files that I and my colleagues can quickly search. I can convert ipynb to html using this command jupyter nbconvert --format=basic my_notebook.ipynb Then I get an html file that I can render with a flask server (with extra templates, css, table of contents, index, etc...). However, I don't want to manually convert all of the ipynb files into html files everytime I make/upgrade them. I'd rather have the Flask server search through a directory, find all of the ipynb files, and then show me a directory tree, and when I click on a notebook in my directory tree, do the ipynb -> notebook conversion and render the html. My question is: how do I convert a jupyter notebook file held in notebook_filename into html, and store that html in notebook_html_contents in Flask during runtime? Is there a better way than to do a Popen.subprocess? I understand the benefits of caching, but I'm going to be writing files probably twice as often as I read them. Having a bunch of html files will also clutter up my file structure and double the amount of memory I use.
tagged with: python
type: AnsweredQuestion
score: 2
possible better answer: http://stackoverflow.com/a/48833756

http://stackoverflow.com/q/48932579
has title: Django - passing argument to custom .save method
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48934883
upvote count: 1
tagged with: django
score: 1
has body: I have a custom .save method on my model. The model has a start_date and a last_edited value. If the difference between these values is more than 14 days, it should copy/clone itself on save (instead of saving). You probably already see the problem: infinite recursion. If the clone saves itself, the values will still differ 14 days and the whole copy process will start anew. Therefore I want to to pass these copies a 'copy' argument in their .save parameter, in order to prevent them from triggering the copy process themselves. To this end I've written the following code: def save(self, *args, **kwargs): #check if a submission is older than the 'create a new one' threshold #Create a new one if that is the case delta = self.last_edited - self.start_date print(args) print(kwargs) if 'copy' in kwargs or 'copy' not in args: print('cloning!') if delta.days &gt;= 14: clone = self clone.pk = None clone.save('copy') super(AssessmentSubmission, self).save(*args, **kwargs) However, for some reason clone.save(copy) does not pass the 'copy' variable to the .save method. I even added some print statements to print all args and kwarg arguments, but both return empty lists/ dicts. Does anyone know what I am doing wrong?
tagged with: django-forms
type: Question
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/84653754
type: QuestionComment
comment on: http://stackoverflow.com/q/48825011
has text: is that two yaml files ?
score: 0
type: Comment

http://stackoverflow.com/comment/84776069
type: Comment
score: 0
type: AnswerComment
has text: But I am trying to do it using recursive calls.. I will try to use recursive calls in your code.. If I could not do I will get back to you.. Thank you so much for the help
comment on: http://stackoverflow.com/a/48885342

http://stackoverflow.com/comment/88211574
type: Comment
type: QuestionComment
has text: Did you ever figure out a way to get this to work?
score: 1
comment on: http://stackoverflow.com/q/48909132

http://stackoverflow.com/comment/84676789
type: Comment
has text: The string is not from a file. It was an output of a result. `partStr = unicode(part_entry[5])`. Please have a look on the URL.
score: 0
comment on: http://stackoverflow.com/q/48835731
type: QuestionComment

http://stackoverflow.com/q/48884116
has comment: http://stackoverflow.com/comment/84772613
tagged with: python
has title: Csv to Json :- Using csv.extend function but getting extra line character while concatenating [
accepted answer: http://stackoverflow.com/a/48886872
downvote count: 3
upvote count: 1
has comment: http://stackoverflow.com/comment/84772923
type: Question
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json
has body: I have one csv file with below content signOffDate,fundEntityType,fundId,benchmarkIds,source,returnType 30-Sep-17,ENTITY_ID,44182,MAN,IP,TR 30-Nov-17,ENTITY_ID,44182,VAN,IP,TR I want to convert in into json file having content using python { "fundId": [ "44182"], "signOffDate": "30-Sep-17", "fundEntityType": "ENTITY_ID", "source": "IP", "returnType": "TR", "benchmarkIds": [ "MAN"] }, { "fundId": ["44182"], "signOffDate": "30-Nov-17", "fundEntityType": "ENTITY_ID", "source": "IP", "returnType": "TR", "benchmarkIds": [ "VAN"] } The python code I have tried so far is below. It has some issues. I am stuck at it. import csv import json csvfile ='sample.csv' jsonfile ='sample.json' def read_CSV(file, json_file): csv_rows = [] with open(file) as csvfile: reader = csv.DictReader(csvfile) field = reader.fieldnames for row in reader: csv_rows.extend([{field[i]:[row[field[i]]] if field[i]=='benchmarkIds' or field[i]=='fundId' else row[field[i]] for i in range(len(field))}]); convert_write_json(csv_rows, json_file) #Convert csv data into json def convert_write_json(data, json_file): with open(json_file, "w") as f: f.write(json.dumps(data, sort_keys=False, indent=4, separators=(',', ': '))) #f.write(json.dumps(data)) read_CSV(csvfile,jsonfile)
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84772708
score: -2
answer count: 1
has answer: http://stackoverflow.com/a/48886872
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/a/48888914
accepted answer of: http://stackoverflow.com/q/48888168
has comment: http://stackoverflow.com/comment/84783166
type: AcceptedAnswer
has body: Right so this looks fine, except for the last part where you write the results to csv. You basically rewrite the csv for each url, which means that only the last one will remain when your code is done. To avoid this, you can open your csv file in append mode, rather than write. Just a small change with open('output.csv', 'a') as csvfile:
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84784221
answers question: http://stackoverflow.com/q/48888168
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84783606

http://stackoverflow.com/q/48928655
type: Question
answer count: 2
downvote count: 0
tagged with: label
favorite count: 0
has answer: http://stackoverflow.com/a/48929036
tagged with: pandas
tagged with: python
upvote count: 2
has body: I have a big dataset (2m rows, 70 variables), which has many categorical variables. All categorical variables are coded in numbers (e.g. see df1) df1: obs gender job 1 1 1 2 1 2 3 2 2 4 1 1 I have a another data frame with all explanations, looking like this: df2: Var: Value: Label: gender 1 male gender 2 female job 1 blue collar job 2 white collar Is there a fast way to replace all values of the categorical columns with their label from df2? This would save me the work to always look up the meaning of the value in df2. I found some solutions to replace values by hand, but I look for an automatic way doing this. Thank you
has title: Python pandas: labeling categorical values based on legend dataframe
accepted answer: http://stackoverflow.com/a/48929036
possible better answer: http://stackoverflow.com/a/48929129
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48929129
tagged with: dataframe

http://stackoverflow.com/a/48847716
has body: I would do it like this: //table[@class="wikitable"]//tr/td[1][not(@rowspan)]//a //table[@class="wikitable"] selects only the tables with the films. //tr/td[1][not(@rowspan)] selects the first field of each row, excluding big ones that list just the year.
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48847665
answers question: http://stackoverflow.com/q/48847665

http://stackoverflow.com/a/48963280
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48963215
score: 2
has body: What you could do is starting from a randomly chosen array x = np.random.choice(np.arange(6), 5) then collect the unique values and sorting them v = sorted(set(x)) then map the original value to the index in v: result = [v.index(y) for y in x]
downvote count: 0

http://stackoverflow.com/comment/84884129
type: Comment
comment on: http://stackoverflow.com/q/48938522
score: 0
type: QuestionComment
has text: with io.open("abc.txt.", 'w') as f: with redirect_stdout(f): #What print statements here?

http://stackoverflow.com/q/48878848
has answer: http://stackoverflow.com/a/48879038
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84761978
favorite count: 0
has title: Parsing text from a table of contents using regex
has comment: http://stackoverflow.com/comment/84761779
has comment: http://stackoverflow.com/comment/84761681
tagged with: python
tagged with: regex
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48879038
has comment: http://stackoverflow.com/comment/84762108
upvote count: 2
has comment: http://stackoverflow.com/comment/84762137
has body: Following is the text I'd like to parse, stored in variable named "toc" Table of Contents I. INTRODUCTION .................................... 1 II. FACTUAL ASPECTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 A. The Clean Air Act . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 B. EPA's Gasoline Rule . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1. Establishment of Baselines . . . . . . . . . . . . . . . . . . . . . . . . 3 2. Reformulated Gasoline . . . . . . . . . . . . . . . . . . . . . . . . . . 4 3. Conventional Gasoline (or "Anti-Dumping Rules") . . . . . . . . 4 C. The May 1994 Proposal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 III. MAIN ARGUMENTS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 A. General .................................... 5 B. The General Agreement on Tariffs and Trade . . . . . . . . . . . . . . . . 6 1. Article I - General Most-Favoured-Nation Treatment . . . . . . . 6 2. Article III - National Treatment on Internal Taxation and Regulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 a) Article III:4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 b) Article III:1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 3. Article XX - General Exceptions . . . . . . . . . . . . . . . . . . . . 15 4. Article XX(b) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 a) "Protection of Human, Animal and Plant Life or Health" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 b) "Necessary" . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 5. Article XX(d) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21 6. Article XX(g) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 a) "Related to the conservation of exhaustible natural resources..." . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22 b) "... made effective in conjunct…
has comment: http://stackoverflow.com/comment/84761737
type: Question
has comment: http://stackoverflow.com/comment/84762017
has comment: http://stackoverflow.com/comment/84762040
has comment: http://stackoverflow.com/comment/84762160
score: 2

http://stackoverflow.com/comment/96316298
score: 0
type: Comment
type: QuestionComment
has text: [related1](https://stackoverflow.com/q/54757400/9059420), [related2](https://stackoverflow.com/q/53035293/9059420)
comment on: http://stackoverflow.com/q/48807196

http://stackoverflow.com/comment/84711866
type: QuestionComment
has text: That's just a copy. `[::-1]` copies all elements into a new string with step -1, so yes, O(n).
comment on: http://stackoverflow.com/q/48854234
score: 0
type: Comment

http://stackoverflow.com/a/48867469
has comment: http://stackoverflow.com/comment/84759935
has body: To fetch text use text instead of click() only text no parenthesis For ext- driver.find_element_by_xpath(r'//*[contains(@id,"ext-gen")]/div/table/tbody/tr/td[17]/div').click() OR driver.find_element_by_xpath(r'//*[matches(@id,"^.*?ext-gen.*$")]/div/table/tbody/tr/td[17]/div').click() OR driver.find_element_by_xpath(r'//*[matches(@id,"ext-gen")]/div/table/tbody/tr/td[17]/div').click() For ext-comp- driver.find_element_by_xpath(r'//*[contains(@id,"ext-comp-")]/div/table/tbody/tr/td[17]/div').click() OR driver.find_element_by_xpath(r'//*[matches(@id,"^.*?ext-comp-.*$")]/div/table/tbody/tr/td[17]/div').click() OR driver.find_element_by_xpath(r'//*[matches(@id,"ext-comp-")]/div/table/tbody/tr/td[17]/div').click() I found one more that is starts-with driver.find_element_by_xpath(r'//*[starts-with(@id,"ext-gen")]/div/table/tbody/tr/td[17]/div').click() driver.find_element_by_xpath(r'//*[starts-with(@id,"ext-comp-")]/div/table/tbody/tr/td[17]/div').click()
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48867221
has comment: http://stackoverflow.com/comment/84760503

http://stackoverflow.com/q/48942762
type: Question
score: 0
upvote count: 1
downvote count: 1
possible better answer: http://stackoverflow.com/a/48942926
favorite count: 0
has answer: http://stackoverflow.com/a/48942926
tagged with: python
answer count: 4
has answer: http://stackoverflow.com/a/48942835
has answer: http://stackoverflow.com/a/48942884
has comment: http://stackoverflow.com/comment/84892337
has body: I am trying to create a set as a value to a dictionary. fd = {} fs = set() fd['a'] = fs.add('x') fd['a'] = fs.add('y') The set is indeed created properly: print(fs) {'x','y'} But the dictionary does not contain the set as the value. print(fd) {'a':None} I thought any object can be a value in a dictionary. Why don't I get the set as the value for the given simple string key?
has comment: http://stackoverflow.com/comment/84892415
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84892273
has comment: http://stackoverflow.com/comment/84892296
has comment: http://stackoverflow.com/comment/84892174
has title: Unable to create set as value to a dictionary
has answer: http://stackoverflow.com/a/48942821
accepted answer: http://stackoverflow.com/a/48942821

http://stackoverflow.com/a/48830158
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48830107
answers question: http://stackoverflow.com/q/48830107
has body: Use numpy.select and cache shifted and diffed Series for better performance and readibility: diff = df.a.diff() shifted = df.b.shift() df['c'] = np.select([diff &gt; 0, diff &lt; 0], [shifted + df.b, shifted - df.b], default=shifted) print (df) a b c 0 2 10 NaN 1 3 16 26.0 2 1 12 4.0 3 1 18 12.0 4 3 11 29.0 5 1 13 -2.0
upvote count: 2
type: AcceptedAnswer
type: Answer
score: 2

http://stackoverflow.com/a/53255119
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48951591
score: 1
has body: Old question, but I would solve it using generators. from itertools import dropwhile # a generator that returns binary # representation of the input def getBinary(N): while N: yield N%2 N //= 2 def longestGap(N): longestGap = 0 currentGap = 0 # we want to discard the initial 0's in the binary # representation of the input for i in dropwhile(lambda x: not x, getBinary(N)): if i: # a new gap is found. Compare to the maximum longestGap = max(currentGap, longestGap) currentGap = 0 else: # extend the previous gap or start a new one currentGap+=1 return longestGap

http://stackoverflow.com/q/48805574
has body: I'm still at learning phase of python. So, here's what I was trying to do. I was fetching the data off of the accuweather page to show the current weather. But requests module seems to give some sort of error. &gt; import requests &gt; from bs4 import * &gt; data = requests.get("https://www.accuweather.com/en/us/new-york-ny/10017/weather-forecast/349727") Traceback (most recent call last): File "/home/nishantsikri/.local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 601, in urlopen chunked=chunked) File "/home/nishantsikri/.local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 387, in _make_request six.raise_from(e, None) File "&lt;string&gt;", line 2, in raise_from File "/home/nishantsikri/.local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 383, in _make_request httplib_response = conn.getresponse() File "/usr/lib/python3.6/http/client.py", line 1331, in getresponse response.begin() File "/usr/lib/python3.6/http/client.py", line 297, in begin version, status, reason = self._read_status() File "/usr/lib/python3.6/http/client.py", line 258, in _read_status line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") File "/usr/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) File "/usr/lib/python3.6/ssl.py", line 1009, in recv_into return self.read(nbytes, buffer) File "/usr/lib/python3.6/ssl.py", line 871, in read return self._sslobj.read(len, buffer) File "/usr/lib/python3.6/ssl.py", line 631, in read v = self._sslobj.read(len, buffer) ConnectionResetError: [Errno 104] Connection reset by peer During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/nishantsikri/.local/lib/python3.6/site-packages/requests/adapters.py", line 440, in send timeout=timeout File "/home/nishantsikri/.local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 639, in urlopen _stacktrace=sys.exc_info()[2]) File "/home/nishantsikri/.local/lib/python3.6/site…
score: 0
has answer: http://stackoverflow.com/a/48806039
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84614900
tagged with: python
tagged with: python-requests
has comment: http://stackoverflow.com/comment/84614116
accepted answer: http://stackoverflow.com/a/48806039
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84614247
has comment: http://stackoverflow.com/comment/84613977
has title: requests.get() giving an error while fetching data
type: Question

http://stackoverflow.com/comment/84734476
comment on: http://stackoverflow.com/q/48865396
score: 0
type: Comment
has text: Or plot something with more xticks?
type: QuestionComment

http://stackoverflow.com/q/48849407
tagged with: listfield
has answer: http://stackoverflow.com/a/53586296
tagged with: python-3.x
type: UnansweredQuestion
tagged with: django
has body: I am trying to use mongodb with django. My main poject name is 'mysite' and inside that there is an app named 'blog' and inside blog/models.py, I have written the following portion. from django.db import models from djangotoolbox.fields import ListField class Post(models.Model): title = models.CharField() text = models.TextField() tags = ListField() comments = ListField() I have installed djangotoolbox. When I run the command on python shell from blog.models import Post It shows the following error. &gt;&gt;&gt; from blog.models import Post Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; File "E:\Study\mysite\blog\models.py", line 2, in &lt;module&gt; from djangotoolbox.fields import ListField File "C:\Program Files (x86)\Python36-32\Lib\site-packages\djangotoolbox\fields.py", line 4, in &lt;module&gt; from django.utils.importlib import import_module ModuleNotFoundError: No module named 'django.utils.importlib' &gt;&gt;&gt; Why is this error occurring? and what is its solution? Because I have seen all over the internet and could not find any.
type: Question
has title: ListField not found error in django
tagged with: mongodb
answer count: 2
has answer: http://stackoverflow.com/a/48849772
score: 0
tagged with: python

http://stackoverflow.com/comment/84696034
score: 0
type: QuestionComment
has text: Thank you for your reply! :) Unfortunately, after I uninstalled Python 3.7.0b1, when I try to "ask" in the command line wich version is active, it's still the 3.7. :(
type: Comment
comment on: http://stackoverflow.com/q/48822571

http://stackoverflow.com/q/48828968
upvote count: 1
has answer: http://stackoverflow.com/a/48829627
type: Question
downvote count: 0
possible better answer: http://stackoverflow.com/a/48829627
has answer: http://stackoverflow.com/a/48828984
answer count: 2
tagged with: pandas
has body: I would like to transform this dataframe: A B C D xx nan 2 3 xx 1 nan 2 yy 4 nan nan yy nan 5 nan yy nan 4 6 zz nan nan nan zz nan 8 nan zz nan 9 nan zz 7 10 nan into this final one (by grouping by 'A' column) A B C D xx 1 2 3 yy 4 5 6 zz 7 8 nan I tried to use groupby,fillna and apply but with no results so far. I want the final dataframe to always show, wherever it is possible, a non-nan value and the first value for each unique 'A' column value. How could I do this?
favorite count: 0
accepted answer: http://stackoverflow.com/a/48828984
tagged with: python
type: AnsweredQuestion
score: 1
has title: Groupby rows, join and selection between a NaN value and a number
tagged with: dataframe

http://stackoverflow.com/a/48922427
answers question: http://stackoverflow.com/q/48869453
has body: You have to compile opencv along with contrib modules, which has the face submodule. The cmake option to do this is -D OPENCV_EXTRA_MODULES_PATH=&lt;path to opencv_contrib&gt;/modules. You can download opencv contrib here
type: Answer
score: 0

http://stackoverflow.com/q/48882225
tagged with: python
has comment: http://stackoverflow.com/comment/84788311
upvote count: 2
score: 0
has body: Stumped on this thread sync I'm encountering. Basically, I'm writing to a out buffer, and waiting on a condition variable until the read buffer is populated with a response from a socket. It's an incredibly simple thread sync. def write_wait_response(self, buffer, timeout=30): ''' Write and wait for response Params: Buffer BYTE encoded data Timeout timeout to wait for response Returns: response str if successful ''' self.buffer = buffer if self.waitLock(timeout): # condition var was signaled, we can return a response readbuf = bytes(self.readbuffer) self.readbuffer = b'' return readbuf else: print("AsyncClientSocket: No response recieved from {} in {} seconds, dumping buffer".format( self.sa, timeout)) self.buffer = '' raise TimeoutError("AsyncClientSocket Timed Out") def handle_read(self): self.readbuffer, address = self.recvfrom(2048) print(self.readbuffer) print("notifying") self.cond.notifyAll() Seems straightforward enough, right? There's 1 thread waiting on the condition variable, and 1 thread (asyncore async callback loop) that will populate self.readbuffer and notify on the condition variable. Even more curious : if I do a time.sleep() instead of using a condition variable, I get a perfectly populated self.readbuffer on the calling thread of write_wait_response(). Obviously this is not a solution I can accept. Here's what I'm expecting is happening: Call to write_wait_response(buffer), this writes to buffer and waits on self.cond asyncore callback loop calls handle_write, writes bytes to socket. Server receives bytes, writes response. asyncore callback loop sees bytes on the socket, reads into self.readbuffer, notifies cv ?????????? write_wait_response should unblock? Console output: waiting &lt;- thread 1 waiting on CV AsyncClientSocket: writing 5 bytes &lt;- thread 2: handle_write b'200,2' &lt;- thread 2: that's the server response notifying &lt;- thread 2: that's handle_read attempting to notify the held CV error: uncaptured python exception, closing chan…
tagged with: multithreading
downvote count: 2
has comment: http://stackoverflow.com/comment/84773469
answer count: 1
has answer: http://stackoverflow.com/a/48891457
has title: condition variable not holding wait across two threads
has comment: http://stackoverflow.com/comment/84791992
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48891457
favorite count: 0
tagged with: python-3.x
tagged with: asyncore
type: Question
tagged with: sockets

http://stackoverflow.com/a/48860433
downvote count: 0
answers question: http://stackoverflow.com/q/48860378
score: 1
type: Answer
has body: You could add a reference to the class which instantiates B: class A: def __init__(self): # pass self while instantiating B self.b = B(self) def foo(self): print('A') class B: def __init__(self, rel_obj): self.rel_obj = rel_obj def bar(self): self.rel_obj.foo() # access foo() using self.rel_obj Similarly, you could pass an object of class C to invoke C's version of foo method.
upvote count: 1

http://stackoverflow.com/comment/84753400
type: QuestionComment
has text: Good start. What about the for loop? Please spend a few moments proof reading your question - it saves people having to extract the information later.
comment on: http://stackoverflow.com/q/48858703
score: 0
type: Comment

http://stackoverflow.com/comment/84824036
has text: Try this: https://askubuntu.com/a/877398
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48908634

http://stackoverflow.com/comment/84829672
type: AnswerComment
has text: @EvanWeissburg I am curious if the above code work for you. As I understand correctly, you are looking for edit distance based similarity, right? As Wu has mentioned that it might work well for hamming distance. Two strings that have small edit distance can have large hamming distance.
comment on: http://stackoverflow.com/a/48893335
type: Comment
score: 0

http://stackoverflow.com/comment/84924606
has text: this solved almost 100% of my problem with some slight modifications to the answer provided. There is still one area I am looking to solve, but I'm certain I can fix that. I will provide an update to my question shortly
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48958195

http://stackoverflow.com/q/48868550
has title: Python fastest way to gets element's array
score: 0
has answer: http://stackoverflow.com/a/48868733
tagged with: python
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48868742
type: AnsweredQuestion
type: Question
answer count: 2
tagged with: arrays
has body: I'm looking for the fastest way to get elements into an array. Suppose we have a Class like this: class test: def __init__(self, a, b): self.let = a self.num = b Now suppose we have an array of tests : test1 = test("a", "1") test2 = test("b", "2") test3 = test("c", "3") vec = [ test1, test2 , test3] I would like the result to be something like this: newest = [] for t in vec: if(t.let == "a" or t.num == "3") newest.append(t) Is there a better way to do this?
accepted answer: http://stackoverflow.com/a/48868742
favorite count: 0
possible better answer: http://stackoverflow.com/a/48868733

http://stackoverflow.com/q/48887127
tagged with: sqlite
downvote count: 1
has comment: http://stackoverflow.com/comment/84786493
tagged with: python
tagged with: bottle
has answer: http://stackoverflow.com/a/48931702
type: UnansweredQuestion
has body: I'm trying to use Bottle framework in python with sqlite3. Then I made a Todo List application but when I tried to post a data at the first time the error happened differently from above. The second time 'database is locked' happened. Can anyone help? #_*_ coding:utf-8- _*_ import os, sqlite3 from bottle import route, run, get, post, request, template #sqlite from here---------------- dbname = "todo.db" connection = sqlite3.connect(dbname) dbcontrol = connection.cursor() #Making table from here-------------------- create_table = '''create table todo_list (todo text)''' @route("/") def index(): todo_list = get_todo() return template("index", todo_list=todo_list) I think I need more specific code here. @route("/enter", method=["POST"]) def enter(): conn = sqlite3.connect("todo.db") todo=request.POST.getunicode("todo_list") save_todo(todo) return redirect("/") def save_todo(todo): connection = sqlite3.connect('todo.db') dbcontrol = connection.cursor() insert="insert into todo_list(todo) values('{0}')".format(todo) dbcontrol.execute(insert) connection.commit() def get_todo(): connection=sqlite3.connect('todo.db') dbcontrol = connection.cursor() select = "select * from todo_list" dbcontrol.execute(select) row = dbcontrol.fetchall() return row run(host="localhost", port=8080, debug=True)
type: Question
upvote count: 1
answer count: 1
favorite count: 0
has title: sqlite3 database is locked(using bottle)
score: 0
has comment: http://stackoverflow.com/comment/84779598

http://stackoverflow.com/comment/84922745
comment on: http://stackoverflow.com/q/48957769
type: QuestionComment
has text: Psychic debugging time: `paths` was defined as `[[something]*something]*something` or something like that, causing it to be a list of a bunch of references to the same sublist.
type: Comment
score: 2

http://stackoverflow.com/comment/84848826
has text: Yes, but you could have just pasted the code _and_ the output into a code block as text. Then it'd work better for mobile users and be easier to reuse.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48920045
score: 1

http://stackoverflow.com/a/48939026
has body: Is it possible that the data inside your metadata.tsv file isn't UTF-8 encoded?
has comment: http://stackoverflow.com/comment/90014569
answers question: http://stackoverflow.com/q/48938165
upvote count: 1
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84904482

http://stackoverflow.com/comment/84660232
type: QuestionComment
has text: @JaredSmith Yeah I know that it is a stupid question but I also was even more stupid not seeing the problem. Thanks, i thought that at least even it is a dumb question I could try to make it look good :D
score: 0
comment on: http://stackoverflow.com/q/48828007
type: Comment

http://stackoverflow.com/q/48887134
upvote count: 3
type: Question
has answer: http://stackoverflow.com/a/48887403
tagged with: matplotlib
downvote count: 0
has comment: http://stackoverflow.com/comment/84779704
has title: Remove dashes from grid
linked to: http://stackoverflow.com/q/20416609
score: 3
duplicate of: http://stackoverflow.com/q/20416609
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48887403
tagged with: python
tagged with: plot
has body: If I run this code import matplotlib.pyplot as plt fig = plt.figure() ax = fig.add_subplot(111) ax.xaxis.set_tick_params(length=0,labelsize=0) ax.grid(True) I get the following: The xaxis ticks and labels don't show (as expected), but some dashes appear on the bottom of the plot (the first three of which I have circled in red). How can I remove them? I have looked at the documentation for grids, but can't find anything. An answer which teaches me how I could have figured out how to do this by looking at the documentation would be particularly useful.
type: AnsweredQuestion

http://stackoverflow.com/q/48839120
type: Question
has comment: http://stackoverflow.com/comment/84682818
tagged with: twisted
has comment: http://stackoverflow.com/comment/84683320
upvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84682951
tagged with: python-2.7
tagged with: python-asyncio
has body: I have a code which is written in Twisted and I am having trouble with converting it to Asyncio. From my problem the problem is about protocol in Server class. The code which is written with Twisted is this: from twisted.internet import reactor, protocol class Client(): def __init__(self): self.something = "" def dataReceived(self, packet): print(packet) def makeConnection(self, transport): self.transport = transport self.server = self.factory def connectionLost(self, args): print("Connection lost.") class Server(protocol.ServerFactory): protocol = Client if __name__ == '__main__': validPort = [] S = Server() try: reactor.listenTCP(44444, S) validPort.append(44444) except: print('Problem about port.') if not validPort == []: print('Server is running.') reactor.run() And this is the code which I converted to Asyncio and doesnt't work (I am not sure the problem is about protocol in Server Class): import asyncio, logging, sys SERVER_ADDRESS = ('localhost', 44444) logging.basicConfig( level=logging.DEBUG, format='%(name)s: %(message)s', stream=sys.stderr, ) log = logging.getLogger('main') event_loop = asyncio.get_event_loop() class Client(): def __init__(self): self.something = "" def data_received(self, packet): self.log.debug('received {!r}'.format(data)) print(packet) def connection_made(self, transport): self.transport = transport self.server = self.factory self.log = logging.getLogger( 'EchoServer_{}_{}'.format(*self.address) ) self.log.debug('connection accepted') def connection_lost(self, args): if error: self.log.error('ERROR: {}'.format(error)) else: self.log.debug('closing') super().connection_lost(error) class Server(asyncio.Protocol): protocol = Client if __name__ == '__main__': S = Server() factory = event_loop.create_server(S, *SERVER_ADDRESS) server = event_loop.run_until_complete(factory) log.debug('starting up on {} port {}'.format(*SERVER_ADDRESS)) try: event_loop.run_forever() finally: log.debug('closing server') server.close() event_loop.run_until_co…
has answer: http://stackoverflow.com/a/48842898
has comment: http://stackoverflow.com/comment/84682809
score: -1
tagged with: python-3.x
has title: Converting Twisted Code to Asyncio Code
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84682914
has comment: http://stackoverflow.com/comment/84682896
tagged with: python
downvote count: 1

http://stackoverflow.com/comment/84926105
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48959662
has text: @RoadRunner data set is kinda large, trying not to append / remove records or columns when doing sorting
score: 0

http://stackoverflow.com/comment/84668296
type: AnswerComment
score: 0
type: Comment
has text: Good afternoon, Thank you! I thought I'd get back to the Editor too, but I understand how Spider works. See you later!
comment on: http://stackoverflow.com/a/48813810

http://stackoverflow.com/q/48912036
type: Question
tagged with: visual-studio-code
has comment: http://stackoverflow.com/comment/84857292
downvote count: 0
has comment: http://stackoverflow.com/comment/84879477
score: 4
favorite count: 0
tagged with: pylint
has comment: http://stackoverflow.com/comment/84836027
has title: Linting in Visual Studio Code not working
tagged with: python
upvote count: 4
answer count: 0
has body: I have been using VSC (Version 1.19.1 for Mac) including the official Python extension (0.9.1) for a couple of month now. As I left most of the configuration unchanged, I have been using Pylint for linting. Until a couple of weeks ago everything was fine, now linting doesn't work anymore. An example would be: def test(x): return x Here I would normally get an indention error shown by Pylint which doesn't happen anymore. I have re-installed the Python extension and then re-installed Visual Studio Code, nothing worked. Can anyone help me? I run MacOS 10.13.1, Python 3.6. and Pylint 1.8.1. My user settings for VSC are: "editor.rulers": [ 99 ], "files.insertFinalNewline": true, "workbench.activityBar.visible": true, "files.trimTrailingWhitespace": true, "editor.minimap.enabled": false, "explorer.confirmDragAndDrop": false
type: UnansweredQuestion

http://stackoverflow.com/comment/84827018
has text: Is there a way to add logistic as final layer and relu for the others? The thing is that MLPRegressor uses squared-loss (y-y_hat)**2. And I would like to use the same equation for logistic regression as final layer (I could do it with tensorflow, but it would take more time to program the code).
type: Comment
comment on: http://stackoverflow.com/a/48910238
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84914420
comment on: http://stackoverflow.com/a/48941516
score: 0
type: Comment
has text: Thanks for replying!!! What does the [0] represent? The 1st item in each dictionary/list?
type: AnswerComment

http://stackoverflow.com/comment/84918211
score: 1
has text: @DebanjanB I have never tried to do this, and it's incredibly useful, thanks! Max, if you want objective load time, why are you jumping through so many hoops? Just track the time between navigating to the page, and when the last element loads. Done. Also, using WebdriverWait will avoid artificially inflating your numbers with time.sleep().
type: AnswerComment
comment on: http://stackoverflow.com/a/48941918
type: Comment

http://stackoverflow.com/q/48950989
type: Question
score: 3
has body: So I have this chatting app like structure I have made using Kivy's RecycleView to instantiate a custom widget (named 'Row') and I pass it values however I wish. It works fine if the Row custom widget only contains a Label child, the moment I add an Image and a Button (I'll explain why in a sec), there are weird spacing and positioning problems which shouldn't exist because I am using a BoxLayout and have tried proper size_hint: and height: techniques to get them to look right. Relevant KV code: &lt;Row@BoxLayout&gt;: orientation: 'vertical' text: '' source: 'res/icon.png' buttontext: '' Label: markup: True text_size: self.size text: root.text Image: size: self.size source: root.source allow_stretch: True Button: text: root.buttontext #contains a link on_press: app.root.stuff(self.text) #opens that link # Relevant Screen where I am using the RecycleView &lt;ChatBotScreen&gt; BoxLayout: ti_userinput: ti_userinput orientation: 'vertical' ScrollView: size_hint_y: 85 RecycleView: id: chatbase_list viewclass: 'Row' data: [] RecycleBoxLayout: padding: "15dp", "45dp", "15dp", "15dp" default_size: None, dp(25) default_size_hint: 1, None size_hint_y: None height: self.minimum_height orientation: 'vertical' TextInput: size_hint_y: None height: "40dp" id: ti_userinput multiline: False on_text_validate: root.on_user_enter_text() Since my custom widget Row is extending BoxLayout and I am using a vertical orientation, why aren't the child widgets (Label, Image and Button) overlapping? This is the class &amp; function via which I am calling to pass the data inside the RecycleView class ChatBotScreen(Screen): nickname = StringProperty() rvList = [] def display_bot_output(self, botOutput): # Initialize an empty dictionary tempDict = {} textToDisplay = '' + botOutput # Update the dictionary with properties:values and then pass it as a list to RecycleView's data tempDict.update({'text':textToDisplay, 'buttontext':'https://google.com'}) self.rvList.append(tempDict) self.ids.chatbase_li…
upvote count: 3
has comment: http://stackoverflow.com/comment/126332580
tagged with: user-interface
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
tagged with: kivy
tagged with: kivy-language
has answer: http://stackoverflow.com/a/63954874
downvote count: 0
has title: Alignment problems with custom widget using RecycleView in Kivy
has comment: http://stackoverflow.com/comment/85438432

http://stackoverflow.com/a/48914668
type: Answer
answers question: http://stackoverflow.com/q/48891610
upvote count: 1
has body: I seem to have answered this question before for links, so I took the same code and duplicated it all for nodes. I did improve the textEdited event handler to handle undo/redo, although it's obviously more verbose with all the calls to console.log. function init() { var $ = go.GraphObject.make; myDiagram = $(go.Diagram, "myDiagramDiv", { initialContentAlignment: go.Spot.Center, "undoManager.isEnabled": true, "ModelChanged": function(e) { // just for demonstration purposes, if (e.isTransactionFinished) { // show the model data in the page's TextArea document.getElementById("mySavedModel").textContent = e.model.toJson(); } if (e.change === go.ChangedEvent.Remove) { if (e.modelChange === "linkDataArray") { var linkdata = e.oldValue; var oldstr = linkdata.text; if (!oldstr) return; var linkchoices = e.model.modelData.linkchoices; var idx = linkchoices.indexOf(oldstr); if (idx &lt; 0) { console.log("deletion adding link choice: " + oldstr); var newlinkchoices = Array.prototype.slice.call(linkchoices); newlinkchoices.push(oldstr); e.model.set(e.model.modelData, "linkchoices", newlinkchoices); } } else if (e.modelChange === "nodeDataArray") { var nodedata = e.oldValue; var oldstr = nodedata.text; if (!oldstr) return; var nodechoices = e.model.modelData.nodechoices; var idx = nodechoices.indexOf(oldstr); if (idx &lt; 0) { console.log("deletion adding node choice: " + oldstr); var newnodechoices = Array.prototype.slice.call(nodechoices); newnodechoices.push(oldstr); e.model.set(e.model.modelData, "nodechoices", newnodechoices); } } } } }); myDiagram.nodeTemplate = $(go.Node, "Auto", $(go.Shape, { fill: "white", portId: "", fromLinkable: true, toLinkable: true, cursor: "pointer" }, new go.Binding("fill", "color")), $(go.TextBlock, { margin: 8, editable: true, textEditor: window.TextEditorSelectBox, // defined in extensions/textEditorSelectBox.js textEdited: function(tb, oldstr, newstr) { if (oldstr !== newstr) { console.log("changing from " + oldstr + " to " + newstr); var mo…
type: AcceptedAnswer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84840621
accepted answer of: http://stackoverflow.com/q/48891610

http://stackoverflow.com/q/48809766
tagged with: python
accepted answer: http://stackoverflow.com/a/48809932
tagged with: django
tagged with: request
type: AnsweredQuestion
type: Question
has title: 'str' object has no attribute 'GET' when requesting to django script
answer count: 1
has answer: http://stackoverflow.com/a/48809932
has body: i have been working with django to make an interactive web page. But when i try to make a Http request to a django view. It throws that error, even though i have the exact same code above and that works just fine. Here is my Python code: def test(request): default = {"Error" : "Could not make request"} name = request.GET.get('showname') token = getToken() showJs = searchShowId(name, token) if showJs.get('Error'): try: token = refreshToken(token) showJs = searchShowId(name, token) return JsonResponse(showJs) except KeyError as error: token = login() showJs = searchShowId(name, token) return JsonResponse(showJs) else: return JsonResponse(showJs) def image(request): default = {"Error" : "Could not make request"} id = request.GET.get('id') return JsonResponse(image(id)) this is the full error: Traceback: File "C:\Users\\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Documentos\Programming\DjangoProjects\mediaD\mediaDe\views.py" in image 33. return JsonResponse(image(id)) File "E:\Documentos\Programming\DjangoProjects\mediaD\mediaDe\views.py" in image 32. id = request.GET.get('id') Exception Type: AttributeError at /image/ Exception Value: 'str' object has no attribute 'GET' Javascript Code: function search() { console.log('Function Called') var showName = document.getElementById('showName'); console.log(showName.value); var name = stringToPost(showName.value); $.ajax({ type: "GET", url: "/request/", data: { showname: showName.value }, success: function (dato) { dato = dato['data']; for (var i = 0;…
score: 0

http://stackoverflow.com/q/48834373
type: Question
upvote count: 0
answer count: 1
favorite count: 0
has body: Getting an operation error with this line. Any idea of whats wrong with the SQL statement? (Bit of a sql noob) Basically just want a way to get an item from a table in where a corresponding item to that record is equal to either of the two options. Code below, thanks! self.cursor.execute("SELECT test_id FROM test WHERE class_id = ? OR WHERE class_id = ?",(self.classIDs[0],self.classIDs[1]))
tagged with: sql
tagged with: sqlite
has title: SQL SQlite3 (Operational Error?)
has answer: http://stackoverflow.com/a/48834434
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84673300
type: UnansweredQuestion
tagged with: python
downvote count: 1
score: -1

java
tags question: http://stackoverflow.com/q/48836436
tags question: http://stackoverflow.com/q/48904661
tags question: http://stackoverflow.com/q/48937571
tags question: http://stackoverflow.com/q/48884494
tags question: http://stackoverflow.com/q/48913924
tags question: http://stackoverflow.com/q/48962130
tags question: http://stackoverflow.com/q/48852421
tags question: http://stackoverflow.com/q/48864717
tags question: http://stackoverflow.com/q/48835150
tags question: http://stackoverflow.com/q/48890049
tags question: http://stackoverflow.com/q/48885704
tags question: http://stackoverflow.com/q/48832907
tag name: java
tags question: http://stackoverflow.com/q/48906447
tags question: http://stackoverflow.com/q/48953878
tags question: http://stackoverflow.com/q/48947770
tags question: http://stackoverflow.com/q/48905888
tags question: http://stackoverflow.com/q/48954939
tags question: http://stackoverflow.com/q/48933797
type: Tag
tags question: http://stackoverflow.com/q/48831346
tags question: http://stackoverflow.com/q/48823661
tags question: http://stackoverflow.com/q/48957165

http://stackoverflow.com/a/48873080
type: Answer
has body: Figured that the subscriber is not being saved, so I put saving solo dev on hold until the subscriber is saved. This helped. sub = subscriber_form.save(commit=False) solo_dev = solo_dev_form.save(commit=False) sub.solo_dev = solo_dev sub.save() solo_dev.save()
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48872140
score: 0
accepted answer of: http://stackoverflow.com/q/48872140

http://stackoverflow.com/a/48829951
type: Answer
answers question: http://stackoverflow.com/q/48829494
score: 0
has body: here is a working example (explanation following): grocery_history={'item_name':[], 'quantity':[], 'cost':[]} cont = 'c' while cont != 'q': item_name = input("Item name:") quantity = int(input("Quantity purchased:")) cost = int(input("Price per item:")) cont = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:") grocery_history['item_name'].append(item_name) grocery_history['quantity'].append(quantity) grocery_history['cost'].append(cost) grand_total = 0 for i in range(len(grocery_history['item_name'])): item_name = grocery_history['item_name'][i] quantity = grocery_history['quantity'][i] cost = grocery_history['cost'][i] priceTimesQuantity = quantity * cost grand_total = grand_total + priceTimesQuantity message = 'Bought {} x{} (each: {}$) to a total of: {}'.format(item_name, quantity, cost, priceTimesQuantity) print( message ) finalmessage = 'Grand Total: {}'.format(grand_total) print(finalmessage) I reduced the part above your first loop (think about it) grocery_history is now a dictionary containing 3 lists. example: we now fill this these lists downwards with the items (append) when the user is finished, we go trough that lists again with i as index (see the little gray number on the left side of the image) Then, for every item we load the details from the list and calculate the price in total Furthermore, we are adding the total to the grand_total, which is a number (starting from zero) adding up with the second loop. after the second loop is done we print the final value (sum) in the Texts : "some text {}".format(var) - {} is a placeholder for the var coming after the string

http://stackoverflow.com/comment/84620516
type: Comment
has text: @0xbaadf00d Sorry, I've updated my post.
type: QuestionComment
comment on: http://stackoverflow.com/q/48808603
score: 0

http://stackoverflow.com/comment/85143807
score: 0
has text: @Walucas i have added models(short version) to code block.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48805477

http://stackoverflow.com/q/48892816
tagged with: python
has title: Tracking movie titles using Google Cloud Vision API
has body: I'm trying to find a way to crop/obtain offsets of Movie titles via Google Cloud Vision API. Here's an example image: https://i.sstatic.net/fyJqF.jpg I've tried to use FACE_DETECTION, LOGO_DETECTON, and event LABEL_DETECTION but I can't seem to get a result for it. Any ideas?
type: Question
has answer: http://stackoverflow.com/a/48938871
score: 0
tagged with: movies
answer count: 1
tagged with: google-cloud-vision
type: UnansweredQuestion

http://stackoverflow.com/a/48947845
has comment: http://stackoverflow.com/comment/84907266
type: Answer
accepted answer of: http://stackoverflow.com/q/48946142
answers question: http://stackoverflow.com/q/48946142
has comment: http://stackoverflow.com/comment/84904749
has comment: http://stackoverflow.com/comment/84905635
type: AcceptedAnswer
has body: The fewest lines of code I can come up with is as follows: import numpy as np import numpy_indexed as npi a = np.array([[1,2,2,2,3], [0,1,1,1,2], [0,0,0,1,0]]) row_idx = np.indices(a.shape, dtype=np.int32)[0] axes, table = npi.Table(row_idx.flatten(), a.flatten()).count() I havnt profiled this, but it does not contain any hidden un-vectorized for-loops; and I doubt you could do it much faster in numpy by any means. Nor do I expect it to perform a whole lot faster than your current solution though. Using the smallest possible int-types may help. Note that this function does not assume that the elements of a form a contiguous set; the axes labels are returned in the axes tuple; that may or may not be the behavior you are looking for. Modifying the code in the Table class to conform to your current layout shouldnt be hard though. If speed is your foremost concern; your problem would probably map really well to numba.
score: 0

http://stackoverflow.com/q/48927607
has answer: http://stackoverflow.com/a/48950047
tagged with: python
has comment: http://stackoverflow.com/comment/84882755
has comment: http://stackoverflow.com/comment/84880597
score: 2
has title: Equivalent of pywinauto library for debian
has comment: http://stackoverflow.com/comment/84880653
type: Question
tagged with: user-interface
downvote count: 0
answer count: 1
tagged with: raspberry-pi3
tagged with: pywinauto
linked to: http://stackoverflow.com/q/40799953
favorite count: 0
tagged with: python-3.x
upvote count: 2
type: UnansweredQuestion
has body: I'm looking for an equivalent Python library that will work when I run my script on Raspberry Pi. I'm under the impression that pywinauto only works on windows machine. I want to control some inputs to a GUI launched by my script, using my script. Apart from pywinauto I have no idea how to do this. I thought about using command line to control the software directly, but if there is a simpler way I would really appreciate knowing about it. Thanks for your time.

http://stackoverflow.com/q/48928968
favorite count: 0
tagged with: beautifulsoup
has title: BeautifulSoup finds element but not its text
tagged with: python
type: AnsweredQuestion
upvote count: 3
type: Question
score: 3
possible better answer: http://stackoverflow.com/a/48929150
has answer: http://stackoverflow.com/a/48930427
has answer: http://stackoverflow.com/a/48929150
has body: I'm trying to extract game stats of MLB games using BeautifulSoup. So far its been working well, but I just noticed that I'm unable to retrieve the information about the start time of the game using the usual way of doing so: soup.findAll("span", {"class": "time game-time"}) What's weird about this is that it finds the exact element, and allows me to print it, and it shows that soup has found the all the contents of the element, except for the text. Unfortunately, the text part is all I need. Images: URL in question: http://www.espn.com/mlb/game?gameId=370925110 Is there any way around this issue without having to use a webdriver like Selenium? Code: with urllib.request.urlopen(link) as url: page = url.read() soup = BeautifulSoup(page, "html.parser") clock = soup.findAll("span", {"class": "time game-time"}) print(clock[0])
linked to: http://stackoverflow.com/q/4770297
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48930427

http://stackoverflow.com/q/48835854
tagged with: python
tagged with: plot
type: AnsweredQuestion
upvote count: 1
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48836174
tagged with: matplotlib
has title: Plotting a sequence of double arrays, and refreshing the graph after each plot, using matplotlib
has body: Each iteration at line 97 gives me arrays for x and y coordinates respectively. for step in range(N_OF_DTs): I'd like to plot an iterations result, clear the window, and then plot the next iterations results. I'm using python 3. I don't know enough python to display data. import numpy as np import matplotlib.pylab as plt np.random.seed(314159) N_OF_DTs = 1000 DT = 0.001 DTover6 = DT/6.0 WIDTH = 20 I_EXT = 1.1 WEIGHT = 0.24 grid_u = np.zeros((WIDTH,WIDTH)) fired = np.zeros((WIDTH,WIDTH)) u = np.zeros((WIDTH,WIDTH)) k1 = np.zeros((WIDTH,WIDTH)) k2 = np.zeros((WIDTH,WIDTH)) k3 = np.zeros((WIDTH,WIDTH)) k4 = np.zeros((WIDTH,WIDTH)) spike_data = np.zeros((WIDTH, WIDTH, N_OF_DTs), dtype=object) def init_grid(): global grid_u grid_u = np.random.rand(WIDTH,WIDTH) def clear_fired_grid(): global fired fired = np.zeros((WIDTH,WIDTH)) def step1_grid(): global grid_u u = grid_u k1 = -u + I_EXT k2 = -(u + 0.5*k1*DT) + I_EXT k3 = -(u + 0.5*k2*DT) + I_EXT k4 = -(u + k3*DT) + I_EXT grid_u = grid_u + DTover6*(k1 + 2*k2 + 2*k3 +k4) def check_fired_grid(): for i in range(WIDTH-1): for j in range(WIDTH-1): check_fired_neuron(j,i) global fired spike_data[0,0,step] = fired def check_fired_neuron(j,i): if grid_u[j,i] &gt; 1: grid_u[j,i] = grid_u[j,i] - 1 global fired fired[j,i] = 1 propagate_to_neighbors(j,i) check_fired_neighbors(j,i) def check_fired_neighbors(j,i): if j &gt; 1: check_fired_neuron(j-1,i) else: check_fired_neuron(WIDTH-1,i) if j &lt; WIDTH-1: check_fired_neuron(j+1,i) else: check_fired_neuron(1,i) if i &gt; 1: check_fired_neuron(j,i-1) else: check_fired_neuron(j,WIDTH-1) if i &lt; WIDTH-1: check_fired_neuron(j,i+1) else: check_fired_neuron(j,1) def propagate_to_neighbors(j,i): if j &gt; 1: grid_u[j-1,i] = grid_u[j-1,i] + WEIGHT else: grid_u[WIDTH-1,i] = grid_u[WIDTH-1,i] + WEIGHT if j &lt; WIDTH-1: grid_u[j+1,i] = grid_u[j+1,i] + WEIGHT else: grid_u[1,i] = grid_u[1,i] + WEIGHT if i &gt; 1: grid_u[j,i-1] = grid_u[j,i-1] + WEIGHT else: grid_u[j,WIDTH-1] = grid_u[j,WIDTH-1] +…
score: 0
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48836174

http://stackoverflow.com/comment/84704408
type: Comment
comment on: http://stackoverflow.com/a/48850088
has text: I think db.Column is flask-sqlalchemy.
type: AnswerComment
score: 0

http://stackoverflow.com/a/74906575
score: 0
has body: Just adding this since I had this problem recently. My model wasn't fitting to a polynomial and seemed to only be doing linear regression. After increasing the epochs to 50000, the model began fitting the polynomial properly.
type: Answer
has comment: http://stackoverflow.com/comment/132203316
answers question: http://stackoverflow.com/q/48934338

http://stackoverflow.com/comment/84822576
score: 0
type: AnswerComment
has text: Your'e Welcome! :)
type: Comment
comment on: http://stackoverflow.com/a/48895911

http://stackoverflow.com/q/48879224
has body: models.py This is my view file with Album and Song Classes. class Album(models.Model): artist = models.CharField(max_length=250) album_title = models.CharField(max_length=500) genre = models.CharField(max_length=250) album_logo = models.FileField() def __str__(self): return self.album_title + '-' + self.artist class Song(models.Model): song = 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 __str__(self): return self.song_title views.py This is my views file for Deleting Song def delete_songs(request, album_id): if request.method == "GET":
score: 1
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/48879310
answer count: 1
tagged with: python
favorite count: 0
upvote count: 1
tagged with: django
accepted answer: http://stackoverflow.com/a/48879310
has title: How can I delete a specific song and also edit song info from my album list without using DeleteView in Django?
type: AnsweredQuestion

http://stackoverflow.com/q/48805069
has body: Example: import pandas as pd arr = pd.Series(['a',['a','b'],'c']) I would like to get the indices of where the series contains elements containing 'a'. So I would like to get back indices 0 and 1. I've tried writing arr.str.contains('a') but this returns 0 True 1 NaN 2 False dtype: object while I'd like it to return 0 True 1 True 2 False dtype: object
has answer: http://stackoverflow.com/a/48805403
downvote count: 0
has title: Find indices of where Pandas Series contains element containing character
tagged with: string
favorite count: 0
tagged with: series
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84616745
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84616623
possible better answer: http://stackoverflow.com/a/48805403
has answer: http://stackoverflow.com/a/48805090
accepted answer: http://stackoverflow.com/a/48805090
type: Question
has comment: http://stackoverflow.com/comment/84619010
answer count: 2
tagged with: contains
tagged with: pandas

http://stackoverflow.com/comment/84687996
type: Comment
has text: I can confirm the problem using your code example. The behavior to me looks like a bug in Qt. The whole column, except most recent line, gets shifted vertically. I don't think this is related to the question you referenced. Probably you need to file a bug report with the Qt project.
score: 0
comment on: http://stackoverflow.com/q/48840059
type: QuestionComment

http://stackoverflow.com/q/48904551
type: Question
type: AnsweredQuestion
has title: Query regarding numpy append function in for loop
duplicate of: http://stackoverflow.com/q/9775297
tagged with: numpy
linked to: http://stackoverflow.com/q/9775297
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48904950
accepted answer: http://stackoverflow.com/a/48904950
favorite count: 0
score: 0
downvote count: 1
tagged with: python
has body: I am struggling in appending a numpy array to other one.. data_X = load_dataset() print(data_X.shape) # (6794, 11) result_array = np.empty((0, 110)) for i in range(0, 1000, 10): arr_1d = data_X[i:i+10].reshape(1, 110) np.append(result_array, arr_1d, axis=0) print(result_array.shape) Not sure what I am doing wrong.. There is no error but shape of result_array is (0,110). Please help.

http://stackoverflow.com/q/48859312
has comment: http://stackoverflow.com/comment/84722023
has answer: http://stackoverflow.com/a/79299681
has title: Python-No such file or directory getAttribute.js
has answer: http://stackoverflow.com/a/48859328
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/70038755
answer count: 6
tagged with: selenium-webdriver
linked to: http://stackoverflow.com/q/79225757
has comment: http://stackoverflow.com/comment/84722170
has body: I had a Python selenium program working a week or so ago. Now selenium fails on the import: from selenium import webdriver The IDLE ouput: Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. &gt;&gt;&gt; RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\testpack.py Traceback (most recent call last): File "C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\testpack.py", line 1, in &lt;module&gt; from selenium import webdriver File "C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\__init__.py", line 18, in &lt;module&gt; from .firefox.webdriver import WebDriver as Firefox # noqa File "C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\firefox\webdriver.py", line 35, in &lt;module&gt; from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver File "C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 26, in &lt;module&gt; from .webelement import WebElement File "C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\webelement.py", line 43, in &lt;module&gt; getAttribute_js = pkgutil.get_data(_pkg, 'getAttribute.js').decode('utf8') File "C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\lib\pkgutil.py", line 634, in get_data return loader.get_data(resource_name) File "&lt;frozen importlib._bootstrap_external&gt;", line 832, in get_data FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Mike\\AppData\\Local\\Programs\\Python\\Python36-32\\lib\\site-packages\\selenium\\webdriver\\remote\\getAttribute.js' &gt;&gt;&gt; When I try to reinstall the package with pip, I am told that the requirements are satisfied. chromedriver.exe is in c:\Windows\system32. Any ideas greatly appreciated.
score: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/74330473
has answer: http://stackoverflow.com/a/55244623
has answer: http://stackoverflow.com/a/48860891
type: UnansweredQuestion

http://stackoverflow.com/q/48850234
tagged with: repeat
tagged with: python
accepted answer: http://stackoverflow.com/a/48850397
type: AnsweredQuestion
tagged with: python-3.x
tagged with: list
score: 0
upvote count: 1
downvote count: 1
type: Question
has title: Efficient Permutation of a Sorted List with Repetitions
has body: I have a list of names assigned to ranks, often with ranks duplicated. I want to generate all permutations of the list with keeping the ranks in sorted order. For example: [Sam(17), Harry(17), Bob(5), Sally(5)] would generate Sam(17), Harry(17), Bob(5), Sally(5) Sam(17), Harry(17), Sally(5), Bob(5) Harry(17), Sam(17), Bob(5), Sally(5) Harry(17), Sam(17), Sally(5), Bob(5) Essentially, for every distinct group of ranks, there are n! combinations. In this case it would be 2! * 2!. I'm having trouble finding an efficient way to do permutations for a list with 34 names across 8 ranks. I'm running out of memory trying to find 2! * 2! * 4! * 2! * 2! *8! * 4! * 10! different lists. Is there any efficient way to generate this list? How much memory would python need?
linked to: http://stackoverflow.com/q/48890902
has comment: http://stackoverflow.com/comment/84704120
has answer: http://stackoverflow.com/a/48850397
answer count: 1
tagged with: permutation
favorite count: 0

http://stackoverflow.com/comment/84892391
type: Comment
comment on: http://stackoverflow.com/a/48942868
type: AnswerComment
has text: Are you sure that this won't close the div tag unexpectedly.
score: 0

http://stackoverflow.com/q/48810468
answer count: 6
has answer: http://stackoverflow.com/a/48810638
has answer: http://stackoverflow.com/a/48827252
has answer: http://stackoverflow.com/a/67532140
has answer: http://stackoverflow.com/a/58585713
downvote count: 0
has comment: http://stackoverflow.com/comment/84637695
has body: I want to add internationalization to a project, so I use django-modeltranslation app. However, after following all the steps of configuration and running migrations, when I enter in my admin the model is registered, but when I click on it: "Something's wrong with your database installation. Make sure the appropriate database tables have been created, and make sure the database is readable by the appropriate user." Here's the code (note I have put it all in a file for clarity): INSTALLED_APPS = [ 'modeltranslation', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'nuggets', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'Trans', 'USER': 'postgres', 'PASSWORD': 'c1l2a3u4', 'HOST': '127.0.0.1', 'PORT': '5432', } } LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True gettext = lambda s: s LANGUAGES = ( ('en', gettext('English')), ('es', gettext('Spanish')), ) #Models code from django.db import models class News(models.Model): title = models.CharField(max_length=255) text = models.TextField() #Admin code from django.contrib import admin from .models import News from modeltranslation.admin import TranslationAdmin class NewsAdmin(TranslationAdmin): pass admin.site.register(News, NewsAdmin) #translation.py code from modeltranslation.translator import translator, TranslationOptions from .models import News class NewsTranslationOptions(TranslationOptions): fields = ('title', 'text',) translator.register(News, NewsTranslationOptions) ]2]2 I have tried before createing the models, after, with default db, with postgre... Nothing seems to work, help please!
favorite count: 0
tagged with: django-modeltranslation
accepted answer: http://stackoverflow.com/a/48827252
tagged with: django
tagged with: python
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48810892
has title: Error in db with modeltranslation in django
upvote count: 3
type: Question
possible better answer: http://stackoverflow.com/a/50739093
has answer: http://stackoverflow.com/a/50739093

http://stackoverflow.com/comment/84635753
score: 0
has text: you write `if ret:`, but what is ret here, don't think you've ever defined it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48815849

http://stackoverflow.com/q/48950421
has answer: http://stackoverflow.com/a/48950566
answer count: 1
tagged with: python
has title: Python ,Feature selection
tagged with: machine-learning
upvote count: 1
accepted answer: http://stackoverflow.com/a/48950566
type: AnsweredQuestion
has body: When I use RFE to select the most important features in my data set, it returns all features , instead of returning the number of features that I specified here is simple code: from sklearn.svm import SVC from sklearn.datasets import load_digits from sklearn.feature_selection import RFE import matplotlib.pyplot as plt new_X=np.array([[1,2,3,3],[1,2,4,4],[3,1,3,4],[3,1,4,5]]) new_Y=np.array([1,1,0,0]) svc = SVC(kernel="linear", C=1) rfe = RFE(estimator=svc, n_features_to_select=2, step=1) rfe.fit(new_X, new_Y) ranking = rfe.ranking_ len(ranking)
score: 1
type: Question
tagged with: rfe
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/84659126
score: 0
has text: So, Do I need to install MPFR in Heroku ?
comment on: http://stackoverflow.com/q/48825775
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48940974
downvote count: 1
has comment: http://stackoverflow.com/comment/84889189
score: -1
has body: If all the arrays are of the same length you can just go through them until you find an index that is the same for all 3. For example (python, O(n)) def findMatchingIndex(a, b, c): for index, val in enumerate(a): # enumerate through a to get the index of the item we are looking at... if val == b[index] and b[index] == c[index]: # if a = b and b = c then a = c return index # return the first shared index we find return -1 # or -1 for no index. # for example... findMatchingIndex([1, 2, 3], [2, 2, 1], [3, 2, 1]) # = 1 findMatchingIndex([1, 2, 3], [4, 5, 6], [3, 2, 1]) # = -1 EDIT However if they are not of the same length you will want to use the lowest common denominator which would be the minimum length. def findMatchingIndex2(a, b, c): # get the smallest size size = sorted( [ len(a), len(b), len(c) ] )[0] # sort the lengths of the arrays and get the smallest/first one for index in range (0, size): # go until the smallest array is done if a[index] == b[index] and b[index] == c[index]: # if a = b and b = c then a = c return index # return the first shared index we find return -1 # or -1 for no index. # for example... findMatchingIndex2([1, 2, 3], [2, 2, 1], [3, 2, 1]) # = 1 findMatchingIndex2([1, 2, 3], [2, 3, 3], [3, 3, 3]) # = 2 findMatchingIndex2([1, 2, 3], [2, 3, 3], [3, 3]) # = -1
accepted answer of: http://stackoverflow.com/q/48940905
upvote count: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48940905
type: Answer
has comment: http://stackoverflow.com/comment/84889396

http://stackoverflow.com/comment/84918579
score: 1
has text: When you say "minimum length of the most inner sub-lists", do you mean "the length of the shortest list that is at the same depth as the deepest list"? Or just "the length of the shortest list contained within the given list"?
comment on: http://stackoverflow.com/q/48955868
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84731708
has text: @rasmusgude I read that VHD files are created for disks in blob storage, but when I go and check there, I don't see any vhd file. Is it right that VHD files are created for disks automatically? And if yes, how do I get them? and if No, how to create and find them.
type: QuestionComment
comment on: http://stackoverflow.com/q/48856112
type: Comment
score: 0

http://stackoverflow.com/q/48873233
favorite count: 0
tagged with: python
upvote count: 4
type: AnsweredQuestion
has body: I'm trying to get a correlation in pandas that's giving me a bit of difficulty. Essentially I want to answer the following question: given a sentence and a value and a dataframe, what word correlates the best with a higher value? What about the worst? Trivial example: Sentence | Score "hello there" | 100 "hello kid" | 95 "there kid" | 5 I'm expecting to see a high correlation value here for the word "hello" and score. Hopefully this makes sense -- if this is possible natively in Pandas I'd really appreciate knowing! If anything is unclear please let me know.
downvote count: 0
type: Question
has title: Is there a way to get correlation with string data and a numerical value in pandas?
score: 4
answer count: 2
tagged with: pandas
has answer: http://stackoverflow.com/a/48873546
accepted answer: http://stackoverflow.com/a/48873546
possible better answer: http://stackoverflow.com/a/48873449
has answer: http://stackoverflow.com/a/48873449

http://stackoverflow.com/a/48963537
has comment: http://stackoverflow.com/comment/84934563
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84934803
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/119229996
type: Answer
has body: Which predictions get updated? Stepping through the code, the reason it's happening is all the Q values that aren't meant to be updated (the ones for actions we didn't take) increase slightly. It's my understanding that passing the networks own output to the network during training should keep the output the same, not increase or decrease it. Below I have drawn a very simple neural network with 3 input nodes, 3 hidden nodes, and 3 output nodes. Suppose that you have only set a new target for the first action, and simply use the existing predictions as targets again for the other actions. This results in only a non-zero (for simplicity I'll just assume greater than zero) error (denoted by delta in the image) for the first action/output, and errors of 0 for the others. I have drawn the connections through which this error will be propagated from output to hidden layer in bold. Note how each of the nodes in the hidden layer still gets an error. When these nodes then propagate their errors back to the input layer, they'll do this through all of the connections between input and hidden layer, so all of those weights can be modified. So, imagine all those weights got updated, and now imagine doing a new forwards pass with the original inputs. Do you expect output nodes 2 and 3 to have exactly the same outputs as before? No, probably not; the connections from hidden nodes to the last two outputs may still have the same weights, but all three hidden nodes will have different activation levels. So no, the other outputs are not guaranteed to remain the same. Is there some way I can mask the update so it only updates the relevant Q value? Not easily no, if at all. The problem is that the connections between pairs of layers other than the connections between the final pair are not action-specific, and I don't think you want them to be either. Target Network Is there something wrong with my model? One thing I'm seeing is that you seem to be updating the same network that is used…
answers question: http://stackoverflow.com/q/48898104
accepted answer of: http://stackoverflow.com/q/48898104

http://stackoverflow.com/q/48939473
has comment: http://stackoverflow.com/comment/84886182
has comment: http://stackoverflow.com/comment/84886117
has answer: http://stackoverflow.com/a/48939629
has comment: http://stackoverflow.com/comment/84886236
has comment: http://stackoverflow.com/comment/84886277
has comment: http://stackoverflow.com/comment/84886186
downvote count: 1
has title: Python: Basic L-System: Axiom and Rules
type: Question
tagged with: function
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/84886220
answer count: 1
has comment: http://stackoverflow.com/comment/84886278
favorite count: 0
has body: The tests (the calling of the function) that I am using are: rewrite('A', {'A':'AB','B':'A'}, 2) &gt;&gt;&gt; 'ABA' rewrite('A', {'A':'AB','B':'A'}, 4) &gt;&gt;&gt; 'ABAABABA' rewrite('A', {'A':'AB','B':'A'}, 0) &gt;&gt;&gt; 'A' They are not working and I can't figure out what the problem is. This is an L-System that essentially stacks a rule upon another rule depending on how many iterations the user request, here is an example of what I mean. I know this can be done using multiple functions, but I have to figure out how to run it all in one. def rewrite(word, prod, n): start1 = list(prod.keys())[0] rule1 = list(prod.values())[0] start2 = list(prod.keys())[1] rule2 = list(prod.values())[1] newWord = "" if word == start1: newWord = rule1 newWord1 = "" i = 0 for i in range(n): for x in newWord: if x == start1: newWord1 = newWord1 + rule1 newWord = newWord1 i += 1 elif x == start2: newWord1 = newWord1 + rule2 newWord = newWord1 i += 1 else: newWord1 = newWorld1 if word == start2: newWord = rule2 newWord1 = "" i = 0 for i in range(n): for x in newWord: if x == start1: newWord1 = newWord1 + rule1 newWord = newWord1 i += 1 elif x == start2: newWord1 = newWord1 + rule2 newWord = newWord1 i += 1 else: newWord1 = newWord1 else: newWord1 = word # no rules apply so keep the character return newWord1 I know that I can do it this way and that this way works: def rewrite(word, production, n): for i in range(n): newWord = '' for x in word: if x in production: newWord += production[x] else: newWord += x word = newWord return word But I spent a lot of time on the one above, and although it is very complicated, I wanted to know if I was on the right track.
type: UnansweredQuestion
tagged with: python
tagged with: dictionary

http://stackoverflow.com/comment/84639783
type: QuestionComment
has text: I also try this: `class FullNameForeignKeyWidget(ForeignKeyWidget): def get_queryset(self, value, row): return self.model.objects.filter( date__iexact=row["date"], requestChannel__iexact=row["requestChannel"], problem__iexact=row["problem"], solution__iexact=row["solution"] ) class UsersResource(resources.ModelResource): userRequest = fields.Field(column_name='userRequest', attribute='userRequest', widget=FullNameForeignKeyWidget(UsersRequests))` but it's not working too
comment on: http://stackoverflow.com/q/48817433
score: 0
type: Comment

http://stackoverflow.com/comment/84635864
has text: yeah i didn't see the `if ret` i changed the question now ^^
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48815849
score: 0

http://stackoverflow.com/comment/84858341
comment on: http://stackoverflow.com/a/48907637
score: 0
type: AnswerComment
has text: My game is to ask people to guess a number, so it will have many settings, but not just text. I don't know how to make controls of list.
type: Comment

spyder
tag name: spyder
tags question: http://stackoverflow.com/q/48881224
tags question: http://stackoverflow.com/q/48953189
tags question: http://stackoverflow.com/q/48860709
tags question: http://stackoverflow.com/q/48813309
tags question: http://stackoverflow.com/q/48902370
type: Tag
tags question: http://stackoverflow.com/q/48831091
tags question: http://stackoverflow.com/q/48845796

http://stackoverflow.com/comment/84771402
has text: You are sorting the strings by alphabetic order, convert your strings to some date format to be able to sort them.
comment on: http://stackoverflow.com/q/48883493
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/84722579
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48859561
has text: Use regex to obtain numbers with $

http://stackoverflow.com/comment/84733157
score: 0
comment on: http://stackoverflow.com/q/48864655
type: QuestionComment
has text: @Yohboy or at least to combine xlsx writer with saveas function. So that all the processes are automatized
type: Comment

http://stackoverflow.com/q/48811239
possible better answer: http://stackoverflow.com/a/48811305
has answer: http://stackoverflow.com/a/48811305
tagged with: sql
score: 3
tagged with: python
has answer: http://stackoverflow.com/a/48865788
favorite count: 0
accepted answer: http://stackoverflow.com/a/48865788
downvote count: 1
type: AnsweredQuestion
has body: I'm trying to write MySQL query in the sqlalchemy syntax, but I don't know how to represent aliasForC. Could you help me? Query with aliasForC alias: SELECT aliasForC.secondId FROM A, B, C as aliasForC WHERE B.firstId = A.firstId AND B.status = 'Reprep' AND A.secondId = aliasForC.secondId AND B.status = ALL ( SELECT status FROM C INNER JOIN A ON A.secondId = C.secondId INNER JOIN B ON A.firstId = B.firstId WHERE code = aliasForC.code )
tagged with: sqlalchemy
type: Question
upvote count: 4
answer count: 2
has title: How to set alias in the sqlalchemy for the table?

http://stackoverflow.com/q/48897200
has body: It seems there's a bug in the HDFStore module in Pandas when making certain queries but I cannot find a workaround. Namely, it seems that pd.HDFStore.select internally re-formats otherwise valid strings into bad syntax. For example, the string "03" will, for some reason, enter the where statement as "0 3" which returns a syntax error. sample data: p1 = np.random.randint(0,100,(100,2)) p2 = np.random.choice(np.array(range(1990,2010)),100).reshape((100,1)) df = pd.DataFrame(np.concatenate([p2,p1],axis=1), columns = ['year', 'value1', 'value2']) df.year2 = df.year.astype(str).str[2:] data_path = "C:/Users/.../some path" with pd.HDFStore("/".join([data_path, 'sampleData.h5']), 'w') as store: store.put('example', df, format='table') query- working query1 = 'year2&lt;={0}'.format('99') query2 = "year2=={0} | year2=={1}".format('01', '02') with pd.HDFStore("/".join([data_path, 'sampleData.h5']), 'r') as store: df_load = store.select('example', where=[query1],columns = ['year', 'year2', 'value1']) query - not working In [111]: %paste with pd.HDFStore("/".join([data_path, 'sampleData.h5']), 'r') as store: df_load = store.select('example', where=[query2],columns = ['year', 'year2', 'value1']) ## -- End pasted text -- File "&lt;unknown&gt;", line 1 (year2 ==0 1 or year2 ==0 2 ) ^ SyntaxError: invalid syntax Does anyone know of a workout that won't separate "01" into "0 1"?
answer count: 1
tagged with: string
score: 0
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48937629
tagged with: python
type: Question
type: AnsweredQuestion
tagged with: hdf
has title: Pandas HDF query interpreter workaround
has answer: http://stackoverflow.com/a/48937629

http://stackoverflow.com/comment/84727028
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48862002
has text: `.cat.codes()` -> `.cat.codes`. If something is not a function, do not call it.

http://stackoverflow.com/a/48847737
type: Answer
answers question: http://stackoverflow.com/q/48847349
downvote count: 0
score: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48847349
has body: You need to save the file: filename = '' # This can be the same filename or a different one wb.save(filename) Please see Saving to a file in the documentation linked here.
upvote count: 2

http://stackoverflow.com/comment/84928232
score: 0
type: Comment
type: QuestionComment
has text: @Ayush Shanker How do I find the encoding? I used type(x) it gives me <class 'numpy.str_'>
comment on: http://stackoverflow.com/q/48960939

http://stackoverflow.com/q/48953875
has title: Copying data from one pandas dataframe to other based on column value and separated by comma
tagged with: python
has comment: http://stackoverflow.com/comment/84914677
score: 2
type: AnsweredQuestion
downvote count: 0
tagged with: dataframe
type: Question
upvote count: 2
answer count: 1
favorite count: 0
has body: I have two dataframes viz., df1 and df2. df1 is like Index YH HE MT CU EI 0 Dot Sf Sy Lc 1 Rls Bd Sa Ta 2 Fs Ft Rg And df2 is like Index Z1 Z2 Z3 0 YH HE 1 HE EI 2 MT CU I want a df3 which looks like this Index Z1 Z2 Z3 0 YH HE 1 HE EI 2 MT CU 3 Dot,Rls,Fs Sf,Bd 4 Sf,Bd 5 Sy,Sa,Ft Lc,Ta,Rg Basically, in one cell only but separated by a comma. The comma separated cell is obtained from df1. In df3, the rows 3,4,5 correspond to rows 0,1,2 (0,Z1) of df2 is YH and column YH in df1 is Dot,Rls,Fs So Dot,Rls,Fs comes at (3,Z1) in df3 (1,Z1) of df2 is HE and HE column has Sf,BD in df1 So Sf,Bd comes at (4,Z1) in df3 Similarly, for all others. Please let me know if it is still not clear.
tagged with: pandas
has answer: http://stackoverflow.com/a/48954119
accepted answer: http://stackoverflow.com/a/48954119

http://stackoverflow.com/q/48852976
has answer: http://stackoverflow.com/a/48853018
favorite count: 0
accepted answer: http://stackoverflow.com/a/48853032
tagged with: selenium
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
has title: Opening several URLs in same tab one by one using Selenium Python
has body: This is my script where a JSON file contains all the URLs to be opened. What this script does is, it opens a URL takes screenshot and closes it; then opens a new one and so on. What if I want to keep using the same browser session for all these URLs. Like Go to site 1, take screen cap. Now go to site 2 in the same browser/tab. and close the session/browser only at the last URL. import json from selenium.webdriver import Chrome with open('path to json file', encoding='utf-8') as s: data = json.loads(s.read()) for site in data['sites']: driver = Chrome('path to chrome driver') driver.get(data['sites'][site]) driver.get_screenshot_as_file(site + '.png') driver.close()
type: Question
answer count: 2
score: 5
upvote count: 5
downvote count: 0
possible better answer: http://stackoverflow.com/a/48853018
has answer: http://stackoverflow.com/a/48853032

http://stackoverflow.com/comment/84780915
score: 0
type: Comment
has text: @Louc : df['Iext'] is float type. Values in millions/billions.. Same goes for df['OT']... Do these all numbers need to be positive ? Is that the reason ? df['Month'] is simply the yyyy-mm format datetime...
type: QuestionComment
comment on: http://stackoverflow.com/q/48881348

http://stackoverflow.com/comment/84871041
comment on: http://stackoverflow.com/q/48932007
score: 0
has text: I mean what should I put inside each of the print statements to return ######### with said text inside
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84680379
comment on: http://stackoverflow.com/a/48837832
type: AnswerComment
score: 0
type: Comment
has text: Cool! Another non groupy option. Note though, that you will want to group on Date1 as well.

http://stackoverflow.com/a/48958260
type: Answer
has body: To set the label color in the rcParams as well use text.color: blue axes.labelcolor: blue or, from within the script mpl.rcParams.update({'text.color' : "blue", 'axes.labelcolor' : "blue"})
score: 8
downvote count: 0
answers question: http://stackoverflow.com/q/48958208
upvote count: 8

http://stackoverflow.com/q/48891727
has comment: http://stackoverflow.com/comment/84795353
has comment: http://stackoverflow.com/comment/84794328
tagged with: linux-kernel
linked to: http://stackoverflow.com/q/33741002
accepted answer: http://stackoverflow.com/a/48894210
type: AnsweredQuestion
has title: Using socket AF_PACKET / SOCK_RAW but tell kernel to not send RST
favorite count: 0
has comment: http://stackoverflow.com/comment/84794998
has comment: http://stackoverflow.com/comment/84815928
tagged with: linux
type: Question
tagged with: sockets
score: 5
tagged with: python
has comment: http://stackoverflow.com/comment/84794584
answer count: 1
linked to: http://stackoverflow.com/q/31762305
tagged with: raw-sockets
has comment: http://stackoverflow.com/comment/112282886
has body: My question has roughly been discussed here. And the tl;dr solution is to do: iptables -A OUTPUT -p tcp --tcp-flags RST RST -j DROP And you could modify this to only block the port you're actively listening after. But as mentioned in the above question, and here, these are not elegant solutions. Now, I don't really care about the elegance of things. But I do care about learning. So I've dug deep into the Linux source code (mostly interested in Linux based machines for now) and sorted through what I think is the socket.bind method in order to find anything related to instructing the kernel that "we" are actively monitoring a TCP port. I assumed that the socket library informed the kernel some how about a specific port being bound to a application, this so that the kernel don't automatically respond with a RST packet to the client connecting, prompting a "Connection refused". However, I find no such code in the source code. Nor does the packet man page tell me anything about how to inform the kernel to ignore/accept packets coming in on a specific port. I've got a pretty basic socket set up to listen with promiscuous mode (that is a tale of it's own). However, my problem is that as soon as a client connects, on any given port - the kernel sends the incoming Ethernet+IP+TCP data frame my way as expected - but it also instantly sends out a response with "reversed" source and destination ports and the RST flag set. Which it should, but not on a specific port I tell it to. Problem is, how do I tell the kernel I'm monitoring a specific port? One option would be to (as discussed in some other forums and on other various SO threads) - create a dummy socket on that port. s = socket() s.bind(('', &lt;port&gt;)) However, that causes a bunch of other problems (one of which is that this will have a buffer that will quickly be filled) and most importantly, still doesn't teach me how all this magic happens. The two above solutions are last resort if there's no other ways, but I fee…
has answer: http://stackoverflow.com/a/48894210
has comment: http://stackoverflow.com/comment/84796619
has comment: http://stackoverflow.com/comment/84806106
upvote count: 5
has comment: http://stackoverflow.com/comment/112285635
downvote count: 0

http://stackoverflow.com/q/48819547
answer count: 3
downvote count: 1
has title: multiple logarithm in numpy
linked to: http://stackoverflow.com/q/35398472
has comment: http://stackoverflow.com/comment/84643137
has comment: http://stackoverflow.com/comment/84644563
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48820217
linked to: http://stackoverflow.com/q/7359828
tagged with: python
has comment: http://stackoverflow.com/comment/84643093
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84642937
has answer: http://stackoverflow.com/a/48819598
accepted answer: http://stackoverflow.com/a/48819598
score: 1
has comment: http://stackoverflow.com/comment/84642981
type: Question
tagged with: numpy
has body: I want take logarithm multiple times. We know this import numpy as np np.log(x) now the second logarithm would be np.log(np.log(x)) what if one wants to take n number of logs? surely it would not be pythonic to repeat n times as above.
possible better answer: http://stackoverflow.com/a/48820217
has answer: http://stackoverflow.com/a/48821548
tagged with: arrays
upvote count: 2

http://stackoverflow.com/q/48937176
type: Question
has body: I am trying to create a 3-D plot and a 2-D plot side-by-side in python. I need equal aspect ratios for both plots, which I managed using code provided by this answer: https://stackoverflow.com/a/31364297/125507. The problem I'm having now is how to effectively "crop" the 3-D plot so it doesn't take up so much white space. That is to say, I want to reduce the length of the X and Y axes while maintaining equal scale to the (longer) Z-axis. Here is a sample code and plot: from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.pyplot as plt import numpy as np def set_axes_equal(ax): '''Make axes of 3D plot have equal scale so that spheres appear as spheres, cubes as cubes, etc.. This is one possible solution to Matplotlib's ax.set_aspect('equal') and ax.axis('equal') not working for 3D. Input ax: a matplotlib axis, e.g., as output from plt.gca(). ''' x_limits = ax.get_xlim3d() y_limits = ax.get_ylim3d() z_limits = ax.get_zlim3d() x_range = abs(x_limits[1] - x_limits[0]) x_middle = np.mean(x_limits) y_range = abs(y_limits[1] - y_limits[0]) y_middle = np.mean(y_limits) z_range = abs(z_limits[1] - z_limits[0]) z_middle = np.mean(z_limits) # The plot bounding box is a sphere in the sense of the infinity # norm, hence I call half the max range the plot radius. plot_radius = 0.5*max([x_range, y_range, z_range]) ax.set_xlim3d([x_middle - plot_radius, x_middle + plot_radius]) ax.set_ylim3d([y_middle - plot_radius, y_middle + plot_radius]) ax.set_zlim3d([z_middle - plot_radius, z_middle + plot_radius]) ax = [None]*2 fig = plt.figure() ax[0] = fig.add_subplot(121, projection='3d', aspect='equal') ax[1] = fig.add_subplot(122, aspect='equal') nn = 30 phis = np.linspace(0,np.pi, nn).reshape(1,nn) psis = np.linspace(0,np.pi*2,nn).reshape(nn,1) ones = np.ones((nn,1)) el_h = np.linspace(-5, 5, nn).reshape(1,nn) x_sph = np.sin(phis)*np.cos(psis) y_sph = np.sin(phis)*np.sin(psis) z_sph = np.cos(phis)*ones x_elp = np.sin(phis)*np.cos(psis)*.25 y_elp = np.sin(p…
linked to: http://stackoverflow.com/q/13685386
linked to: http://stackoverflow.com/q/31888825
has comment: http://stackoverflow.com/comment/84918236
tagged with: python
has comment: http://stackoverflow.com/comment/84903016
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: plot
has comment: http://stackoverflow.com/comment/84918600
linked to: http://stackoverflow.com/q/8130823
tagged with: mplot3d
has comment: http://stackoverflow.com/comment/84903203
tagged with: matplotlib
has title: Reducing axis length while maintaining equal aspect ratio in 3D plot

http://stackoverflow.com/comment/84729853
comment on: http://stackoverflow.com/q/48863307
has text: what is users.backend.Authbackend?? can you post that code too?
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84751543
type: QuestionComment
has text: Hi @martineau it allows my code function to be run on a specified interval of time but I understand your point that it is not standard and makes simulation harder for others. I have removed it as it isn't part of the problem! Thanks for the tips!
score: 0
comment on: http://stackoverflow.com/q/48870758
type: Comment

http://stackoverflow.com/comment/84838436
type: Comment
has text: It's 2018, and this ought to work across all platforms: `open('poop.txt', 'w').write('')`
type: AnswerComment
comment on: http://stackoverflow.com/a/48914927
score: 0

http://stackoverflow.com/comment/84741075
has text: Cheers this is very helpful exactly what I was looking for.
score: 1
comment on: http://stackoverflow.com/a/48868718
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84757261
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48876573
has text: would you say that your wrote a for loop `for` each `n in range(10)`?
type: Comment

http://stackoverflow.com/q/48919241
linked to: http://stackoverflow.com/q/14302248
tagged with: python
score: -1
tagged with: django
downvote count: 1
type: AnsweredQuestion
tagged with: django-views
has answer: http://stackoverflow.com/a/48919401
tagged with: django-models
linked to: http://stackoverflow.com/q/48912441
has comment: http://stackoverflow.com/comment/84845226
has body: I'm new to Django. I'm using Mezzanine 4.2.3 (Django 1.10.8 under the hood according to requirements.txt). I have a Postgres database of details about movies. I want to display 10 movies on a page. I tried asking about this method but couldn't get a suitable solution, so now I'm trying to to write my own SQL query. But, I don't know how to create the context. In the code below, I first randomly collect ten countries from a list of countries. Next, I iterate over the list and use each country to acquire a row in a Postgres database. Then, I make a dictionary from each row and become stuck at trying to make the context for the template. import psycopg2 from psycopg2 import sql from .countries import countries # Just a Python list of countries import random class MoviesListView(generic.ListView): model = Movies connection = psycopg2.connect([DB DETAILS]) c = connection.cursor() def get_context_data(self, **kwargs): random_countries = [] while len(random_countries) &lt; 10: choice = random.choice(countries) if choice not in random_countries: random_countries.append(choice.lower()) else: pass for country in random_countries: get_rows = "SELECT * FROM movies WHERE LOWER(production_countries) LIKE %s LIMIT 1;" c.execute(get_rows, ('%' + country + '%',)) rows = c.fetchall() for i in rows: row_dict = {} row_dict['id'] = i[0] row_dict['original_title'] = i[3] row_dict['release_date'] = i[6] row_dict['production_countries'] = i[8] # Point at which I'm stuck. # Context().push(row_dict) # return Movies.objects.raw(get_rows, ('%' + country + '%',)) template_name = r"movies_crud/movies_list.html" I read the Django documentation on Context() and I thought either Context().push() or Context.update() would help create the context. But it's not working out. I also tried .raw() but it won't work because I'm trying to generate the context dynamically with a for loop. How do we make a Django context in this case? Update: To give an idea of what I'm trying to do, the template looks like t…
possible better answer: http://stackoverflow.com/a/48919676
type: Question
has comment: http://stackoverflow.com/comment/84845398
answer count: 2
has answer: http://stackoverflow.com/a/48919676
has title: How to create Django context from dictionaries made from Postgres database
upvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48919401
tagged with: postgresql

http://stackoverflow.com/q/48909667
tagged with: pyramid
type: Question
tagged with: python
has body: Let's say I have this simplified app, named "Alambic". I left out the auth policy stuff, at this point I'm curious about what's the best way to tackle testing in the context of pyramid_ldap3 auth. I can try to get a lightweight repository set up with a minimal working example if the following isn't enough (in which case I'll amend this post). __init__.py: import ldap3 from pyramid.config import Configurator def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.include('pyramid_ldap3') config.ldap_setup( 'ldap://localhost', bind='uid=dummy,ou=people,dc=domain,dc=fr', passwd='passwd' ) config.ldap_set_login_query( base_dn='ou=people,dc=domain,dc=fr', filter_tmpl='(uid=%(login)s)', scope=ldap3.LEVEL, ) config.ldap_set_groups_query( base_dn='ou=people,dc=domain,dc=fr', filter_tmpl='(uid=%(userdn)s)', scope=ldap3.LEVEL, attributes=ldap3.ALL_ATTRIBUTES, ) config.add_route('home', '/') # No auth config.add_route('menu', '/menu') # Needs LDAP auth config.scan() return config.make_wsgi_app() views.py: from pyramid.view import view_config @view_config(route_name='menu', permission='auth') def menu(request): ...some code... Now I know about pyramid-ldap-test, which is nice to have a local server to connect against, however I'm stuck trying to get my unittest setup. Getting the db tested is fine (so I left it out here), but for some reason, I can't get the ldap settings to register in my tests. I use testing.DummyRequest, but for some reason all the LDAP data/settings fail to stick even though they are processed correctly. I end up getting a ConfigurationError : pyramid.exceptions.ConfigurationError: You must call Configurator.ldap_setup during setup to use an LDAP connector. This is what my tests.py looks like: import unittest import transaction from pyramid import testing import ldap3 from ldap_test import LdapServer server = LdapServer(java_delay=1) class BaseTest(unittest.TestCase): def…
upvote count: 1
type: UnansweredQuestion
has title: How to properly test a pyramid_ldap3 based app?
answer count: 0
downvote count: 0
score: 1
favorite count: 0

http://stackoverflow.com/comment/84802955
type: QuestionComment
comment on: http://stackoverflow.com/q/48898690
has text: Also keys can be preceded by beginning of string, unless that string is supposed to have a space at the beginning of it.
score: 0
type: Comment

http://stackoverflow.com/comment/84700402
type: QuestionComment
has text: Either `hello` and `hi` should just return the absolute string instead of printing it. Or just replace `print(x('hello..` with `x('hello...)`
score: 0
comment on: http://stackoverflow.com/q/48848242
type: Comment

http://stackoverflow.com/comment/84801054
type: Comment
comment on: http://stackoverflow.com/a/48897556
score: 0
type: AnswerComment
has text: @SamCraig you're right I want a newline after each paragraph and dictionary have one comment for iteration.

http://stackoverflow.com/a/48917274
type: Answer
has body: This is one way. def transformer(data): for k, v in data.items(): if isinstance(v, list): data[k] = [tuple(v)] elif isinstance(v, dict): data[k] = [tuple(chain(*(v.items())))] else: data[k] = [v] return data df = pd.DataFrame(transformer(data), index=['a']) # w x y z # a (1, 2, 3, 4) 1 (1, 2, 3) (4, 5, 6)
answers question: http://stackoverflow.com/q/48917141
score: 0

http://stackoverflow.com/comment/84720879
type: Comment
has text: can this function remove the nodes from the original single list?
comment on: http://stackoverflow.com/a/48858091
type: AnswerComment
score: 0

http://stackoverflow.com/a/54480966
answers question: http://stackoverflow.com/q/48934840
has comment: http://stackoverflow.com/comment/102247681
type: Answer
accepted answer of: http://stackoverflow.com/q/48934840
has body: You don't need to activate a virtual env to run pip in it, you just use the path of the pip binary in the virtualenv and it will install it within that virtualenv. proc.execFile("myapp/venv/bin/pip", { args: ["install", "myPipModule"]}, function() { // do stuff });
has comment: http://stackoverflow.com/comment/102244272
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/102253718

http://stackoverflow.com/comment/84915019
type: QuestionComment
has text: from the crawls
comment on: http://stackoverflow.com/q/48913525
score: 0
type: Comment

http://stackoverflow.com/comment/84668071
type: AnswerComment
type: Comment
has text: in my solution I call `w.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)` instead of calling `resizeColumnsToContents()` because it automatically updates the size and I do not need to call it at any time.
comment on: http://stackoverflow.com/a/48818732
score: 0

http://stackoverflow.com/q/48815807
has answer: http://stackoverflow.com/a/48867900
linked to: http://stackoverflow.com/q/44976677
has comment: http://stackoverflow.com/comment/84635891
score: 0
tagged with: token
answer count: 1
tagged with: access-token
tagged with: python
has title: If a token hasn't been used in a week, the token should expire
has body: The expiration time for the token I am creating is one week expiration_time = timedelta(weeks=1) app.config['JWT_ACCESS_TOKEN_EXPIRES'] = expiration_time How do I make the token last longer if the user use it before it expires? like e.g. if the user uses the token and sends a message, I would like to refresh the token's expiration time and make it a week again. Is there any way to do so?
tagged with: jwt
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48867900
type: Question

http://stackoverflow.com/comment/84627558
comment on: http://stackoverflow.com/a/48810770
has text: Thank you so much #humodz ! That's exactly what I am looking for. Is there any way to store the out put in to the database (mysql or sqligh) ?
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48864287
accepted answer: http://stackoverflow.com/a/48864333
upvote count: 1
answer count: 1
has title: Getting error regarding "os" module of python
favorite count: 0
has answer: http://stackoverflow.com/a/48864333
tagged with: python
downvote count: 3
has body: I am using python2.7 on ubuntu system. I am getting following errors while working with "os": AttributeError: 'module' object has no attribute 'fsencode' On this line: directory=os.fsencode(indir) I have checked other solutions but they are not relevant.
tagged with: python-os
type: AnsweredQuestion
score: -2
type: Question
tagged with: python-2.7

http://stackoverflow.com/q/48873483
type: UnansweredQuestion
tagged with: qevent
tagged with: python
score: 2
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/84758672
has comment: http://stackoverflow.com/comment/84755356
has comment: http://stackoverflow.com/comment/84753996
has body: Wacom has no official python SDK. Nevertheless, PyQt has a QTabletEvent that handles these tablets. Alas, I found no working python example of this. One can see a c++ example here. Can anyone please refer me to a python example?
has answer: http://stackoverflow.com/a/49208287
upvote count: 4
tagged with: wacom
tagged with: pyqt
answer count: 1
favorite count: 0
has title: Python example for Wacom tablets

http://stackoverflow.com/comment/84745113
comment on: http://stackoverflow.com/q/48869966
has text: @quamrana The issue I am seeing is that once I turn these files into a package, and I run the first function, the 'new_table' argument isnt available to the second function. I am going to take a look at Paula's post below and see if that solves it for me.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84783998
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48873995
has text: @ead There can be any number of columns in theory but typically its less than 100. They can also be any type and in reality I will have several 2D arrays each of a different type. Essentially, I have a table of data from a database and want to find the unique rows.

http://stackoverflow.com/q/48807726
score: -2
has comment: http://stackoverflow.com/comment/84618664
has body: I have tried searching online but I can't seem to find anything that would answer this question. I current have a script that is running, and I am using an if statement to catch anomaly. if test &lt;= limit: return True This works as intended, but I am looking to reduce said code into a single line like return True if test &lt;= limit else [continue with script] But I have no idea what to put in the [continue with script] part.
has answer: http://stackoverflow.com/a/48809039
accepted answer: http://stackoverflow.com/a/48809039
has comment: http://stackoverflow.com/comment/84618799
downvote count: 3
upvote count: 1
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84619240
has comment: http://stackoverflow.com/comment/84618784
has comment: http://stackoverflow.com/comment/84618966
tagged with: python
has comment: http://stackoverflow.com/comment/84618245
has comment: http://stackoverflow.com/comment/84618519
type: AnsweredQuestion
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84618288
has comment: http://stackoverflow.com/comment/84619088
has title: Is there a way to continue my script after running an if statement to catch anomaly in Python?
type: Question
has comment: http://stackoverflow.com/comment/84620393
tagged with: if-statement

http://stackoverflow.com/comment/84734028
type: QuestionComment
has text: Are you sure this is valid json?
score: 1
comment on: http://stackoverflow.com/q/48865303
type: Comment

http://stackoverflow.com/comment/84880751
score: 0
type: AnswerComment
type: Comment
has text: @IrinaS, can you post your desired data set in your question?
comment on: http://stackoverflow.com/a/48936133

http://stackoverflow.com/comment/84860506
type: AnswerComment
comment on: http://stackoverflow.com/a/48925892
score: 0
type: Comment
has text: https://files.fm/f/68w5qkvk so the file is called hotelname_Action_Log.xlsx therefore in this case I need cell B2 to become "hotelname"

http://stackoverflow.com/a/48909657
downvote count: 0
has comment: http://stackoverflow.com/comment/84825352
has body: A simple workaround would be to replace all the \n characters in the document text before you search it: pat = re.compile(r'\(\d{3}\)-\d{3}\d{4}') numbers = pat.findall(text.replace('\n','')) # ['(555)-555-5555'] If this cannot be done for any reasons, the obvious answer, though unsightly, would be to handle a newline character between each search character: pat = re.compile(r'\(\n*5\n*5\n*5\n*\)\n*-\n*5\n*5\n*5\n*-\n*5\n*5\n*5\n*5') If you needed to handle any format, you can pad the format like so: phonenumber = '(555)-555-5555' pat = re.compile('\n*'.join(['\\'+i if not i.isalnum() else i for i in phonenumber])) # pat # re.compile(r'\(\n*5\n*5\n*5\n*\)\n*\-\n*5\n*5\n*5\n*\-\n*5\n*5\n*5\n*5', re.UNICODE) Test case: import random def rndinsert(s): i = random.randrange(len(s)-1) return s[:i] + '\n' + s[i:] for i in range(10): print(pat.findall(rndinsert('abc (555)-555-5555 def'))) # ['(555)-555-5555'] # ['(555)-5\n55-5555'] # ['(555)-5\n55-5555'] # ['(555)-555-5555'] # ['(555\n)-555-5555'] # ['(5\n55)-555-5555'] # ['(555)\n-555-5555'] # ['(555)-\n555-5555'] # ['(\n555)-555-5555'] # ['(555)-555-555\n5']
score: 1
has comment: http://stackoverflow.com/comment/84825777
has comment: http://stackoverflow.com/comment/84826114
accepted answer of: http://stackoverflow.com/q/48909309
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48909309
has comment: http://stackoverflow.com/comment/84825407
type: Answer
has comment: http://stackoverflow.com/comment/84825544

http://stackoverflow.com/comment/84672534
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48833803
has text: @spikespaz its giving me error... Attribute error Ui_dialogAdd has no attribute 'close' when i use self.close()

http://stackoverflow.com/q/48939712
type: Question
tagged with: python
answer count: 1
downvote count: 1
accepted answer: http://stackoverflow.com/a/48939906
has body: hoping for a little help, i need to scrap the the id and temperature. I have tried a couple things but i cannot get it right can someone help.i am using BeautifulSoup to get the information then print it 21.1 ºC
score: 0
upvote count: 1
has title: need guidance with retrieving data from span id
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48939906
favorite count: 0

http://stackoverflow.com/q/48874002
has answer: http://stackoverflow.com/a/48874111
downvote count: 0
score: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
type: Question
upvote count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48874111
has title: How to parse text structure with beautifulsoup?
answer count: 1
has body: i want to parse some information in python with beautifulsoup. This is the source HTML: 21:07 John Room 1 21:10 Susi Room 2 .... I want to output all in the following way: 21:07 John Room 1 21:10 Susi Room 2 What i tried until now: page = urlopen(html_page) soup = BeautifulSoup(page, 'lxml') soup.prettify() times = soup.find_all('dt', {'class': 'time'}) roominfos = soup.find_all('li', {'class': 'title'}) for time in times: print(time.text) for roominfo in roominfos: print(roominfo.text) I only manage to get the time item and the room information seperatly, but not side by side. How could i do this? Thanks.
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/q/48891382
has title: Stacking matrices to make a matrix with sites of parent matrices map as block diagonals
type: UnansweredQuestion
tagged with: python
score: 1
tagged with: scipy
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84788219
has comment: http://stackoverflow.com/comment/84788418
has comment: http://stackoverflow.com/comment/84788492
has body: How stack matrices as follows in python such that elements of parent matrices make a block diagonal at the same block diagonal site of the daughter matrix. example: I have four matrices AA,AB,BA, BB I want to make the matrix out as shown in attached image.
has comment: http://stackoverflow.com/comment/84788700
upvote count: 1
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48891747
favorite count: 0

http://stackoverflow.com/comment/84710588
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48853565
has text: I think you're right. But that's not formulated as an answer
score: 0

http://stackoverflow.com/q/48886830
has title: A memory efficient alternative to generating this nested list?
favorite count: 0
has comment: http://stackoverflow.com/comment/84792041
has comment: http://stackoverflow.com/comment/84786766
answer count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
has body: I have been trying to convert a large list of rgb arrays to hsv arrays in the following way and it got killed every time due to memory, could anyone kindly suggest a better way to do it? Preferably the result should be a large list of hsv arrays but if that's not the way to go, I'm good with any other forms of storage to work with. Here are my current codes: os.chdir("/mnt/saswork/sh2264/vision/code") X_train_matched = np.load("X_train_scores.npy") R = [r[0] for r in X_train_matched] G = [g[1] for g in X_train_matched] B = [b[2] for b in X_train_matched] import colorsys #hsv = [[[colorsys.rgb_to_hsv(x,y,z) for x,y,z in zip(a,b,c)]for a,b,c in zip(d,e,f)] for d,e,f in zip(R,G,B)] # this is too memory intense hsv = [] for image in X_train_matched: hsv.append([colorsys.rgb_to_hsv(x,y,z) for x,y,z in zip(a,b,c)] for a,b,c in zip(image[0],image[1],image[2])]) Thanks a million!
has comment: http://stackoverflow.com/comment/84790805
linked to: http://stackoverflow.com/q/42198408
has comment: http://stackoverflow.com/comment/84778424
tagged with: image-processing
tagged with: memory
tagged with: image
type: Question
tagged with: numpy
score: 2
downvote count: 0

http://stackoverflow.com/comment/84734823
comment on: http://stackoverflow.com/q/48865441
has text: The problem is within the file uploads code, not the csrftoken (the file uploads code call is triggered on the first access to `request.POST`, which happens to be the csrftoken verification). The first thing I'd do would be to uninstall then reinstall django - preferably using a virtualenv this time. If the problem persists, I'd edit django/http/multipartparser.py to add a pdb breakpoint just before the offending line (line 364 in your traceback) and check what happens (and specially what `remaining` actually is at this point and why it's not what it's supposed to be). Basic debugging really
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48883555
has comment: http://stackoverflow.com/comment/84771372
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84771410
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84771374
accepted answer: http://stackoverflow.com/a/48884009
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48883608
has answer: http://stackoverflow.com/a/48883608
type: Question
answer count: 2
downvote count: 4
upvote count: 0
has comment: http://stackoverflow.com/comment/84771507
has body: First of all, I am a Django rookie, so pls get that. I am trying to set up local enviroment, so I can run a web page locally on a VM. But I am getting ImportError: No module named 'basic' in Python error, no matter if I'm trying to run as su or not. Django version is 2.0.2 Python is 3.4.3 This is my output
score: -4
has title: ImportError: No module named 'basic' in Python
has answer: http://stackoverflow.com/a/48884009

http://stackoverflow.com/comment/84900236
type: Comment
comment on: http://stackoverflow.com/a/48946225
score: 0
type: AnswerComment
has text: Right now there is no `related_name` in `section` field.

http://stackoverflow.com/comment/84875531
score: 0
type: Comment
type: QuestionComment
has text: While it's possible to "fix" the problem you're encountering, there really isn't a good way to do so with the approach implemented in your existing code (although doing so would be fairly simple as illustrated in my now deleted answer). Instead I _strongly_ suggest you take a look at [this answer](https://stackoverflow.com/a/7557028/355230) because I think doing things the way it does would provide a much better basic architecture for what you appear to want to do in your `tkinter`-based application. Also take a look at this [related answer](https://stackoverflow.com/a/32865334/355230).
comment on: http://stackoverflow.com/q/48893180

http://stackoverflow.com/q/48869903
tagged with: javascript
tagged with: flask
tagged with: ajax
score: 0
has body: I'm working with Twitter API on Python to get the current trending hashtags of a city, then I should pass the results (as an array) to my HTML file where I'm working on visualizing the results using JavaScript. So, I've tried multiple solutions but I thought that flask was yet the easiest. This is my python code (hashtags.py): import tweepy import json from flask import Flask, request, render_template consumerKey = "x" consumerSecret = "x" accessToken = "x" accessTokenSecret = "x" auth = tweepy.OAuthHandler("x", "x") auth.set_access_token("x", "x") api = tweepy.API(auth) app = Flask(__name__) @app.route('/map/') @app.route('/map/<trends>') def trend_hash(id): for location in api.trends_place(id): for trend in location["trends"] : print " - %s" % trend["name"] trends = trend["name"] return render_template("map.html", trends=json.dumps(trends)) trend_hash(1939753) This is my JavaScript code (map.html) I tried to watch my console to see if it will print the trending hashtags, but this is what I got: it just prints the word (trends) without any results. What am I missing? UPDATE I'm quite positive with the code in python, because I tried to print: render_template("map.html", trends=trends) and it prints map.html with the value of trends. my problem now is with my script:
answer count: 1
favorite count: 0
upvote count: 2
type: UnansweredQuestion
downvote count: 2
tagged with: python
linked to: http://stackoverflow.com/q/35555383
duplicate of: http://stackoverflow.com/q/35555383
has answer: http://stackoverflow.com/a/48871000
type: Question
has title: Passing Python results (array) to JavaScript

http://stackoverflow.com/a/48864996
has comment: http://stackoverflow.com/comment/98122853
has comment: http://stackoverflow.com/comment/98122902
has body: Use isin: df = df[df.index.isin(df1.index)] Or get all intersectioned indices and select by loc: df = df.loc[df.index &amp; df1.index] df = df.loc[np.intersect1d(df.index, df1.index)] df = df.loc[df.index.intersection(df1.index)] print (df) A B C D 1 1 4 9 1 3 5 5 1 0 22 1 3 9 6 EDIT: I tried solution: df = df.loc[df1.index]. Do you think that this solution is correct? Solution is incorrect: df = df.loc[df1.index] print (df) A B C D 1 1.0 4.0 9.0 1.0 3 5.0 5.0 1.0 0.0 4 NaN NaN NaN NaN 5 NaN NaN NaN NaN 6 NaN NaN NaN NaN 7 NaN NaN NaN NaN 22 1.0 3.0 9.0 6.0 28 NaN NaN NaN NaN 29 NaN NaN NaN NaN 32 NaN NaN NaN NaN C:/Dropbox/work-joy/so/_t/t.py:23: FutureWarning: Passing list-likes to .loc or [] with any missing label will raise KeyError in the future, you can use .reindex() as an alternative. See the documentation here: http://pandas.pydata.org/pandas-docs/stable/indexing.html#deprecate-loc-reindex-listlike print (df)
has comment: http://stackoverflow.com/comment/84734227
accepted answer of: http://stackoverflow.com/q/48864923
answers question: http://stackoverflow.com/q/48864923
upvote count: 82
has comment: http://stackoverflow.com/comment/122372833
score: 82
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84734091
type: Answer

http://stackoverflow.com/q/48822571
linked to: http://stackoverflow.com/q/51265858
has title: SyntaxError: Generator expression must be parenthezised / python manage.py migrate
answer count: 9
score: 51
has answer: http://stackoverflow.com/a/62914625
type: UnansweredQuestion
upvote count: 51
has comment: http://stackoverflow.com/comment/101899552
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/67937818
has answer: http://stackoverflow.com/a/51382928
has answer: http://stackoverflow.com/a/51952129
has comment: http://stackoverflow.com/comment/90878787
has answer: http://stackoverflow.com/a/51608110
has answer: http://stackoverflow.com/a/55605363
type: Question
has answer: http://stackoverflow.com/a/54010644
has comment: http://stackoverflow.com/comment/84696034
has answer: http://stackoverflow.com/a/48822656
has answer: http://stackoverflow.com/a/54569424
tagged with: syntax-error
has body: I'm really new in programming and I wanted to follow the Djangogirls tutorial, but I'm stucked now. In the tutorial, I am here: To create a database for our blog, let's run the following in the console: python manage.py migrate (we need to be in the djangogirls directory that contains the manage.py file). If that goes well, you should see something like this: ... There is no option to fail in the tutorial but I have an error message: (myvenv) C:\Users\Julcsi\djangogirls&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\Julcsi\djangogirls\myvenv\lib\site-packages\django\core\management\__init__.py", line 364, in execute_from_command_line utility.execute() File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\core\management\__init__.py", line 338, in execute django.setup() File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\apps\registry.py", line 85, in populate app_config = AppConfig.create(entry) File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-packages\django\apps\config.py", line 94, in create module = import_module(entry) File "C:\Users\Julcsi\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 955, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 665, in _load_unlocked File "&lt;frozen importlib._bootstrap_external&gt;", line 723, in exec_module File "&lt;frozen importlib._bootstrap&gt;", line 219, in _call_with_frames_remove File "C:\Users\Julcsi\djangogirls\myvenv\lib\site-pac…
downvote count: 0
has comment: http://stackoverflow.com/comment/119730503
tagged with: migrate
has comment: http://stackoverflow.com/comment/84648806
favorite count: 0

access-violation
tags question: http://stackoverflow.com/q/48892375
type: Tag
tag name: access-violation

http://stackoverflow.com/a/48936917
score: 0
has body: This should give you some idea: ## create dataframe df = pd.DataFrame({'a':[1,0,1,0,0], 'b':False}) ## create flag d['b'] = d.groupby('a').transform(lambda x: (np.random.choice([True, False], len(x), p = [0.65,0.35]))) print(d) a b 0 1 False 1 0 True 2 1 False 3 0 True 4 0 True
answers question: http://stackoverflow.com/q/48936132
type: Answer

http://stackoverflow.com/q/48813300
tagged with: debugging
linked to: http://stackoverflow.com/q/34827263
has comment: http://stackoverflow.com/comment/84630260
has body: I am making a little program in python that is supposed to read the questions from a text file in the format of give question, answers ABCD and should check if the user put in the correct answer. Below is the code I wrote for doing that import time file = open("Questions.txt", "r") def askQuestion(): print(file.readline()) for counter in range(4): print(file.readline()) x = file.readline() userAnswer = input("Please input a letter that corresponds to the correct answer") print("The answer is", userAnswer) print("The X is", x) if userAnswer.upper() == x: print("You got that right") for counter in range(10): time.sleep(1) askQuestion() file.close() and here is a text file with the questions and answers, in advance I just want to say that I am not sure if this is how I should format the text in the file so I am sorry if it isn't the right way to do it on stack overflow. 1) What was the name of the atomic bomb dropped on Hiroshima in 1945? A)Fat Man B)Little Boy C)Annihilator D)Heisenberg B 2)How many stars is there on the American Flag? A)48 B)47 C)50 D)52 C 3)How many countries is there in Europe? A)52 B)38 C)12 D)28 D 4)What is the capital city of Poland? A)Warsaw B)Krakow C)Kijew D)Moscow A 5)What are the colors on the polish flag? A)RED-WHITE B)WHITE-RED C)WHITE-GREEN D)YELLOW-BLUE B 6)What does 2+2*2 evaluate to? A)8 B)10 C)6 D)20 C 7)What year do we have? A)3920 B)120 C)20018 D)2018 D 8)When did WW2 end? A)1945 B)1919 C)1905 D)1834 A 9)When was Python 3 realesed? A)2000 B)2012 C)2010 D)2014 C 10)Who is the president of USA? A)Micheele Obama B)Barack Obama C)George Washington D)Donald Trump D My problem is that let's say for the first question the answer is "B" which is saved in variable x (to make sure x was actually "B" I printed it as seen in the code. Then I printed the user input which also was "B", but for some reason python does not execute the if statement below, even though the condition seems to be True. The condition states that userAnswer (which is whe…
tagged with: if-statement
score: 1
accepted answer: http://stackoverflow.com/a/48813371
answer count: 1
favorite count: 0
tagged with: logic
has comment: http://stackoverflow.com/comment/84630283
has title: Why is "B" not equal to "B"?
tagged with: python
has answer: http://stackoverflow.com/a/48813371
type: AnsweredQuestion
upvote count: 2
downvote count: 1
type: Question

http://stackoverflow.com/comment/84779631
type: QuestionComment
has text: Could you move the app to digital ocean?
score: 0
comment on: http://stackoverflow.com/q/48887289
type: Comment

http://stackoverflow.com/q/48853867
score: 1
has answer: http://stackoverflow.com/a/48853903
favorite count: 0
has title: Aggregate CSV rows by multiple criteria
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has answer: http://stackoverflow.com/a/48854026
has body: suppose I have a CSV file similar to this one, only much bigger: Cost center number,Month,Amount 1,Amount 2 1234,1,755,9356 1234,2,6758,786654 1234,1,-954,31234 1234,2,2345,778 1234,5,680,986 5678,6,876,456 5678,6,1426,321 5678,5,823,164 5678,7,4387,3485 91011,11,1582,714 91011,12,778,963 91011,10,28,852 91011,12,23475,147 I want to sort of mimic Excel pivot table functionality and group the data by cost center, months and sum of both amounts, so the output would look like this: Cost center number,Month,Amount 1 + Amount 2 1234,1,Amount 1 value + Amount 2 value 1234,2,Amount 1 value + Amount 2 value 1234,5,Amount 1 value + Amount 2 value 5678,6,Amount 1 value + Amount 2 value 5678,5,Amount 1 value + Amount 2 value 5678,7,Amount 1 value + Amount 2 value 91011,11,Amount 1 value + Amount 2 value 91011,10,Amount 1 value + Amount 2 value 91011,12,Amount 1 value + Amount 2 value So far I have tried iterating through each row and creating list for the data I am interested in by I don't know where to go from there: import csv filename = 'APAC.csv' with open(filename) as f: reader = csv.reader(f) headers = next(reader) for header in enumerate(headers): print(header) cost_centers = [] months = [] amounts1 = [] amounts2 = [] for row in reader: cost_centers.append(row[1]) months.append(row[2)] amounts1.append(row[3]) amounts2.append(row[4]) I know with Pandas there is the option of 'group by' and 'agg', but this is an exercise for list and dictionaries (however I am open to different approaches) for me and I would prefer to stay within the native Python library.
has answer: http://stackoverflow.com/a/48854295
answer count: 3
upvote count: 1
linked to: http://stackoverflow.com/q/17430553
accepted answer: http://stackoverflow.com/a/48854295
type: AnsweredQuestion
downvote count: 0
possible better answer: http://stackoverflow.com/a/48853903

http://stackoverflow.com/a/48931956
downvote count: 0
has comment: http://stackoverflow.com/comment/84871140
score: 1
has comment: http://stackoverflow.com/comment/84871087
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84908967
accepted answer of: http://stackoverflow.com/q/48931842
has body: First, run the application with sudo (or click Run as Administrator on your Windows machine). It could be a permissions issue. This is most likely caused by the fact that your anaconda-navigator needs updating. This has been logged in anaconda issue 1984 and 6006. Try running the following command which will update your package: conda update anaconda-navigator If that still doesn't work, also call the application with the --reset flag as follows: anaconda-navigator --reset.
answers question: http://stackoverflow.com/q/48931842

http://stackoverflow.com/comment/84893738
comment on: http://stackoverflow.com/q/48942715
type: Comment
type: QuestionComment
has text: [`urllib`](https://docs.python.org/3/library/urllib.html). It's kind of unwieldy, which is why Kenneth Reitz bothered with writing the Requests package instead of using the standard library.
score: 0

http://stackoverflow.com/comment/84738348
has text: I want to remove the value from the initial query too !!
type: Comment
comment on: http://stackoverflow.com/a/48867559
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84621106
has text: line 7, in <module> y = 13*np.cos(t)-5*np.cos(2*t)-2*np.cost(3*t)-np.cos(4*t) AttributeError: module 'numpy' has no attribute 'cost'
comment on: http://stackoverflow.com/q/48808912
score: 0
type: Comment
type: QuestionComment

reference
tags question: http://stackoverflow.com/q/48872113
type: Tag
tags question: http://stackoverflow.com/q/48932115
tag name: reference

http://stackoverflow.com/q/48912313
has comment: http://stackoverflow.com/comment/84831412
tagged with: python-3.x
score: 1
has answer: http://stackoverflow.com/a/48912706
has body: I've noticed that if I have methods with the same name of numpy methods in a class, numpy tends to use the methods defined in the class rather than its own. For example: import numpy as np # using numpy 1.13.1 class PizzaPie: def __init__(self, slice_angles: list, topping: str='Cheese'): try: if sum(slice_angles) &gt; 360: raise Exception('A pizza cannot have more than 360 degrees cut ' 'from it.') if sum(slice_angles) == 360: self._angles = slice_angles else: self._angles = slice_angles + [360 - sum(slice_angles)] except TypeError: # maybe slices are described as complex numbers...? total_pie = 0 for pizza_slice in slice_angles: angle = ( np.arctan(pizza_slice.imag / pizza_slice.real) * (180 / np.pi) ) total_pie += angle if total_pie == 360: self._angles = slice_angles else: # make the left over slice a simple number in degrees. self._angles = slice_angles + [360 - total_pie] self._topping = topping @property def topping(self): return self._topping @topping.setter def topping(self, new): """Only able to add additional toppings. Removing is too messy.""" self._topping = self._topping + ', ' + str(new) @property def slices(self): """Returns the number of slices""" return len(self.angles) def cos(self): """Returns the slice number and the cosine of the slice angle as a tuple""" return [(sl, np.cos(a*(np.pi/180))) for sl, a in enumerate(self._angles) ] def imag(self): """Returns the imaginary portion of the slice angles. Weird huh?""" return [(sl, np.imag(a)) for sl, a in enumerate(self._angles)] mypie = PizzaPie([90, 45, 30, 30, 35]) my_imag_pie = PizzaPie([(20+5j), 90.0, (3+4j)], topping='Dark Matter') print(np.cos(mypie)) print(np.imag(my_imag_pie)) (of course this code is completely fabricated and fictional, but it serves as a simple example of something I'm trying to do. And it's fun to think about Imaginary Pizzas...) But you'll notice that running the above code will return the bound method PizzaPie.imag instead of calling PizzaPie.imag() (in Python 3.5.3) while…
upvote count: 1
has title: Name of the behavior of numpy calling class methods if defined?
type: Question
type: AnsweredQuestion
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48912706
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python

http://stackoverflow.com/comment/84736546
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48865959
score: 0
has text: Your suggestion sounds simple and interesting, but why is it the correct one? To get the actual login dates out of your suggestion one would have to write a simple simulation, which I will try if no better alternatives show up.

http://stackoverflow.com/q/48811375
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84626422
has body: I've got a numpy array, chop_preds, that is very large (~10 million elements) that needs to be modified such that it contains values of 1.0, 0.5, or 0 (see below). How can I parallelize this reassignment? chop_preds=chop_preds.flatten() for k in range(len(chop_preds)): if(chop_preds[k]&gt;=0.4): chop_preds[k]=1.0 elif(chop_preds[k]&lt;0.1): chop_preds[k]=0 else: chop_preds[k]=0.5 my_sum=np.sum(chop_preds)
has title: Parallelize reassignment of elements in large array
tagged with: python-multiprocessing
tagged with: numpy
answer count: 2
has answer: http://stackoverflow.com/a/48811778
downvote count: 0
has answer: http://stackoverflow.com/a/48811850
favorite count: 0
possible better answer: http://stackoverflow.com/a/48811850
tagged with: python
score: 2
accepted answer: http://stackoverflow.com/a/48811778
upvote count: 2
tagged with: multiprocessing
has comment: http://stackoverflow.com/comment/84626568
type: Question
tagged with: parallel-processing

http://stackoverflow.com/comment/84745815
score: 0
comment on: http://stackoverflow.com/q/48870515
type: Comment
type: QuestionComment
has text: Does that work? I don't know if that is the best way...

http://stackoverflow.com/q/48951409
score: 1
has comment: http://stackoverflow.com/comment/84909762
tagged with: machine-learning
has comment: http://stackoverflow.com/comment/84909831
linked to: http://stackoverflow.com/q/44704435
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48951920
has title: ValueError: Error when checking input: expected lstm_1_input to have 3 dimensions, but got array with shape (393613, 50)
type: Question
has comment: http://stackoverflow.com/comment/84910045
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/84909579
tagged with: keras
favorite count: 0
possible better answer: http://stackoverflow.com/a/54142737
has comment: http://stackoverflow.com/comment/84909770
has body: I have a error in Keras and I can't find the solution. I have searched the whole internet and I have still no answer ^^ Here is my Code. model = Sequential() model.add(LSTM(32, return_sequences=True, input_shape=X.values.shape)) model.add(LSTM(32, return_sequences=True)) model.add(LSTM(32)) model.add(Dense(10, activation="softmax")) model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=['accuracy']) The error is the second line. It says "ValueError: Error when checking input: expected lstm_1_input to have 3 dimensions, but got array with shape (393613, 50)" The Shape of my Dataframe X is correct. And when I try to train the model the Error pops up model.fit(X.values, Y.values, batch_size=200, epochs=10, validation_split=0.05) I hope someone could help me :-) [EDIT] Btw. here is the model.summary() Layer (type) Output Shape Param # lstm_1 (LSTM) (None, 393613, 32) 10624 lstm_2 (LSTM) (None, 393613, 32) 8320 lstm_3 (LSTM) (None, 32) 8320 dense_1 (Dense) (None, 10) 330 Total params: 27,594 Trainable params: 27,594 Non-trainable params: 0 Kind regards Niklas.
has answer: http://stackoverflow.com/a/54142737
tagged with: python
has comment: http://stackoverflow.com/comment/84909768
accepted answer: http://stackoverflow.com/a/48951920
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/84692780
score: 0
type: QuestionComment
type: Comment
has text: Sorry, how do i do that?
comment on: http://stackoverflow.com/q/48841927

http://stackoverflow.com/comment/84872306
type: AnswerComment
has text: Is It jozefeg@gmail.com? I have sent mail to you
comment on: http://stackoverflow.com/a/48929967
type: Comment
score: 0

http://stackoverflow.com/q/48868228
type: Question
has answer: http://stackoverflow.com/a/48868498
upvote count: 9
linked to: http://stackoverflow.com/q/9792664
has comment: http://stackoverflow.com/comment/84740683
has comment: http://stackoverflow.com/comment/84740414
has title: is there a magic method for sorted() in Python?
has answer: http://stackoverflow.com/a/72589347
accepted answer: http://stackoverflow.com/a/48868498
possible better answer: http://stackoverflow.com/a/48868515
favorite count: 0
has comment: http://stackoverflow.com/comment/84740856
has comment: http://stackoverflow.com/comment/84739996
has comment: http://stackoverflow.com/comment/84740251
has answer: http://stackoverflow.com/a/48868515
has body: I understand that there are magic methods in python that can be overwritten by classes to control the way certain built in functions treat the members of these classes. For example, the behavior of len() and str() can be overwritten via magic methods __len__() and __str__(): class EmptySet(object): def __len__(self): return 0 def __str__(self): return '[]' &gt;&gt;&gt; e = EmptySet() &gt;&gt;&gt; str(e) [] &gt;&gt;&gt; len(e) 0 There are also __cmp__() and __ge__(), __le__() etc methods to control how these objects can be compared and how a list of them should be ordered by list.sort(). My question is not about customizing the ordering of objects in a list but about sorting the object itself. Suppose the set weren't empty and I want to use sorted() to sort it: class SetOfTwo(object): def __init__(self, a , b): el_0 = a el_1 = b def __len__(self): return 2 def __str__(self): return '[{}, {}]'.format(el_0, el_1) Is there a magic method I can implement to have sorted() flip the elements if they aren't in order? I'm picturing the following behavior: &gt;&gt;&gt; s = SetOfTwo(2, 1) &gt;&gt;&gt; str(s) [2, 1] &gt;&gt;&gt; t = sorted(s) &gt;&gt;&gt; str(t) [1, 2] &gt;&gt;&gt; type(t) &gt;&gt;&gt; SetOfTwo
has comment: http://stackoverflow.com/comment/84740052
tagged with: python
tagged with: magic-methods
has comment: http://stackoverflow.com/comment/84740013
has answer: http://stackoverflow.com/a/48869018
answer count: 4
has comment: http://stackoverflow.com/comment/84740365
score: 8
type: AnsweredQuestion
tagged with: oop
has comment: http://stackoverflow.com/comment/84739917
has comment: http://stackoverflow.com/comment/84740824
downvote count: 1

http://stackoverflow.com/comment/84811651
type: QuestionComment
has text: I compiled it by myself. Can we pass any option during compilation to make it work on all the computers?
score: 0
comment on: http://stackoverflow.com/q/48882088
type: Comment

powercli
tag name: powercli
tags question: http://stackoverflow.com/q/48896382
type: Tag

http://stackoverflow.com/q/48922718
has answer: http://stackoverflow.com/a/48923034
accepted answer: http://stackoverflow.com/a/48923034
tagged with: python
tagged with: image-processing
has body: My problem is the width and height of rectangle are equals and I want to change it to rectangle not square (width and height are different) and this is my code img = cv2.imread(pic) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) coils,reject,level = coil_cascade.detectMultiScale3(gray,1.3,5, outputRejectLevels=True) for (x,y,w,h) in coils: cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) cv2.imshow('img',img) cv2.waitKey(0) cv2.destroyAllWindows()
type: Question
tagged with: opencv
type: AnsweredQuestion
tagged with: haar-classifier
has title: How to change shape of opencv detected scale
has comment: http://stackoverflow.com/comment/84869010
score: 0
has comment: http://stackoverflow.com/comment/84888196
answer count: 1

http://stackoverflow.com/comment/84831383
comment on: http://stackoverflow.com/q/48912403
has text: The number of leading underscores is different: you set `self.__MAX_RABBITS_IN_WARREN`, but the name is `Warren._MAX_RABBITS_IN_WARREN`. Fix that, and stop passing the value as an argument to `Warren.__init__`.
score: 0
type: QuestionComment
type: Comment

windows-subsystem-for-linux
tags question: http://stackoverflow.com/q/48951759
tag name: windows-subsystem-for-linux
type: Tag

http://stackoverflow.com/q/48880221
type: Question
has body: I'm studying the paper "An Introduction to Deep Learning for the Physical Layer". While implementing the proposed network with python keras, I should normalize output of some layer. One way is simple L2 Normalization (||X||^2 = 1), where X is a tensor of former layer output. I can implement simple L2 Normalization by the following code: from keras import backend as K Lambda(lambda x: K.l2_normalize(x,axis=1)) The other way, what I want to know, is ||X||^2 ≤ 1. Is there any way that constrains the value of layer outputs?
score: 2
has title: Layer Normalization with Python Keras
downvote count: 0
tagged with: keras
favorite count: 0
has answer: http://stackoverflow.com/a/48882750
answer count: 1
tagged with: python
accepted answer: http://stackoverflow.com/a/48882750
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/comment/84747214
has text: Why not including? Do you want `range(10)` to produce 10 numbers or 11? `[0,1,2...9]` or `[0,1,2,...,9,10]`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48861789

http://stackoverflow.com/q/48834717
type: Question
has comment: http://stackoverflow.com/comment/84820862
score: 3
has comment: http://stackoverflow.com/comment/84677029
has body: I find myself wanting to perform arithmetic of random variables in Python; for the sake of example, let us consider the experiment of repeatedly tossing two independent fair coins and counting the number of heads. Sampling from each random variable independently is straightforward with scipy.stats, and we can start getting results right away In [5]: scipy.stats.bernoulli(0.5).rvs(10) + scipy.stats.bernoulli(0.5).rvs(10) Out[5]: array([1, 0, 0, 0, 1, 1, 1, 2, 1, 2]) Now, a pessimist would remark that we wouldn't even have to go that far and could instead just do np.random.randint(2, size=10) + np.random.randint(2, size=10), and a cynic would notice that we could just calculate the sum and never have to sample anything. And they'd be right. So, say that we have many more variables and more complex operations to perform on them, and graphical models quickly become useful. That is, we might want to operate on the random variables themselves and only start sampling when our graph of computation is set up. In lea, which does exactly that (albeit only for discrete distributions), the example above becomes In [1]: from lea import Lea In [7]: (Lea.bernoulli(0.5) + Lea.bernoulli(0.5)).random(10) Out[7]: (0, 2, 0, 2, 0, 2, 1, 1, 1, 2) Appears to be working like a charm. Enter PyMC3, one of the more popular libraries for probabilistic programming. Now, PyMC3 is intended for usage with MCMC and Bayesian modeling in particular, but it has the building blocks we need for our experiment above. Alas, In [1]: import pymc3 as pm In [2]: pm.__version__ Out[2]: '3.2' In [3]: with pm.Model() as model: ...: x = pm.Bernoulli('x', 0.5) ...: y = pm.Bernoulli('y', 0.5) ...: z = pm.Deterministic('z', x+y) ...: trace = pm.sample(10) ...: Assigned BinaryGibbsMetropolis to x Assigned BinaryGibbsMetropolis to y 100%|███████████████████████████████████████| 510/510 [00:02&lt;00:00, 254.22it/s] In [4]: trace['z'] Out[4]: array([2, 0, 2, 0, 2, 0, 2, 0, 2, 0], dtype=int64) Not exactly random. Unfortun…
linked to: http://stackoverflow.com/q/46454814
has comment: http://stackoverflow.com/comment/84683882
has comment: http://stackoverflow.com/comment/84715740
has title: Coin tosses, arithmetic of random variables, and PyMC3
tagged with: random
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/62853535
favorite count: 0
has comment: http://stackoverflow.com/comment/84960938
tagged with: python
type: AnsweredQuestion
tagged with: pymc3
upvote count: 3
tagged with: probability
has comment: http://stackoverflow.com/comment/84676839
has comment: http://stackoverflow.com/comment/84691339
accepted answer: http://stackoverflow.com/a/62853535
tagged with: montecarlo
has comment: http://stackoverflow.com/comment/84714675

http://stackoverflow.com/q/48946472
favorite count: 0
has comment: http://stackoverflow.com/comment/84906466
answer count: 0
type: UnansweredQuestion
tagged with: python
has body: Using this code to for capturing image and it is running well on spyder-anaconda but I want to integrate with my app which is made on node.js platform but unable to do so. the beginning of python code is as follows : //cam_open.py import cv2 import numpy as np aarcascade_frontalface_default.xml" detector=cv2.CascadeClassifier('haarcascade_frontalface_default.xml') cam = cv2.VideoCapture(0) #------Id=raw_input('enter your id')---- Id=1 path= 'Dataset1' sampleNum=0 while(True): ret, img = cam.read(); . . . and code for integrating with node.js is as follows: (note: I have used this code to run other python scripts and it is running perfect on them but when I include opencv it is giving me errors even though I have added opencv path to my environment variables too) //index.js var PythonShell = require('python-shell'); var pyshell = new PythonShell('cam_open.py'); pyshell.on('message', function (message) { console.log(message); }); the error I'm getting is as follows: HIBA@hiba-pc MINGW64 ~/documents/sabah/driver-comp/test $ node index.js events.js:137 throw er; // Unhandled 'error' event ^ Error: ImportError: No module named cv2 at PythonShell.parseError (C:\Users\HIBA\documents\sabah\driver-comp\node_modules\p ython-shell\index.js:184:17) at terminateIfNeeded (C:\Users\HIBA\documents\sabah\driver-comp\node_modules\python -shell\index.js:98:28) at ChildProcess.&lt;anonymous&gt; (C:\Users\HIBA\documents\sabah\driver-comp\node_modules \python-shell\index.js:89:9) at ChildProcess.emit (events.js:160:13) at Process.ChildProcess._handle.onexit (internal/child_process.js:209:12) ----- Python Traceback ----- File "cam_open.py", line 1, in &lt;module&gt; import cv2 Can anybody here help me get out of this :)
tagged with: node.js
tagged with: opencv
score: 3
upvote count: 3
type: Question
has title: Cannot run opencv-python script in node.js : No module named cv2
downvote count: 0

http://stackoverflow.com/a/48843378
accepted answer of: http://stackoverflow.com/q/48843069
has comment: http://stackoverflow.com/comment/84691286
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48843069
has comment: http://stackoverflow.com/comment/84691354
upvote count: 3
type: AcceptedAnswer
has body: Use the numpy.random module which provides vectorized sampling together with view casting: &gt;&gt;&gt; n, k = 20, 10 &gt;&gt;&gt; &gt;&gt;&gt; np.random.choice((*fastadict['seq1'],), replace=True, size=(n * k,)).view(f'U{k}') array(['GCAGAATGCT', 'GGAGGTGCAT', 'CACCATCATT', 'CGTGGTGTAC', 'AGAATATCGG', 'GATTTTGGCC', 'GAACATAAGC', 'CGGGCCAAGC', 'GTTGGTGTTT', 'GACCAATAAC', 'ACCCGTAGCC', 'GAATTCCCGG', 'AACAGGTCAC', 'AGACAAGCAC', 'CACACTTGCC', 'CGTTTGTAAT', 'CTAGCCCTCG', 'CTCGACATAT', 'GATGATTAGA', 'TCTATCCTCA'], dtype='&lt;U10') Python 2 version: &gt;&gt;&gt; np.random.choice(tuple(fastadict['seq1']), replace=True, size=(n * k,)).view('S{k}'.format(k=k)) Speed: &gt;&gt;&gt; from time import perf_counter &gt;&gt;&gt; n, k = 100, 1000000 &gt;&gt;&gt; t0 = perf_counter(); x = np.random.choice((*fastadict['seq1'],), replace=True, size=(n * k,)).view(f'U{k}');t1 = perf_counter() &gt;&gt;&gt; t1-t0 1.29188625497045
type: Answer

http://stackoverflow.com/q/48888293
type: Question
has comment: http://stackoverflow.com/comment/84782855
downvote count: 0
has body: I want to resize my images to the following ratios :rescale images in the range x0.5, x0.75, x0.9, x1.1 x1.25, x1.5 basically all i want to give as input is let's say 0.5 and all the images in my folder will have their sizes in half . Note that my images have different sizes and yes i know how to get the height and width of an image and multiply it by an input and yes i have checked this previous question on here How do I resize an image using PIL and maintain its aspect ratio? but is there a better way to do it since then? Edit: Is something like this possible: import os from PIL import Image path = path_to_input_images for filename in os.listdir(path + 'image/'): im = Image.open(path + 'image/' + filename) im.size = list(im.size) im.size[0] = int(float(im.size[0]) * 0.5) im.size[1] = int(float(im.size[1]) * 0.5) im.size = tuple(im.size) im.save(path + 'resized_images'+ filename) but i got an error that ValueError: tile cannot extend outside image
upvote count: 3
answer count: 1
has comment: http://stackoverflow.com/comment/84782389
has title: ValueError: tile cannot extend outside image
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/273946
has answer: http://stackoverflow.com/a/48889238
accepted answer: http://stackoverflow.com/a/48889238
tagged with: python
type: AnsweredQuestion
score: 3
tagged with: python-imaging-library
linked to: http://stackoverflow.com/q/29367990
tagged with: image

http://stackoverflow.com/comment/84775011
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48885216
has text: wouldn't ['Band_1'][0] be just the thing you want? A bit confusing, what is the desired result?

http://stackoverflow.com/a/48895203
accepted answer of: http://stackoverflow.com/q/48895054
answers question: http://stackoverflow.com/q/48895054
has comment: http://stackoverflow.com/comment/103882555
type: AcceptedAnswer
downvote count: 0
has body: In your settings.py set SESSION_COOKIE_AGE SESSION_COOKIE_AGE = 15 * 60 # 15 Minutes Know more in the doc https://docs.djangoproject.com/en/2.0/ref/settings/#std:setting-SESSION_COOKIE_AGE
has comment: http://stackoverflow.com/comment/84801891
type: Answer
has comment: http://stackoverflow.com/comment/99953205
score: 2
upvote count: 2

http://stackoverflow.com/a/48839870
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48839767
has body: Based on @RoadRunner answer: You want a moving minimum of 3 consecutive numbers... a = [44.1, 78.2, 74.2, 85.4, 107.6, 167.7, 221.6, 245.2, 299.2, 314.5] a.reverse() [min(a[i:i+3]) for i in range(0, len(a) - 2)] With the -2 you ensure that you always have 3 numbers.
upvote count: 1
type: Answer

http://stackoverflow.com/comment/84685502
type: QuestionComment
comment on: http://stackoverflow.com/q/48831544
type: Comment
has text: Also try installing `kivy.deps.glew` in your PyCharm environment.
score: 0

http://stackoverflow.com/comment/84921251
score: 0
has text: When you add the three patterns in your example, you get a new pattern `'([0-9]+)one(?P<r1>[-/])two(?P=r1)threeone(?P<r1>[-/])two(?P=r1)three'` which is likely not what you want. Adding the patterns simply concatenates them as strings. Perhaps you want to join them with '|'?
comment on: http://stackoverflow.com/q/48957035
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84658636
has text: For dynamic validation you need to use ajax. In case you are validating the form after submitting it, then your form action is pointing to a wrong route, which needs to be changed to `/` from `/send`.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48817898

http://stackoverflow.com/q/48871840
has answer: http://stackoverflow.com/a/78012036
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48872005
type: UnansweredQuestion
tagged with: python
tagged with: pygame
score: 2
upvote count: 2
has title: How can you center the mouse pointer to make it a crosshair?
type: Question
has answer: http://stackoverflow.com/a/65594672
answer count: 3
has body: I made a custom cursor on GIMP for a game and I want the mouse to be centered on the cursor. So the tip of the normal arrow pointer is in the center of the crosshair. Any ideas? I have already hidden the other cursor and displayed the new one, I just want to make it centered.
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/84634084
has text: @MartjinPeiters there this `if letter_list.remove(x)` in the list comprehension which always returns `None`. the proper list comp would be `letter_list = "".join([x for x in lettersGuessed if x not in letter_list])`.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48815046
score: 0

http://stackoverflow.com/comment/85164787
score: 0
has text: unfortunately no, I spent a couple of days playing around with all options and also read the docs on doc.qt.io until I was pulling out my hair. So for now I'll just place the widgets manually....
comment on: http://stackoverflow.com/a/48860962
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48887189
score: 2
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48884480
answers question: http://stackoverflow.com/q/48884480
upvote count: 2
type: AcceptedAnswer
has body: Here's your modified code (code.py): #!/usr/bin/env python3 import sys from dateutil import parser from datetime import datetime, timedelta today = datetime(2018, 2, 20) data = [ ("Tuesday", today, today), ("Thursday", datetime(2018, 2, 15), today), ("Jan 31", datetime(2018, 1, 31), today), ("December 10", datetime(2017, 12, 10), today), ] def parse(date_str, default=None): # this needs to be modified return parser.parse(date_str, default=default) def _days_in_year(year): try: datetime(year, 2, 29) except ValueError: return 365 return 366 def parse2(date_str, default=None): dt = parser.parse(date_str, default=default) if default is not None: weekday_strs = [day_str.lower() for day_tuple in parser.parserinfo.WEEKDAYS for day_str in day_tuple] if date_str.lower() in weekday_strs: if dt.weekday() &gt; default.weekday(): dt -= timedelta(days=7) else: if (dt.month &gt; today.month) or ((dt.month == today.month) and (dt.day &gt; today.day)): dt -= timedelta(days=_days_in_year(dt.year)) return dt def print_stats(parse_func): print("\nPrinting stats for \"{:s}\"".format(parse_func.__name__)) for triple in data: d = parse_func(triple[0], default=triple[2]) print(" [{:s}] [{:s}] [{:s}] [{:s}]".format(triple[0], str(d), str(triple[1]), "True" if d == triple[1] else "False")) if __name__ == "__main__": print("Python {:s} on {:s}\n".format(sys.version, sys.platform)) print_stats(parse) print_stats(parse2) Notes: I changed the structure of the code "a bit", to parametrize it, so if a change is needed (e.g. a new example to be added) the changes should be minimal Instead of asserts, I added a function (print_stats) that prints the results (instead raising AssertError and exiting the program if things don't match) Takes an argument (parse_func) which is a function that does the parsing (e.g. parse) Uses some globally declared data (data) together with the (above) function data - is a list of triples, where each triple contains: Text to be converted Expected datetime ([Python 3.Docs…
type: Answer

http://stackoverflow.com/a/48926329
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/139291084
score: 1
accepted answer of: http://stackoverflow.com/q/48926119
has body: First of all, this line: -bash: $: command not found tells that you've executed the "$" which is not right. Your command to set permissions should look like this: chmod +x hello.py Another comment is that the shebang line should be without space: #!/usr/bin/env python3
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48926119
has comment: http://stackoverflow.com/comment/139290461
has comment: http://stackoverflow.com/comment/139285715

http://stackoverflow.com/comment/84872432
has text: Added actual data
comment on: http://stackoverflow.com/q/48932345
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84781440
score: 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48888195
has text: Python code without indentation is not a [mcve].
type: Comment

http://stackoverflow.com/comment/84628744
type: QuestionComment
has text: the indentation in the .kv is important, and according to what I see this is not appropriate, you could correct it.
score: 0
comment on: http://stackoverflow.com/q/48812442
type: Comment

http://stackoverflow.com/a/48851541
accepted answer of: http://stackoverflow.com/q/48851337
answers question: http://stackoverflow.com/q/48851337
downvote count: 0
has body: I think that using datetime will be more pythonic, from datetime import datetime date_list = '20180101,20180102,20180103,20180104,20180105,20180106,20180107,20180108' def new_date_format(old_format_str): date_format = datetime.strptime(old_format_str, '%Y%m%d') new_format = date_format.strftime("%Y-%m-%d") return new_format for date_str in date_list.split(","): print(new_date_format(date_str)) This will produce the following output: 2018-01-01 2018-01-02 2018-01-03 2018-01-04 2018-01-05 2018-01-06 2018-01-07 2018-01-08
score: 4
type: AcceptedAnswer
type: Answer
upvote count: 4

http://stackoverflow.com/q/48844520
favorite count: 0
tagged with: spam
tagged with: classification
tagged with: python
has comment: http://stackoverflow.com/comment/84693955
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48847410
has title: Stemming words in email addresses without putting them into arrays
downvote count: 1
type: Question
has body: I was trying to re-implement the spam classifier in the Stanford ML course by Andrew Ng and i used 'PorterStemmer()' but the emails after stemming is in a list form ps = PorterStemmer() for i in range(len(just_emails)): words = word_tokenize(just_emails[i]) just_emails[i] = [ps.stem(w) for w in words] print(just_emails.split() but what i need to do is stem the words in the email and keep the emails in their original form Actual Output: [go, until, jurong, point, crazi, avail, onli,...] Desired Output : go until jurong point crazi avail onli
score: -1
has comment: http://stackoverflow.com/comment/84693847
has answer: http://stackoverflow.com/a/48847410
upvote count: 0
answer count: 1

http://stackoverflow.com/a/48826875
accepted answer of: http://stackoverflow.com/q/48826813
has comment: http://stackoverflow.com/comment/84657320
downvote count: 0
answers question: http://stackoverflow.com/q/48826813
score: 5
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84657375
has body: That's not how you capture exceptions. try: float(some value) except ValueError as e: print("here's the message", e.args) except OSError as e: print("here's a different message") (Note, though, there's no instance when calling float would raise an OSError.)
upvote count: 5
type: Answer

http://stackoverflow.com/comment/85025890
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48916970
has text: There's no type `object` in Cerberus and it would hardkly make sense. Is Oleg aware you're using his user account?

http://stackoverflow.com/a/48845352
upvote count: 3
answers question: http://stackoverflow.com/q/48845333
score: 3
has comment: http://stackoverflow.com/comment/102848939
type: AcceptedAnswer
downvote count: 0
has body: It seems you need if date2 is same for each group: df.groupby(['date1', 'date2'],as_index=False).agg({'numbers':'sum'}) Or need aggregate by first: df.groupby(['date1'],as_index=False).agg({'numbers':'sum','date2':'first'}) But if need mean of datetime it is a bit complicated: df['date2'] = pd.to_datetime(df['date2']) f = lambda x: pd.to_datetime(x.values.astype(np.int64).mean()) df1 = df.groupby(['date1'],as_index=False).agg({'numbers':'sum','date2':f}) print (df1) date1 numbers date2 0 2018-01-01 159 2018-12-31 1 2018-01-02 104 2018-12-31 2 2018-01-03 75 2018-12-31 3 2018-01-04 98 2018-12-31 4 2018-01-05 184 2018-12-31
type: Answer
accepted answer of: http://stackoverflow.com/q/48845333

http://stackoverflow.com/q/48863227
answer count: 1
has body: As was suggested, I started to use .after method to create bouncing ball GUI, and again an into a problem. from tkinter import* from tkinter import ttk import random class Widg: def __init__(self, master): master.geometry('600x500+200+150') canvas = Canvas(master) canvas.pack(fill=BOTH, expand=True) oval = canvas.create_oval(1, 1, 11, 11, fill='green') def call_func(self): for i in range(3): rand_x = random.randint(1, 50) rand_y = random.randint(1, 50) canvas.move(oval, rand_x, rand_y) canvas.after(500) print('x= ', rand_x) print('y= ', rand_y) canvas.bind('&lt;ButtonPress-1&gt;', call_func) def main(): root = Tk() a = Widg(root) root.mainloop() if __name__ == '__main__': main() And again, when I start it, it runs behind the widget and simply shows the final result. (No animation) upd.: upd2.: @ tobias_k duly noted! Won't happen again! Thanks for your answers!
tagged with: tkinter-canvas
has comment: http://stackoverflow.com/comment/84730900
favorite count: 0
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84779128
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84732793
tagged with: python
has comment: http://stackoverflow.com/comment/84730126
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84733115
type: Question
has answer: http://stackoverflow.com/a/48864236
has title: using after method with tkinter
upvote count: 1

http://stackoverflow.com/comment/84709885
has text: How about this `[list(np.unique(z)).index(val) for val in z]`
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48853037

http://stackoverflow.com/comment/84647333
type: Comment
has text: ...and how's this Pythonic?
comment on: http://stackoverflow.com/a/48822012
score: 1
type: AnswerComment

http://stackoverflow.com/comment/84788944
comment on: http://stackoverflow.com/a/48890910
score: 0
type: AnswerComment
type: Comment
has text: I don't think that's the way when we are using any 3rd module, for example if we want print `timestamp`, just need import `datetime`, don't have to know the path, and we don't have a path also. I tried `from submodule1 import hello`, the error is "ModuleNotFoundError: No module named '__main__.submodule1'; '__main__' is not a package".

http://stackoverflow.com/comment/84910178
comment on: http://stackoverflow.com/a/48951776
type: AnswerComment
has text: _I don't see anything wrong with your way of doing it_ Nothing wrong except that he said it doesn't work...
score: 0
type: Comment

http://stackoverflow.com/q/48835094
has answer: http://stackoverflow.com/a/48835792
has title: Getting python to write to a file once per hour for 24 hours before creating a new file
has comment: http://stackoverflow.com/comment/84675022
score: 0
has body: Here's the issue I'm having...I can get python to write a file once per hour for 24 hours, no problem. I can get python to write to a new file, again, no problem. But getting python to write to a file for 24 hours and then creating a new file to continue writing to is giving me problems. The code I'm using to write for 24 is as follows (may be slightly ham-fisted); import time i = 1 while (i &lt;= 24): time_stamp = time.strftime("%c") with open('/home/pi/comp.txt') as file_two: contents = file_two.read() with open("/home/pi/comp2.txt", "a", encoding='utf-8') as file_three: file_three.writelines(time_stamp + "\n") file_three.writelines(contents + "\n" + "\n") i += 1 time.sleep(3600) And the code I'm using to get it to write a new file is; while (i &lt;= 24): file_names = "data_" + str(i) + ".txt" with open('/home/pi/comp.txt', 'r') as file_one: contents = file_one.readlines() with open(file_names, 'w', encoding='utf-8') as file_four: file_four.writelines(contents) i += 1 As I said, I haven't been able to get them to play nicely with each other. I've tried using a for loop for the second code to get it to use each name individually (e.g. "data_1.txt" for 24 hours, then "data_2.txt" for the next 24), but when I tried that, I got an IsADirectoryError from the compiler. I appreciate any help!
answer count: 1
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84675382
has comment: http://stackoverflow.com/comment/84674982
tagged with: python
type: Question

http://stackoverflow.com/q/48873638
tagged with: discord
favorite count: 0
accepted answer: http://stackoverflow.com/a/48873822
tagged with: python
has comment: http://stackoverflow.com/comment/84751191
type: AnsweredQuestion
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84751291
type: Question
has body: Okay, so I know the command to do this but my issue is I do not know what arguments to pass to the parameters. I want my code to take a user's message content and then move the user to a voice channel named "afk". Here is a snippet of my code: All I want to do is move a user that types the words !move in any case to be moved to another voice channel. I am sorry if my code is bad but I just need this down. I know you might need to see my definitions but all it is: def on_message(message): if '!MOVE' in message.content.upper(): author = message.author voice_channel = id('afk') await client.move_member(author, voice_channel)
tagged with: discord.py
has comment: http://stackoverflow.com/comment/84751247
has answer: http://stackoverflow.com/a/48873822
has title: How do I move a user to a specific channel on discord using the discord.py API
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48808912
favorite count: 0
has comment: http://stackoverflow.com/comment/84621107
has answer: http://stackoverflow.com/a/48809559
has comment: http://stackoverflow.com/comment/84621664
has comment: http://stackoverflow.com/comment/84621137
answer count: 1
has comment: http://stackoverflow.com/comment/84620963
has comment: http://stackoverflow.com/comment/84620934
has comment: http://stackoverflow.com/comment/84621431
has comment: http://stackoverflow.com/comment/84622077
has comment: http://stackoverflow.com/comment/84621965
linked to: http://stackoverflow.com/q/5963269
has title: AttributeError: module 'numpy' has no attribute 'cost'
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84621797
downvote count: 3
has comment: http://stackoverflow.com/comment/84621106
has body: I don't know much about coding and am trying to open a .py my boyfriend wrote for me. I finally got matploglib/seaborn/numpy to install but now I am getting this error and don't know what it means/how to remedy it: AttributeError: module 'numpy' has no attribute 'cost' numpy is updated with the latest version. I tried to look for the answer before posting this but couldn't find it. If anyone could help, that'd be sick. import matplotlib.pyplot as plt import numpy as np import seaborn as sns t = np.arange(0,2*np.pi,0.1) x = 16 * np.sin(t)**3 y = 13*np.cos(t)-5*np.cos(2*t)-2*np.cost(3*t)-np.cos(4*t) plt.plot(x,y) sns.set_style("dark") sns.despine() plt.show()
type: Question
tagged with: numpy
accepted answer: http://stackoverflow.com/a/48809559
has comment: http://stackoverflow.com/comment/84621923
has comment: http://stackoverflow.com/comment/84621409
score: -2
has comment: http://stackoverflow.com/comment/84622316

http://stackoverflow.com/q/48902411
accepted answer: http://stackoverflow.com/a/48903232
has body: I'm trying to plot a data frame using colors stored in a dictionary. This code works: import matplotlib.pyplot as plt import pandas as pd df = pd.DataFrame(np.random.randn(100, 4), index=range(100), columns=list('ABCD')) df = df + [-2, 0, 2, 4] x = list(range(100, 1100, 10)) clrhex = {'abcd':'#FFA500', 'efgh':'#FF0000','ijkl':'#000000','mnop':'#6495ED'} plt.plot(x, df, color=[clrhex['abcd'], clrhex['efgh'], clrhex['ijkl'], clrhex['mnop']]) plt.show() but I'd like to make this shorter by indexing the dictionary with a list. This: plt.plot(x, df, color=clrhex['abcd', 'efgh', 'ijkl', 'mnop']) gives the following error message: Invalid RGBA argument How can I get multiple values from a dictionary ?
type: Question
possible better answer: http://stackoverflow.com/a/48902507
answer count: 2
upvote count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48902507
has title: Indexing a dictionary by passing a list
tagged with: color-scheme
type: AnsweredQuestion
score: 1
tagged with: matplotlib
linked to: http://stackoverflow.com/q/18619422
has answer: http://stackoverflow.com/a/48903232

http://stackoverflow.com/comment/84880394
comment on: http://stackoverflow.com/a/48933432
has text: I did, it probably doesn't show though bc it says I have a reputation of less than 15 <.<
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84636810
type: Comment
has text: When you say "**it** gives, say 3 instead of 3/1", what precisely is **it**? What function do you invoke? Please reduce your program to the shortested **complete** program that demonstrates the problem. Copy-paste that short program (3-5 lines, I should think) into your question. Include the expected and actual output. See [mcve] for more information.
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48816327

http://stackoverflow.com/comment/84698621
type: QuestionComment
comment on: http://stackoverflow.com/q/48847210
score: 0
has text: Is this homework?
type: Comment

http://stackoverflow.com/comment/84814038
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48904160
has text: yes ,__table__ = db.Model.metadata.tables['condition'] using this

http://stackoverflow.com/a/48870187
answers question: http://stackoverflow.com/q/48864357
score: 1
has body: NCL's ncl_convert2nc function is my go-to for this type of problem: https://www.ncl.ucar.edu/Document/Tools/ncl_convert2nc.shtml
upvote count: 2
downvote count: 1
has comment: http://stackoverflow.com/comment/119842354
type: Answer

http://stackoverflow.com/a/48840500
accepted answer of: http://stackoverflow.com/q/48840448
type: Answer
upvote count: 1
has body: The SQL you're using looks like MySQL, not Access SQL. In Access SQL, you delimit a field name by using square brackets [] and you don't add apostrophes for numbers, like an integer: "SELECT [Law_ID] FROM Laws WHERE [Fine]=1" You do need the apostrophes if the Fine column actually contains a string.
score: 1
answers question: http://stackoverflow.com/q/48840448
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48817792
has comment: http://stackoverflow.com/comment/84639778
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84657298
has comment: http://stackoverflow.com/comment/84640731
tagged with: python
has answer: http://stackoverflow.com/a/48818492
type: Question
tagged with: function
has body: First important note, I'm using tkinter. Each 'child' class has some unique widgets and functions, but every child class inherits the widgets and functions from the parent class (stuff like the background colour is defined here, because it's the same on every screen). When the user clicks certain buttons, the current class' screen is destroyed, and the next class is called. With that said, if I have a parent class like this: class parent: def __init__(self): def back(): if (someCondition == True): #some algorithm to go back, by deleting the current screen and popping the previous screen off a stack. else: change() #Algorithm to create main window self.back = Button(command=back) And a child class like this class child(parent): def __init__(self): parent.__init__(self) def change() #algorithm to change the contents of the screen, because in this unique case, I don't want to destroy the screen and call another one, I just want the contents of this screen to change. #Some algorithm to put unique widgets and such on this screen How could I call the change() function from within the back() function? I tried 'child.change', but this returned an error message stating there was no attribute of 'child' called 'change'.
tagged with: class
score: 0
has comment: http://stackoverflow.com/comment/84639681
has comment: http://stackoverflow.com/comment/84639624
has title: Call a class function in __init__ from another class?
has comment: http://stackoverflow.com/comment/84639707
answer count: 1
has comment: http://stackoverflow.com/comment/84658039
has comment: http://stackoverflow.com/comment/84639905
has comment: http://stackoverflow.com/comment/84639654
tagged with: tkinter

http://stackoverflow.com/a/48896809
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48896633
has body: For this kind of storage you would use a dictionary for the greeting categories, like this: testcategory = 'chicken' greeting = {} greeting['greetingInput'] = ['hi','HI','Hi','Hello','wazzup','hello','sup','Sup','howdy','Howdy','hey','Hey','What\'s hanging my dude?',] greeting['greetingOutput'] = ['Hello, how are you?','How\'s it going?','Wazzup','What\'s hanging my dude?',] greeting['greetingResponseP'] = ['good','great','ok','fine','okay','amazing','splendid','Good','Great','Ok','Fine','Okay','OK','Amazing','Splendid','allright','Allright',] greeting['greetingResponseB'] = ['bad','sucky','lame','not good','horrible','cruddy','bloody horrible','terrible','Bad','Sucky','Lame','Not good','Horrible','Cruddy','Bloody horrible','Not Good','Bloody Horrible','Terrible'] greeting['statusInputandResponseP'] = ['Good, how are you?','I\'m great, how are you?','i\'m good, how are you?','Good how are you?','I\'m great how are you?','i\'m good how are you?','Im great, how are you?','im good, how are you','Good, how are you','I\'m great, how are you','i\'m good, how are you','Im great, how are you','im good, how are you','Good, hbu?','I\'m great, hbu?','i\'m good, hbu?','Good hbu?','I\'m great hbu?','i\'m good hbu?','Im great, hbu?','im good, hbu','Good, hbu','I\'m great, hbu','i\'m good, hbu','Im great, hbu','im good, hbu','Good how are you?','I\'m great how are you?','i\'m good how are you?','Im great how are you?','im good how are you','Good how are you','I\'m great how are you','i\'m good how are you','Im great how are you','im good how are you','Good hbu?','I\'m great hbu?','i\'m good hbu?','Im great hbu?','im good hbu','Good hbu','I\'m great hbu','i\'m good hbu','Im great hbu','im good hbu',] greeting['statusInput'] = ['how are you','How are you','how about you','How about you','hbu','HBU','how are you?','How are you?','how about you?','How about you?','hbu?','HBU?','How\'s it going?','how\'s it going?','how\'s it going','How\'s it going','Hows it going?','Hows it going','H…
type: Answer
answers question: http://stackoverflow.com/q/48896633
score: 1
upvote count: 1

http://stackoverflow.com/comment/85333998
type: QuestionComment
comment on: http://stackoverflow.com/q/48810935
has text: I wanted to know if any built-in code is there in networkx to find the node strength and its distribution just like degree
score: 0
type: Comment

http://stackoverflow.com/q/48887491
has comment: http://stackoverflow.com/comment/84783137
has comment: http://stackoverflow.com/comment/84783772
tagged with: mongodb
has body: I need help with designing my Mongo database (I'm new with MongoDB). This is my current status This keys and vals are for ONE feature, and I want Features_Collection to contain a lot of features (For simplicity - 1000). First solution Creating 1000 Collections. Every collection will have it's name Feature1_Collection, Feature2_Collection, etc..., And the values will be like in the screen shot - Xs and Ys, and I could search for Xs in O(Log(N)). Is this solution good? Is it normal to work with 1000 Collections? Second solution I've tried creating key of feature name, and insert inside an array of dicts of the keys and values (Array: [{"x": 0.659, "y":".."},{"x":0.6611613,"y":..} ) But I think that in this way I won't enjoy the advantages of searching in O(1) which is imported for me in this project. Edit: For clarity: O(Log(N)) - Complexity of searching. Xs: x values: [0.659, 0.6611613...] Ys: y values: [... , ...]
answer count: 0
downvote count: 0
score: 1
favorite count: 0
type: Question
tagged with: python
tagged with: mongodb-query
has title: MongoDB - How to design my collections? Do I need nested collections?
has comment: http://stackoverflow.com/comment/84783051
upvote count: 1
has comment: http://stackoverflow.com/comment/84781858
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84781794

http://stackoverflow.com/comment/84620716
comment on: http://stackoverflow.com/a/48808506
type: AnswerComment
score: 0
type: Comment
has text: Ok. Could you post the topic generator method as well? Everything in those methods seems legitimate

http://stackoverflow.com/q/48913396
has answer: http://stackoverflow.com/a/48913490
score: 5
possible better answer: http://stackoverflow.com/a/48913531
answer count: 3
tagged with: pandas
favorite count: 0
upvote count: 5
has body: I'm trying to create a new column based on a conditional subtraction. I want to first group the dataframe from column A, then take the row value of C where B is minimum, and subtract that value from all values in column C. import pandas as pd data = [ ["R", 1, 2], ["R", 2, 4], ["R", 3, 6], ["R", 4, 8], ["S", 0, 5], ["S", 1, 4], ["S", 2, 1], ["S", 3, 3]] df = pd.DataFrame(data=data, columns=["a", "b", "c"]) df Out[1]: a b c 0 R 1 2 1 R 2 4 2 R 3 6 3 R 4 8 4 S 0 5 5 S 1 4 6 S 2 1 7 S 3 3 Want it to yield the column 'd' of: Out[2]: a b c d 0 R 1 2 0 1 R 2 4 2 2 R 3 6 4 3 R 4 8 6 4 S 0 5 0 5 S 1 4 -1 6 S 2 1 -4 7 S 3 3 -2 Anyone have any nice pythonic ways of doing this? Thanks
has answer: http://stackoverflow.com/a/48913581
tagged with: python
has title: Pandas groupby conditional subtraction
has answer: http://stackoverflow.com/a/48913531
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48913490
downvote count: 0
type: Question

http://stackoverflow.com/q/48897860
favorite count: 0
tagged with: vtk
has body: Funny question, and I am really new to this (please dont assume i know anything lol) But I have taken a set of points and converted to a polyline (polydata) and then extruded this polydata using vtkLinearExtrusionFilter into a surface. Now I would like to extrude that surface into a 3d solid, how can I extrude the 1st extrusion? How to properly save 1st extrusion as vtkDataObject (see error below) TypeError: SetInputData argument 1: method requires a vtkDataObject, a vtkLinearExtrusionFilter was provided.
tagged with: python
accepted answer: http://stackoverflow.com/a/48984551
type: AnsweredQuestion
tagged with: paraview
downvote count: 1
type: Question
tagged with: modeling
score: -1
has answer: http://stackoverflow.com/a/48984551
has title: How to extrude an extrusion using VTK python ..how to convert the first extrusion to something useable in vtkLinearExtrusionFilter()?
upvote count: 0
answer count: 1

http://stackoverflow.com/q/48956583
has comment: http://stackoverflow.com/comment/84928664
has comment: http://stackoverflow.com/comment/84920869
upvote count: 1
favorite count: 0
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/27571305
tagged with: python
has title: subprocess.Popen bufsize=1 being ignored
has comment: http://stackoverflow.com/comment/84920545
tagged with: subprocess
downvote count: 0
tagged with: popen
score: 1
has body: I'm having a similar problem described here: subprocess stdin buffer not flushing on newline with bufsize=1 My script is not outputting line by line when I specify bufsize=1. It's infact outputting when the buffer fills. I want to read line by line in realtime. I've tried the below on Linux Mint and CentOS 7. test.py is what I run, it calls the 'script' file which is executable. test.py #!/usr/bin/python import subprocess import sys process = subprocess.Popen('/root/script',bufsize=1, stdout=subprocess.PIPE, stderr=subprocess.PIPE,close_fds=True, universal_newlines=True) for line in iter(process.stdout.readline, b''): print line script #!/usr/bin/python import time for i in range(0,999999): print str('This is a short line, ' + str(i) + '\n') time.sleep(0.01) This outputs large numbers of lines at once with pauses between the output. The first large chunk ends at line 154 However, If I make the output line much larger in the script file: print str('This is a long line................................................................................................. ' + str(i) + '\n') The first large chunk ends at line 66 Why is my buffer size being ignored?
type: Question
has comment: http://stackoverflow.com/comment/84968878

http://stackoverflow.com/a/48834608
type: Answer
has comment: http://stackoverflow.com/comment/84674246
has body: From what I can see in what you posted, you are attempting to use the python script in Python/Test_Run/Game_tic_tac_toe.py to load the module located at Python/functions. You do not have your project directory in your sys.path, so your import, from functions.Tic_Tac_Toe import *, cannot find the functions module. You would either want to use a relative import for your module or fix your python path. It looks like you have attempted to alter your python path in your Game_tic_tac_toe.py script. The problem as I see it is that you used what appears to be a Windows path to specify a directory on MacOSX. If you are using Windows, make sure you have the correct path. If you are using MacOSX, remove the c: from your path and see if that works.
score: 0
answers question: http://stackoverflow.com/q/48834216

http://stackoverflow.com/comment/85151986
type: AnswerComment
type: Comment
has text: This is already a part of my original question. It does not help me because the first line itself throws an exception with no details but a message of parameter not found.
comment on: http://stackoverflow.com/a/48956246
score: 0

http://stackoverflow.com/a/48850658
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48850130
downvote count: 0
has body: The problem I feel is that you need to understand that you are trying to print in the second loop. If you print in the first iteration, you can see the following result. import requests res = requests.get("https://bitbns.com/order/getTickerAll") for items in res.json(): print(items) {'BTC': {'sellPrice': 703500, 'buyPrice': 702000, 'lastTradePrice': 702000}} {'XRP': {'sellPrice': 72.89, 'buyPrice': 72.7, 'lastTradePrice': 72.9}} {'NEO': {'sellPrice': 8480, 'buyPrice': 8400, 'lastTradePrice': 8400}} {'GAS': {'sellPrice': 3000, 'buyPrice': 2990, 'lastTradePrice': 2990}} {'ETH': {'sellPrice': 61499, 'buyPrice': 60800, 'lastTradePrice': 60800}} {'XLM': {'sellPrice': 29.6, 'buyPrice': 29.53, 'lastTradePrice': 29.53}} Now you need to iterate through the second object, so you can use the following code. import requests res = requests.get("https://bitbns.com/order/getTickerAll") for item in res.json(): for key,value in item.items(): print(key, value) for subkey,subvalue in value.items(): print(subkey,subvalue) The second and third for loops are coming because of Python's assumption that dictionary by definition has arbitrary number of keys. You can continue to drill down as much as you want or follow the previous answer where you have got the exact result as you want.
type: Answer
has comment: http://stackoverflow.com/comment/84704832

http://stackoverflow.com/comment/84915738
type: AnswerComment
score: 0
has text: If you're trying to plot `group['MATCH']` against something, you need to specify what you want to plot it against. For instance, in the example, they plotted `['X']` against `['S']`
type: Comment
comment on: http://stackoverflow.com/a/48953541

http://stackoverflow.com/a/48831072
type: Answer
accepted answer of: http://stackoverflow.com/q/48830854
has body: Simply use: list(Event.objects.all().order_by('-id')[:5]) + list(Event.objects.filter(is_home=True)) Unfortunately, you cannot (as far as I can tell) combine queries after taking a slice, so conversion to lists is necessary. If you really really want to have a QuerySet you can do: Event.objects.filter(Q(id__in=Event.objects.all().order_by('-id')[:5].values_list('id', flat=True)) | Q(is_home=True)) Which is extremely ugly.
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48830854
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/62328157
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48865970
has body: Whenever getting these kind of messages, if you see all files and handlers have the right name, format, location, etc., check also if other parts of the Lambda configuration are set up properly for what the code is trying to do. For example, you might receive that unrelated error if your code is trying to execute against an RDS database that is in a private subnet and you are missing the correct VPC configuration that allows connectivity to that database.

http://stackoverflow.com/q/48866886
tagged with: pandas
has answer: http://stackoverflow.com/a/48867908
tagged with: python
has title: Joining tables in python with different lengths based on a key field
favorite count: 0
tagged with: inner-join
downvote count: 1
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48867908
tagged with: join
score: -1
has body: So I want to make a join on two tables with a key field which both tables contain, so I can make a side by side comparison. Table A has 1164 rows and table B has 74 rows. And the common field in Table A is called EmployeeID and the 'same' field in Table B is called UserID. Table A Table B I want to have the output in 3 forms: Table 1 with the records where the key field values were only found in TableA. (UNMATCHED LEFT) Table 2 with the matching records (so the key field value was found in Table A and B. (INNER JOIN) Table 3 with the records that were only in Table B. (UNMATCHED RIGHT) What is the best way to tackle this problem? When I used this code: data_left_join = pd.merge(table_a, table_b, how='left') I got 48268 rows as result. All the articles I could find were in SQL or R. I managed to import the tables and make some modifications to the tables. But I got stuck here. Thank in advance.
type: Question
upvote count: 0
answer count: 1

http://stackoverflow.com/comment/84896731
comment on: http://stackoverflow.com/a/48944563
type: AnswerComment
has text: It throws **Exception** then. `IntegrityError` `NOT NULL constraint failed: news_event.date`. I guess it doesn't accept data I provide do `DateField`. I'm using `timezone.now` now, and still not working.
score: 0
type: Comment

http://stackoverflow.com/comment/84906919
has text: @Link so you do want the loop, but only print when the value has changed?
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48950178

http://stackoverflow.com/a/48912026
downvote count: 0
has comment: http://stackoverflow.com/comment/84831811
has comment: http://stackoverflow.com/comment/84858963
has comment: http://stackoverflow.com/comment/84835046
upvote count: 2
has comment: http://stackoverflow.com/comment/84858832
type: AcceptedAnswer
has body: Units (compilation units, components) are a relatively new feature, as opposed to modules, that have been in Transcrypt from the start. You need Transcrypt 3.6.101 to use units. Note that since CPython is an interpreter rather than a compiler, the concept of a compilation unit plays no role there. The use of units in combination with modules is shown in: https://transcrypt.org/docs/html/special_facilities.html#transcrypt-s-unit-mechanism-and-creating-native-javascript-component-frameworks This example should get you started, if not please let me know in a comment or edit. [EDIT] All units (as opposed to modules) should be compiled separately, so in the example: transcrypt -u .run animals.py transcrypt -u .com cats.py transcrypt -u .com dogs.py So the module containing the runtime with the .run option and the other components with the .com option. The -n switch can be added if desired. Modules that are used in multiple units should be added to the runtime unit, that is the one compiled with the -u .run switch.
accepted answer of: http://stackoverflow.com/q/48911754
type: Answer
answers question: http://stackoverflow.com/q/48911754
score: 2

http://stackoverflow.com/q/48881709
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/17071871
linked to: http://stackoverflow.com/q/43586176
linked to: http://stackoverflow.com/q/7106330
duplicate of: http://stackoverflow.com/q/17071871
has title: How to filter numeric values in Pandas not in Boolean values, but in a new column with filtered integers?
answer count: 0
downvote count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/15867337
tagged with: pandas
score: 1
favorite count: 0
has body: I have a dataset and a column with numeric values. In order to apply a log function to the column, I need to filter negative and zero values first. How can I create a new column (or a variable) with non-Boolean values? If I apply data['new_column'] = (data['old_column'] &gt; 0) I can only get Boolean values which are useful for me further. I assume my question is quite similar to the ones below, but I don't know how to transfer R syntax to Python. How to efficiently filter a data frame? Filter values in data frame How to filter out data out of a dataset?
type: Question

http://stackoverflow.com/q/48960699
has answer: http://stackoverflow.com/a/48961048
type: Question
upvote count: 4
linked to: http://stackoverflow.com/q/45085233
accepted answer: http://stackoverflow.com/a/48978754
answer count: 2
has body: May I ask how to change the kernel display name from Python [defaul] to Python 2.7.12 for example? I've been trying to modify the kernel.json file, particularly chaning the "display_name" from Python 2 to Python 2.7.12 But whenever I reopen the user interface through command ipython notebook, it never changes to what I want. To clarify the possible duplicate with previous question: I did try what it suggests to do as I describe in the question. Unfortunately, it just doesn’t work. It would be nice if someone who does make this change successfully could share how they do
has comment: http://stackoverflow.com/comment/84927808
downvote count: 0
possible better answer: http://stackoverflow.com/a/48961048
score: 4
has comment: http://stackoverflow.com/comment/84927872
has comment: http://stackoverflow.com/comment/85076586
tagged with: user-interface
tagged with: kernel
tagged with: jupyter-notebook
favorite count: 0
has title: How to Change Jupyter Notebook Kernel Display Name
has answer: http://stackoverflow.com/a/48978754
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84927933

rest
tags question: http://stackoverflow.com/q/48940073
tags question: http://stackoverflow.com/q/48903018
tags question: http://stackoverflow.com/q/48942393
tags question: http://stackoverflow.com/q/48901618
tags question: http://stackoverflow.com/q/48949726
tags question: http://stackoverflow.com/q/48900544
tags question: http://stackoverflow.com/q/48909280
tags question: http://stackoverflow.com/q/48862106
tags question: http://stackoverflow.com/q/48865152
tags question: http://stackoverflow.com/q/48842144
tags question: http://stackoverflow.com/q/48927972
type: Tag
tags question: http://stackoverflow.com/q/48901934
tag name: rest
tags question: http://stackoverflow.com/q/48807995
tags question: http://stackoverflow.com/q/48943331
tags question: http://stackoverflow.com/q/48941191
tags question: http://stackoverflow.com/q/48953184

http://stackoverflow.com/comment/84740014
comment on: http://stackoverflow.com/q/48866879
score: 0
type: QuestionComment
has text: I'm using OS X @Tom
type: Comment

http://stackoverflow.com/q/48867064
has title: Socket python + send back message to client
tagged with: python
has body: I have a basic python socket, like: server.py import socket ip = '192.168.2.231' port = 2005 addr = (ip, port) serv_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serv_socket.bind(addr) serv_socket.listen(2) con, cliente = serv_socket.accept() receive = con.recv(1024) if receive == '0123456789': #print "Accepted ACK" HERE - how can i send a message to client.py back serv_socket.close() How can i respond to the client.py that the sent ACK is correct? On line 16(server.py) I perform an IF and print a message, I want send a message back to the client.py saying that the ACK is invalid / invalid
type: Question
has answer: http://stackoverflow.com/a/48867290
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: sockets

http://stackoverflow.com/comment/84628523
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48812073
has text: Thanks for the help.

http://stackoverflow.com/q/48907127
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
has title: Pandas: Finding overlapping regions based on start- and stop coordinates
has body: I want to identify rows with start- and stop positions that overlap with the start- and stop position of other rows. There are a few restrictions that apply: The rows I want to check are a subset of the entire data set The rows in the subset should be compared to the entire data set The rows should not be compared with themselves Below is a minimal representation of the data set: id type start stop 0 1 AP 0 10 1 2 AP 3 7 2 3 ES 5 15 3 4 ES 12 18 Here's an image that describes the problem better. Each box represent an event/row, and the number represents their ID: And here's my desired output: id type start stop number_of_overlapping_exons 0 1 AP 0 10 2 1 2 AP 3 7 2 I want to find the rows with type equal to AP that have other rows (of any type) that overlap their position. In the image above, the blue boxes represent AP events. There are two events/rows overlapping blue box 1 (boxes 2 and 3), so the number_of_overlapping_exons for ID 1 should be 2. Blue box 2 also has two overlapping events (boxes 1 and 3). Here's what I've got so far: import pandas as pd # Sample input df = pd.DataFrame({ "id": [1, 2, 3, 4], "type": ["AP", "AP", "ES", "ES"], "start": [0, 3, 5, 12], "stop": [10, 7, 15, 18] }) # Extract only AP events ap = df.loc[df.type == "AP"] # Find events that overlap start positions in "ap" # by identifying "start" or "stop" positions in "df" # that are greater or equal to "start" positions in "ap". overlapping_start_positions = df.loc[(df.start &gt;= ap.start) | (df.stop &gt;= ap.start)] # Find events that overlap stop positions in "ap" # by identifying "start" or "stop" positions in "df" # that are smaller or equal to "stop" positions in "ap". overlapping_stop_positions = df.loc[(df.start &lt;= ap.stop) | (df.stop &lt;= ap.stop)] I'm getting a ValueError when doing overlapping_start_positions saying ValueError: Can only compare identically-labeled Series objects EDIT: Come to think of it, condition 3: The rows should not be compared with themselves is not rea…
tagged with: python
has answer: http://stackoverflow.com/a/48907701
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48907701

http://stackoverflow.com/a/48892659
type: Answer
has body: Looks like the output of the query is already a valid set of CSV rows so you can probably just write it as is to a file. # Your code import requests params = { "api_key": "tSKqprcg7k-S", "format": "csv" } r = requests.get('https://www.parsehub.com/api/v2/projects/tq1H9ha1sKAQ/last_ready_run/data', params=params) print(r.text) # This bit of code will write the result of the query to output.csv with open('output.csv', 'w+') as f: f.write(r.text)
answers question: http://stackoverflow.com/q/48892601
accepted answer of: http://stackoverflow.com/q/48892601
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48857557
has body: L3 += L1[i] + L2[i] is equivalent to L3.extend(L1[i] + L2[i]) L1[i] + L2[i] is a string like 'a1'. extend expects an iterable, and it will append each of its elements to the list. So, it iterates over your 'a1' string and appends to the list the elements 'a' and '1'. You want to append the string instead: L3.append(L1[i] + L2[i]) As noted by Mark Tolonen, L3 += [L1[i] + L2[i]] also works. It is equivalent to L3.extend([L1[i] + L2[i]]), so for example L3.extend(['a1']). In this case, extend will append the only element of the list it receives as parameter, 'a1', to L3.
type: Answer
upvote count: 4
has comment: http://stackoverflow.com/comment/84718763
downvote count: 0
answers question: http://stackoverflow.com/q/48857500
score: 4
has comment: http://stackoverflow.com/comment/84719033

http://stackoverflow.com/comment/84907952
score: 1
has text: The error says "You appear not to have the 'sqlite3' program installed". So, have you tried [installing it](https://www.sqlite.org/download.html) yet?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48950645

http://stackoverflow.com/comment/84694097
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48844892
has text: @BUZZY is there a less expensive way of achieving the same outcome?

http://stackoverflow.com/q/48837553
tagged with: python-3.5
score: -2
favorite count: 0
has comment: http://stackoverflow.com/comment/84680105
has answer: http://stackoverflow.com/a/49921321
has comment: http://stackoverflow.com/comment/84679802
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/84679854
has comment: http://stackoverflow.com/comment/84680161
has body: I'm super new to programming and I'm learning python. I am excited to announce that I have written 3 short programs so far. I am experimenting with while and for loops but can't get either implemented into my programs. Here is my pseudocode trying to use a for loop for the first time. Declare count Run leapyearprogram3 Count + 1 = Count Go back to line 2 I appreciate that there are multiple ways of doing this (range, xrange, while, etc.) and I am trying to understand how a for loop works and how to implement it in more than just the following code. # My leap year Python program. # This program demonstrates the following: # Determines if a user input of year is a leap year using the calendar # function # # Author: Thomas Schuhriemen # Course: CIS1400 import calendar t1= int(input()) print ("Welcome to my leap year program") print ("You may type any year and I will tell you if it is a leap year") # some of the following is based on code written by INDIAN VILLAN on # comments on w3resource.com # 3.0 is a stable build but this one (4.1) is experimenting with for to # repeat the question. count = 0 for count &gt;= 5: if calendar.isleap(t1) is True: print (t1, "is a leap year.") else: print (t1, "is not a leap year.") count = count + 1 I can't seem to grasp why this keeps giving me errors. I have given me an error saying there is something wrong with the code immediately following the for command the code it says "for count >= 5 &amp; count &lt;= 0:" has an invalid syntax error highlighting the "=" Thank you for your interest in helping me learn how to use for!
has comment: http://stackoverflow.com/comment/84679898
upvote count: 3
has title: Python 3.5 how to implement this while loop or for loop
has comment: http://stackoverflow.com/comment/84679837
type: Question
has answer: http://stackoverflow.com/a/48837658
accepted answer: http://stackoverflow.com/a/49921321
has answer: http://stackoverflow.com/a/48837683
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84680119
downvote count: 5
possible better answer: http://stackoverflow.com/a/48837658
has comment: http://stackoverflow.com/comment/84679827
has answer: http://stackoverflow.com/a/48838549

http://stackoverflow.com/comment/84660999
type: Comment
comment on: http://stackoverflow.com/a/48827966
has text: why do you think that I need to look for class attributes? I am searching for the origin of self.y variable. The fact that it starts with "self" indicates that it is an attribute of an instance. Am I wrong?
type: AnswerComment
score: 0

http://stackoverflow.com/q/48889787
has comment: http://stackoverflow.com/comment/84786474
has comment: http://stackoverflow.com/comment/84786333
tagged with: ram
tagged with: fpga
tagged with: memory
type: Question
answer count: 2
has title: How to optimize my writing from RAM to disc?
has comment: http://stackoverflow.com/comment/84785509
tagged with: optimization
has answer: http://stackoverflow.com/a/48891113
score: 0
has comment: http://stackoverflow.com/comment/84786763
tagged with: python
has body: I have some python code for reading data from RAM of an FPGA and writing it to disk on my computer. The code's runtime is 2.56sec. I need to bring it down to 2sec. mem = device.getNode("udaq.readout_mem").readBlock(16384) device.dispatch() ram.append(mem) ram.reverse() memory = ram.pop() for j in range(16384): if 0 &lt; j &lt; 4096: f.write('0x%05x\t0x%08x\n' %(j, memory[j])) if 8192 &lt; j &lt; 12288: f.write('0x%05x\t0x%08x\n' %(j, memory[j]))
has answer: http://stackoverflow.com/a/48889829
type: UnansweredQuestion

http://stackoverflow.com/comment/84888114
type: QuestionComment
comment on: http://stackoverflow.com/q/48940080
has text: not a torch user, so I'm afraid I can't help you with that. What does `.data[0]` do?
score: 0
type: Comment

http://stackoverflow.com/comment/84746271
comment on: http://stackoverflow.com/q/48871043
has text: What is the connecting link between both tables? Some ID?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84796808
type: QuestionComment
has text: Hint... google or here at SO + search function + *eyError: "name='csrftoken', domain=None, path=None"'* = possible solution [>> here <<](https://stackoverflow.com/questions/37816858/cannot-login-to-website-using-requests-module-python-version-3-5-1). Or [here](https://www.google.nl/search?q=python+eyError%3A+%22name%3D%27csrftoken%27%2C+domain%3DNone%2C+path%3DNone%22%27&ie=utf-8&oe=utf-8&client=firefox-b&gfe_rd=cr&dcr=0&ei=L6aMWuKdLpDA8gec2JSAAQ).
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48893436

http://stackoverflow.com/comment/84913557
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48953418
has text: Please copy-paste actual code, not image.

http://stackoverflow.com/a/48829059
accepted answer of: http://stackoverflow.com/q/48829035
score: 2
answers question: http://stackoverflow.com/q/48829035
downvote count: 0
has body: You can use argument unpacking: args = initializeVariables() doLotsOfStuff(*args)
upvote count: 2
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/comment/134495453
comment on: http://stackoverflow.com/a/76246779
has text: Why should the poster use two outputs? Your answer needs supporting information Your answer could be improved with additional supporting information. Please [edit](https://stackoverflow.com/posts/76246779/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](https://stackoverflow.com/help/how-to-answer).
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/48880588
downvote count: 0
has body: A little warning wrt to @Vivek Kalyanarangan's "zipper" solution. For longer sequences this is vulnerable to loss of significance. Let's use float32 for clarity: &gt;&gt;&gt; y = (1000 + np.sin(np.arange(1000000))).astype(np.float32) &gt;&gt;&gt; window=6 &gt;&gt;&gt; # naive zipper solution &gt;&gt;&gt; s=np.insert(np.cumsum(np.array(y)), 0, [0]) &gt;&gt;&gt; output = (s[window :] - s[:-window]) * (1. / window) # towards the end the result is clearly wrong &gt;&gt;&gt; print(output[-10:]) [1024. 1024. 1024. 1024. 1024. 1024. 1024. 1024. 1024. 1024.] &gt;&gt;&gt; # this can be alleviated by first taking the difference and then summing &gt;&gt;&gt; np.cumsum(np.r_[y[:window].sum(), y[window:]-y[:-window]])/window array([1000.02936, 999.98285, 999.9521 , ..., 1000.0247 , 1000.05304, 1000.0367 ], dtype=float32) &gt;&gt;&gt; # compare to last value calculated directly for reference &gt;&gt;&gt; np.mean(y[-6:]) 1000.03217 To further reduce the error one could chunk y and anchor the cumsum every so-and-so many terms without losing much speed.
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48879615

http://stackoverflow.com/comment/84836961
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48911236
score: 0
has text: What do you mean with "creating multiple objects by importing"? What is the workflow that you are trying to do?

http://stackoverflow.com/comment/84857640
type: QuestionComment
comment on: http://stackoverflow.com/q/48925609
has text: what is meant by Traceback(most recent call last)?
type: Comment
score: 0

http://stackoverflow.com/comment/84826331
comment on: http://stackoverflow.com/q/48894822
has text: Apologies for the poor question, however, @Lafexlos link was very helpful. That code did what I needed it to do.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48865521
has comment: http://stackoverflow.com/comment/84734276
type: Answer
has comment: http://stackoverflow.com/comment/84734105
has comment: http://stackoverflow.com/comment/84734204
accepted answer of: http://stackoverflow.com/q/48865451
has comment: http://stackoverflow.com/comment/84734234
score: 6
upvote count: 7
answers question: http://stackoverflow.com/q/48865451
downvote count: 1
has comment: http://stackoverflow.com/comment/84734053
has comment: http://stackoverflow.com/comment/84734080
has body: In your super-simple example. there's no practical difference, since functions are also callable objects. However, a callable object is an object of a class that you write, so you may write this code: class Counter: def __init__(self, value = 0): self.n = 0 def __call__(self): self.n += 1 return self.n def __repr__(self): return str(self.n) redWins = Counter() blueWins = Counter() if foo(): redWins() else: blueWins() print("Red has won {} times.\nBlue has won {} times." .format(redWins, blueWins)) And you'll find it hard to implement such a class using only functions. Even if you try to do it with global variables, you can't have separate instances of one single global variable. See more: Functions, Callable Objects, and how both are created in Python
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84734207

http://stackoverflow.com/a/48891067
score: 1
answers question: http://stackoverflow.com/q/48890702
upvote count: 1
type: Answer
has body: Try this: np.random.seed(0) df = pd.DataFrame({ 'a': [1, 2, 3] * 4, 'b': np.random.choice(['q','w','a'], size=12), 'c': 1 }) df a b c 0 1 q 1 1 2 w 1 2 3 q 1 3 1 w 1 4 2 w 1 5 3 a 1 6 1 q 1 7 2 a 1 8 3 q 1 9 1 q 1 10 2 q 1 11 3 a 1 df.groupby(['a', 'b']).count() c a b 1 q 3 w 1 2 a 1 q 1 w 2 3 a 2 q 2
downvote count: 0

http://stackoverflow.com/a/48880607
downvote count: 0
has body: If you want to fill_between you need to provide two curves. This code, for example, will fill the curves between gem and ys with green ax1.fill_between(xs, [gem] * len(xs), ys, facecolor='g', alpha=1) You seem to want to fill the parts above the gem threshold with red and below the gem threshold in green. Is this correct? Well, unfortunately for that to really work you need the intesection of the gem line and the curve to be part of the points array (have these points as part of xs and ys). That is because fill_between uses only the points that are actually passed to it. The following code will first add intersection points, and then will seperate to curves above and below gem for the colorization # Add intersection points yys = [ys[0]] xxs = [xs[0]] for i in range(1, len(xs)): if (ys[i - 1] &lt; gem and ys[i] &gt; gem) or (ys[i - 1] &gt; gem and ys[i] &lt; gem): yys.append(gem) xxs.append(xs[i - 1] + (gem - ys[i - 1]) / (ys[i] - ys[i - 1]) \ * (xs[i] - xs[i - 1])) xxs.append(xs[i]) yys.append(ys[i]) # Seperate to above and below gem curves belowgem = [y if y &lt;= gem else gem for y in yys] abovegem = [y if y &gt;= gem else gem for y in yys] # fill between ax1.fill_between(xxs, [gem] * len(xxs), belowgem, facecolor='g', alpha=1) ax1.fill_between(xxs, [gem] * len(xxs), abovegem, facecolor='r', alpha=1)
has comment: http://stackoverflow.com/comment/84765538
type: Answer
has comment: http://stackoverflow.com/comment/84765608
has comment: http://stackoverflow.com/comment/84767988
upvote count: 1
answers question: http://stackoverflow.com/q/48878403
score: 1

http://stackoverflow.com/q/48963034
has body: I am currently working on a project where I have scraped reviews relating to a retailer from a review website. The aim is to use a Random Forest classifier to classify each review in the dataset by subject; 'Delivery' or 'Customer Service'. After looking at the dataset, over 90% of the reviews (both training and test data) relate to 'Delivery'. I have been advised by my lecturer that we need to account for sample bias. I've researched this and tried to implement some correction in Python below using ADASYN (near the bottom of the code below): import pandas as pd chunksize = 10 TextFileReader = pd.read_csv('TestToSentimentAnalyse.csv', chunksize=chunksize, header=None) dataset = pd.concat(TextFileReader, ignore_index=False) dataset.columns = ['Reviews', 'Delivery', 'Customer_Service', 'Purchase_Date', 'Likelihood_to_Recommend', 'Overall_Satisfaction', 'Location', 'Date_Published', 'Sentiment'] dataset = dataset.iloc[1:] # Cleaning the texts import re corpus = [] for i in range(1, 29779): corpus.append(review) # Creating the Bag of Words model from sklearn.feature_extraction.text import CountVectorizer cv = CountVectorizer() X = cv.fit_transform(corpus).toarray() # Set up dependant variable - delivery is 0, customer service is 1 y = [] for i in range(1, 29779): if dataset['Delivery'][i] == '2': y.append(1) elif dataset['Customer_Service'][i] == '2': y.append(0) elif dataset['Delivery'][i] == '0' and dataset['Customer_Service'][i] == '0': y.append(0.5) ## flaw in this as we had to choose one elif dataset['Delivery'][i] == '1' and dataset['Customer_Service'][i] == '1': y.append(0.5) ## flaw in this as we had to choose one elif dataset['Delivery'][i] == '0' and dataset['Customer_Service'][i] == '1': y.append(0) elif dataset['Delivery'][i] == '1' and dataset['Customer_Service'][i] == '0': y.append(1) elif dataset['Delivery'][i] == 2: y.append(1) elif dataset['Customer_Service'][i] == 2: y.append(0) elif dataset['Delivery'][i] == 0 and dataset['Customer_Service'][i] == 0: …
score: 2
answer count: 0
tagged with: text-classification
type: Question
downvote count: 0
has title: Resolving Sample Bias in Text Classification - Python - ADASYN
favorite count: 0
tagged with: sampling
upvote count: 2
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/48933241
upvote count: 2
has body: If you want to use only builtin packages, you can use csv. import csv with open("mid.dat") as myfile: csv_records = csv.reader(myfile) list1 = [] list2 = [] for row in csv_records: list1.append(row[0]) list2.append(row[1])
answers question: http://stackoverflow.com/q/48933120
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/a/48965367
has comment: http://stackoverflow.com/comment/84937677
has comment: http://stackoverflow.com/comment/84937094
has comment: http://stackoverflow.com/comment/84937819
answers question: http://stackoverflow.com/q/48906516
has body: ZeroMQ would be my choice for doing UDP/multicast ZeroMQ framework has all the tooling ready and is right-enough for this type of tasks. API documentation has all the details + you may remember my advice on also reading the excellent book "Code Connected: Volume 1". Worth time and efforts ( PDF already available ). Server will .bind() and clients will .connect(), using either a pgm:// ( with possible rate-limitation tools ) or an epgm:// transport-class for the actual infrstructure setup and later for any message delivery. Server-side # -------------------------------------------------------------------- # proper error-state &amp; Event handling is not presented in this mock-up # -------------------------------------------------------------------- aCtx = zmq.Context() aPUB = aCtx.Socket( zmq.PUB ) aPUB.bind( "epgm://eth0;239.192.1.1:5556" ) aPUB.setsockopt( zmq.LINGER, 0 ) # -------------------------------------------------------------------- # proper error-state &amp; Event handling is not presented in this mock-up # -------------------------------------------------------------------- while True: aPUB.send( binascii.unhexlify( msg + ( "%06X" %id ) ), zmq.NOBLOCK ) id += 1 time.sleep( 0.1 ) # -------------------------------------------------------------------- # proper error-state &amp; Event handling is not presented in this mock-up # -------------------------------------------------------------------- aPUB.close() aCtx.term() Clients will: # -------------------------------------------------------------------- # proper error-state &amp; Event handling is not presented in this mock-up # -------------------------------------------------------------------- aCtx = zmq.Context() aSUB = aCtx.Socket( zmq.SUB ) aSUB.connect( "epgm://eth0;239.192.1.1:5556" ) aSUB.setsockopt( zmq.LINGER, 0 ) aSUB.setsockopt( zmq.SUBSCRIBE, "" ) # -------------------------------------------------------------------- # proper error-state &amp; Event handling is not presented in this mock-up # -…
score: 0
has comment: http://stackoverflow.com/comment/84937474
type: Answer

http://stackoverflow.com/comment/84621628
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48808886
has text: I anticipated this solution in my final paragraph. It is not what I am looking for because when it is called like `Bar.method(Foo())`, then `method` has no idea that its receiver was the `Bar` class. That information is lost.

http://stackoverflow.com/q/48918819
has title: Wigets inside of second panel dissapear
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48922804
type: Question
has body: This is a "part two" to this question. So I have this (same) code: import wx import screeninfo class application(wx.Frame): def __init__(self, *args, **kw): super(application, self).__init__(*args, **kw) # Panels panel = wx.Panel(self) StuffPanel = wx.Panel(panel, 1) # Header Header = wx.StaticText(panel, label="Browse", pos=(25, 25)) HeaderFont = Header.GetFont() HeaderFont.PointSize += 10 HeaderFont = HeaderFont.Bold() Header.SetFont(HeaderFont) # displaying everything in 'override_contents.py' import override_contents as over posx = 25 posy = 60 change = 0 def contentButtonDisplay(panel=StuffPanel, id=wx.ID_ANY, label="None", pos=(0,0), event=None, i=None): wx.Button(panel, id, label, pos).Bind(wx.EVT_BUTTON, event) for i in over.contents: contentButtonDisplay(label=i["name"], pos=(posx, posy), event=i["event"]) if change == 5: posy += 50 posx = 25 change = 0 else: posx += 100 change += 1 for m in screeninfo.get_monitors(): r1 = str(m).split("x") screenx = r1[0].split("(")[1] screeny = r1[1].split("+")[0] app = wx.App() frm = application(None, title='Browse', size=(int(screenx), int(screeny))) frm.Show() app.MainLoop() And override_contents: import wx def onPygame(): wx.MessageBox("Pygame!", "Pygame!") def onWxpython(): wx.MessageBox("WxPython!", "WxPython") def onScreeninfo(): wx.MessageBox("Screeninfo", "Screeninfo") contents=[ { "name" : "PyGame", "event": lambda _: onPygame() }, { "name": "WxPython", "event" : lambda _: onWxpython() }, { "name": "Screeninfo", "event" : lambda _: onScreeninfo() }, { "name": "Screeninfo", "event" : lambda _: onScreeninfo() }, { "name": "Screeninfo", "event" : lambda _: onScreeninfo() }, { "name": "Screeninfo", "event" : lambda _: onScreeninfo() }, { "name": "Screeninfo", "event" : lambda _: onScreeninfo() } ] So i'm trying to use two panels, panel and StuffPanel. panel is the main panel, and StuffPanel is where the buttons are being put at. The problem is that when I run it, it displays this: The Image Basicly, it doesn't even …
tagged with: user-interface
tagged with: wxwidgets
score: 0
accepted answer: http://stackoverflow.com/a/48922804
answer count: 1
tagged with: python-3.x
tagged with: python
linked to: http://stackoverflow.com/q/48897597

http://stackoverflow.com/q/48885417
type: Question
score: 0
has title: How to fix an unexpected keyword argument 'axis
tagged with: axis
tagged with: arguments
has comment: http://stackoverflow.com/comment/84776664
has body: the error code is distance=tf.reduce_sum(tf.abs(tf.sub(x_data_train,tf.expand_dims(x_data_test,1))), axis=2 ) this part makes TypeError: reduce_sum() got an unexpected keyword argument 'axis' when I search this error it is maybe version problem. but I don't know exactly. what is the problem?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84776761
tagged with: keyword
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/84846149
tagged with: tensorflow

http://stackoverflow.com/q/48900544
favorite count: 0
tagged with: rest
type: UnansweredQuestion
has title: Understanding REST parameters in google-search-api
tagged with: python
score: 3
answer count: 0
upvote count: 3
tagged with: google-search-api
type: Question
has body: To automatically download image URLs found through googles' search API, I need to be able to programmatically generate relevant search queries in my script. The search url I currently use in my python script looks like this: url = 'https://www.google.com/search?q=' + quote( search_term) + '&amp;espv=2&amp;biw=1366&amp;bih=667&amp;site=webhp&amp;source=lnms&amp;tbm=isch' + params + '&amp;sa=X&amp;ei=XosDVaCXD8TasATItgE&amp;ved=0CAcQ_AUoAg' Which works well if I use simple or combined queries like search_term = "Cats AND -Dogs" When I enter "cats" in google and switch to the images tab, I see the following panel of term-buttons, right above the first images of adorable kittens: Clicking on the buttons "cute","anime" and "love" e.g. changes the search url to https://www.google.de/search?tbm=isch&amp;q=cats&amp;chips=q:cats,g_1:anime,g_2:cute,g_8:love&amp;sa=X&amp;ved=0ahUKEwj6ra6-v7bZAhXEvhQKHR4UCYsQ4lYIOCgA&amp;biw=1536&amp;bih=386&amp;dpr=1 Now to use that feature in my script, I need to understand the following things: In what way does selecting one of the buttons refine or complement my search? Is this a successive refinement of search terms, or a logical combination? The parameter names g_1, g_2 and g_8 in the url above imply some kind of hierarchical ordering. but what do they actually stand for?
downvote count: 0

http://stackoverflow.com/q/48822796
score: 0
has answer: http://stackoverflow.com/a/48822919
tagged with: python
has comment: http://stackoverflow.com/comment/84717497
type: AnsweredQuestion
has title: Probability for correct Image Classification in Tensorflow
has body: I am using Tensorflow retraining model for Image Classification. I am doing single label classification. I want to set a threshold for correct classification. In other words, if the highest probability is less than a given threshold, I can say that the image is "unknown" i.e. if np.max(results) &lt; 0.5 -> set label as "unknown". So, is there any industry standard to set this threshold. I can set a random value say 60%, but is there any literature to back this threshold ? Any links or references will be very helpful. Thanks a lot.
tagged with: image-processing
tagged with: tensorflow
type: Question
accepted answer: http://stackoverflow.com/a/48822919
answer count: 1

http://stackoverflow.com/q/48859161
type: Question
has comment: http://stackoverflow.com/comment/84721842
answer count: 2
has comment: http://stackoverflow.com/comment/84721718
favorite count: 0
possible better answer: http://stackoverflow.com/a/48859342
has title: Plotting Acclerometer Data With Respect To Time
has answer: http://stackoverflow.com/a/48859342
score: 2
upvote count: 3
tagged with: python
downvote count: 1
tagged with: plot
has body: So I am trying to plot accelerometer data with regards to time, my csv reads like this(columns -> time, x, y, z): 1518999378635,2.275090217590332,8.601768493652344,3.691260576248169 1518999378653,2.38462495803833,8.633491516113281,4.0964789390563965 1518999378658,2.449866771697998,8.506000518798828,4.082113742828369 1518999378667,2.4372973442077637,8.166622161865234,4.016273498535156 1518999378675,1.8381483554840088,8.848969459533691,4.086902141571045 1518999378681,1.1402385234832764,8.762179374694824,4.225766181945801 1518999378688,1.7818846702575684,8.652046203613281,3.6110546588897705 1518999378694,2.076371431350708,8.80467700958252,4.0527849197387695 1518999378700,2.3720552921295166,8.471882820129395,4.120420932769775 My initial bet (as given below!) was to use a scatter with time as color, however the output is, well, not very obvious. from numpy import genfromtxt from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np if __name__ == "__main__": print("Plotting Accelerometer Data") acm_data = genfromtxt("acm_data.csv", delimiter=',', names="time, acc_x, acc_y, acc_z") fig = plt.figure() ax = fig.add_subplot(111, projection='3d') x = acm_data["acc_x"] y = acm_data["acc_y"] z = acm_data["acc_z"] c = acm_data["time"] ax.scatter(x, y, z, c=c, cmap=plt.hot()) plt.show() The output looks viz: and is not very interpretable. What would be the best way to handle this? Thanks.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48859319
accepted answer: http://stackoverflow.com/a/48859319
has comment: http://stackoverflow.com/comment/84721748

http://stackoverflow.com/q/48857612
has body: I have inherited code that looks something like this: class A: def __init__(self): print('A') def foo(self, *args): print('foo') a = A() setattr(a,'foo',types.MethodType(foo,a,A)) For that last line, I want to make the code 2to3 compatible, but MethodType only takes two arguments in python3. Simplest option is probably to let it break intelligently and try: setattr(a,'foo',types.MethodType(foo,a,A)) except TypeError: setattr(a,'foo',types.MethodType(foo,a)) But then I realized that I don't understand why I'm adding the third argument in python2, because setattr(a,'foo',types.MethodType(foo,a)) works across languages. In Python2, what is the third argument buying me, to bind it to the class vs not? &gt;&gt;&gt; types.MethodType(foo,a) &lt;bound method ?.foo of &lt;__main__.A instance at 0x1&gt;&gt; &gt;&gt;&gt; types.MethodType(foo,a,A) &lt;bound method A.foo of &lt;__main__.A instance at 0x1&gt;&gt;
type: Question
possible better answer: http://stackoverflow.com/a/48857988
tagged with: python-2.7
answer count: 2
downvote count: 0
has title: types.MethodType third argument in python2
score: 8
favorite count: 0
has answer: http://stackoverflow.com/a/48857988
upvote count: 8
has answer: http://stackoverflow.com/a/48857684
tagged with: python
accepted answer: http://stackoverflow.com/a/48857684
type: AnsweredQuestion

http://stackoverflow.com/q/48813097
score: 27
linked to: http://stackoverflow.com/q/394809
has comment: http://stackoverflow.com/comment/94359368
accepted answer: http://stackoverflow.com/a/48813117
favorite count: 0
upvote count: 30
possible better answer: http://stackoverflow.com/a/65468002
has answer: http://stackoverflow.com/a/70650220
has answer: http://stackoverflow.com/a/65468002
tagged with: python
has title: Does Python have the Elvis operator?
linked to: http://stackoverflow.com/q/39983695
answer count: 4
type: AnsweredQuestion
has body: The ternary operator in many languages works like so: x = f() ? f() : g() Where if f() is truthy then x is assigned the value of f(), otherwise it is assigned the value of g(). However, some languages have a more succinct elvis operator that is functionally equivalent: x = f() ?: g() In python, the ternary operator is expressed like so: x = f() if f() else g() But does python have the more succinct elvis operator? Maybe something like: x = f() else g() # Not actually valid python
downvote count: 3
linked to: http://stackoverflow.com/q/4978738
tagged with: elvis-operator
tagged with: conditional-operator
type: Question
has answer: http://stackoverflow.com/a/48813117
has answer: http://stackoverflow.com/a/60629945

http://stackoverflow.com/comment/84771460
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48883565
has text: What is the error you're getting? Please add the full traceback to the question.

http://stackoverflow.com/comment/84757617
comment on: http://stackoverflow.com/q/48876458
has text: do you mean change this line to ```while next_image_button.is_displayed():``` underneath the try/except? If I use break, does it just break the while loop or my entire script altogether?
score: 0
type: Comment
type: QuestionComment

mechanicalsoup
tag name: mechanicalsoup
tags question: http://stackoverflow.com/q/48897494
type: Tag

http://stackoverflow.com/comment/84758032
score: 0
comment on: http://stackoverflow.com/a/48876624
type: Comment
has text: I may have isolated the issue, when I try to retrieve the csrftoken in `post_request.cookies['csrftoken']` I'm getting this error: `KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))`
type: AnswerComment

http://stackoverflow.com/a/48861810
type: AcceptedAnswer
downvote count: 0
has body: You have to use IOLoop.add_future() since async_func() returns a Future (it is decorated as a coroutine!). Also, you should add the future, when you receive the start message, not on any message: def on_message(self, message): if(message == "START"): self.sending = True tornado.ioloop.IOLoop.current().add_future( self.async_func(self), lambda f: self.close()) if(message == "STOP"): self.sending = False
accepted answer of: http://stackoverflow.com/q/48861657
type: Answer
answers question: http://stackoverflow.com/q/48861657
upvote count: 1
has comment: http://stackoverflow.com/comment/84727367
score: 1
has comment: http://stackoverflow.com/comment/84727610

http://stackoverflow.com/q/48881883
has comment: http://stackoverflow.com/comment/84770677
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84768926
has comment: http://stackoverflow.com/comment/84770812
has comment: http://stackoverflow.com/comment/84769357
has comment: http://stackoverflow.com/comment/84771984
type: Question
has answer: http://stackoverflow.com/a/48884347
has title: Handling writing data to textfiles
linked to: http://stackoverflow.com/q/12444004
tagged with: python
tagged with: text-files
tagged with: large-files
has comment: http://stackoverflow.com/comment/84768626
score: 0
has answer: http://stackoverflow.com/a/48884060
answer count: 2
tagged with: netcdf
has body: I have a general question. It concerns the writing of a large number of large text files. The content of the textfile is based on a dataset and differs for each textfile. The basic question is how to do so most efficiently. More specifically, I want to perform spatially explicit model runs (crop model). The model requires input files to be in txt format. So if I wish to run the model for a large number of raster cells - I need a textfile for each cell (1000s). The efficiency problem occurs when writing the weather input based on climate projections. They are in daily time steps for up to 100 years - eg. 36500 lines (each 8 variables) extracted from the dataset and written to each textfile. My first attempt was to create a for loop that loops through each location (i.e. each textfile) and for each textfile loops through each daily climate timestep to create the whole string for the climate file and then write it to the text file (I also tested writing each time step to file but efficiency was similar). This approach takes ca. 1-2min per file on my (a bit old) machine. For a raster of 70x80 cells ca. 7days. Of course I could scale down the number of locations and select less timesteps - but, nevertheless, I wonder whether there is a more effective way to do this? As from research I believe that the for loop that strings/writes each line together/to file is the bottleneck, I wonder whether pulling the data into an array or dataframe and then saving to cv would be quicker? Or what do you suggest as the most suitable approach for this operation? Thank you in advance! Bests regards, Anton. Here the code: Please let me know if I should provide additional code/info etc. as I am new to programming and teaching myself for a month now - apologies is things are a bit messy. weather_dir = os.path.join( os.getcwd() , "data" , "raw" , "weather" ) precip45l = glob.glob(weather_dir+"/pr*45*d.nc") tasmax45l = glob.glob(weather_dir+"/tasmax*45*") tasmin45l = glob.glob(weather_dir+"/ta…
has comment: http://stackoverflow.com/comment/84768087
has comment: http://stackoverflow.com/comment/84768601

http://stackoverflow.com/comment/84830477
score: 0
comment on: http://stackoverflow.com/q/48911830
type: Comment
type: QuestionComment
has text: is you city is always come with the state, and is well ordered

http://stackoverflow.com/comment/84688874
comment on: http://stackoverflow.com/q/48842368
score: 0
type: Comment
type: QuestionComment
has text: @srinivasreddy: You should [edit] that information into your question.

http://stackoverflow.com/q/48808941
answer count: 1
has comment: http://stackoverflow.com/comment/84631244
favorite count: 0
tagged with: geometry
has body: Does anyone know if it is possible to calculate the overlapping area of two ellipses using matplotlib.patches.Ellipse. I have to ellipses like this: And i would like to calculate the ratio between the overlap area and the are of the individual ellipses. Is this possible using only the Ellipse from matplotlib.patches
accepted answer: http://stackoverflow.com/a/48812832
tagged with: python
tagged with: ellipse
has title: Overlap area of 2 ellipses using matplotlib
type: AnsweredQuestion
score: 1
tagged with: matplotlib
upvote count: 1
has comment: http://stackoverflow.com/comment/84734162
type: Question
has answer: http://stackoverflow.com/a/48812832
downvote count: 0
has comment: http://stackoverflow.com/comment/84621796

http://stackoverflow.com/q/48884346
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: css
tagged with: plot
answer count: 0
score: 1
tagged with: plotly
upvote count: 1
type: Question
linked to: http://stackoverflow.com/q/48879674
tagged with: javascript
has title: How to fit Plotly plot size dynamically
downvote count: 0
has body: Previously I asked a question how to fit Bokeh plot size dynamically and I got a solution from HYRY. How to fit bokeh plot size dynamically Now I would like the same question for the Plotly plot. Similarly to HYRY's method, I could achieve the same effect using Plotly.relayout javascript function: TweenMax.to($("#div2"), 0.5, {height:800, onUpdate:function(){Plotly.relayout("493d6ad0-561e-49b1-9c37-f9c427ba7880", {width:1800, height:800});}}); Thanks again to HYRY. What's inconvenient for Plotly case, I could not find a way to specify plot id on my own. In Bokeh, we can supply id via python function instead of randomly generated id: blue = figure(sizing_mode='stretch_both', tools='pan', id="blue_fig") Would there be any good way?

http://stackoverflow.com/comment/84923425
score: 0
type: Comment
has text: Yes, although note, what it returns won't be convertable back to the correct code-point, i.e. `ord(chr(174).encode('ascii', errors='replace').decode("utf-8"))` won't be `174`
comment on: http://stackoverflow.com/a/48958245
type: AnswerComment

http://stackoverflow.com/comment/84692044
has text: @PaulPanzer: Thanks for the heads-up.
comment on: http://stackoverflow.com/a/48843836
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84850713
has text: @chrisz depending on OP's background knowledge (in combinatorics, recursion, Python, etc.), it may be extremely difficult or even impossible to even get started on this problem.
comment on: http://stackoverflow.com/q/48921965
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84738296
type: AnswerComment
has text: This solution worked for me. Earlier, I used encoding='utf8' but it did not work, now I changed to encoding='utf-8' and adding this '-' helped I guess.
type: Comment
comment on: http://stackoverflow.com/a/48867028
score: 0

http://stackoverflow.com/a/79100179
score: 0
answers question: http://stackoverflow.com/q/48909110
type: Answer
has body: Stumbled on this question when I was trying to create average and sum of the same column of a dataframe with a groupby operation. The last part of the jezrael's answer is also applicable for same columns. For example, using the same data setting above you can get the average and sum of the Grade column partitioned on the Name column with: grouped_df = df.groupby('Name').agg(avg_grade = ('Grade', 'mean'), total_grade = ('Grade', 'total')) print(grouped_df) avg_grade total_grade Name A 11.0 22 B 15.0 30 Thus, I am leaving this answer here for the ones encountering this question with a similar issue.

http://stackoverflow.com/comment/84650444
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48822567
has text: Totally unrelated, but you should use the csv module to write your file too.
score: 0

http://stackoverflow.com/q/48956252
favorite count: 0
tagged with: python
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/89090451
tagged with: machine-learning
linked to: http://stackoverflow.com/q/49208617
type: Question
accepted answer: http://stackoverflow.com/a/48957375
has title: scitkit SGDClassifier partial_fit doesnot learn incrementally. Returns “classes should include all valid labels"
upvote count: 3
has body: I passed two streams of data to sgd_clf classifier as shown in below code. First partial_fit is taking first stream of data x1,y1. Second partial_fit is taking the second stream of data x2,y2. The below code gives me error at second partial_fit step that class lables to be included prior. This error is gone when i include all my data from x2 y2 in x1, y1. (My class labels are included prior to calling second partial_fit now) However, i cannot give this x2 y2 data prior. If at all i give all my data before first partial_fit(), why is there any need for me to use second partial_fit() ? Infact, if i know all data before, i dont need to use partial_fit(), i could just do fit(). from sklearn import neighbors, linear_model import numpy as np def train_new_data(): sgd_clf = linear_model.SGDClassifier() x1 = [[8, 9], [20, 22]] y1 = [5, 6] classes = np.unique(y1) #print(classes) sgd_clf.partial_fit(x1,y1,classes=classes) x2 = [10, 12] y2 = 8 sgd_clf.partial_fit([x2], [y2],classes=classes)#Error here!! return sgd_clf if __name__ == "__main__": print(train_new_data().predict([[20,22]])) Q1: Is my understanding of partial_fit() for sklearn classifiers wrong that it takes data on the fly as specified here: Incremental Learning Q2: I want to retrain a model/update a model with the new data. I dont want to train from scratch. Will partial_fit help me with this ? Q3: I am not specific only to SGDClassifier. I can use any algorithm that support online/batch learning. My main intention is Q3. I have a trained model on 1000's of images. I dont want to retrain this model from scratch just because i have one/two new samples of images. Neither interested in creating a new model for each new entry and then mix all of them. This decreases my performance for predictions to search all over the trained models. I just want to add this new data instances to the trained model with the help of partial_fit. Is this feasible ? Q4: If i cannot acheive Q2 with scikit classifiers, Please direct me how…
has answer: http://stackoverflow.com/a/48957375
downvote count: 1
answer count: 1
tagged with: scikit-learn

http://stackoverflow.com/q/48853535
tagged with: python
has comment: http://stackoverflow.com/comment/84711198
score: 1
has answer: http://stackoverflow.com/a/69029170
linked to: http://stackoverflow.com/q/17257878
upvote count: 1
type: Question
has title: Python: Changing filenames and folder names in all folders and subfolders
has answer: http://stackoverflow.com/a/48853565
has body: I want to change the file names and folder names in a given directory and all subfolders. My folder structure is as follows: top directory file1 file2 folder1 file1 file2 file3 file4 folder2 file1 file2 file3 file4 I get the following error when executing the code below. I already checked the forums, but couldn't find a solution. Could someone please help me solve this issue and let me know what I need to do to get the program working? Or is there a better solution for renaming files and folders in a tree? Error message FileNotFoundError: [WinError 2] The system cannot find the file specified: 'Filename 1' -> 'filename_1' Code #Change file names and folder names in a given directory and all its subfolders import os os.chdir("path\\to\\folder") print(os.getcwd()) #Walk the directory and change the file names and folder names in all folders and subfolders. for root, dirs, files in os.walk("path\\to\\folder"): for dir_name in dirs: os.rename(dir_name, dir_name.replace(" ", "_").lower()) for file_name in files: os.rename(file_name, file_name.replace(" ", "_").lower()) #Print done once all files have been renamed. print("done")
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84711235
has answer: http://stackoverflow.com/a/48853600
has answer: http://stackoverflow.com/a/48853865
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48853889

http://stackoverflow.com/a/48929727
answers question: http://stackoverflow.com/q/48923946
type: Answer
has body: this gives output in list data Type import subprocess out=subprocess.check_output(["hadoop","fs","-ls","&lt;directory&gt;"] ).split("\n") out
score: 0

http://stackoverflow.com/a/48835819
has comment: http://stackoverflow.com/comment/84677728
has body: Try this: content = [] with open('file.ext', as 'r') as file_in: content = file_in.readlines() new_content = [] for line in file: clean_line = line.replace('\00', '') new_content.append(clean_line) with open('outfile.ext', 'w') as file_out: file_out.writelines(new_content)
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48835731
has comment: http://stackoverflow.com/comment/84676786
score: 2
upvote count: 2

http://stackoverflow.com/comment/84619608
score: 0
type: Comment
has text: A very small trial: figure creation and `ax2 = ax1.twiny()` outside the loop?
type: QuestionComment
comment on: http://stackoverflow.com/q/48808320

http://stackoverflow.com/a/48826536
type: Answer
answers question: http://stackoverflow.com/q/48826408
downvote count: 0
has comment: http://stackoverflow.com/comment/84656943
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84656820
has body: EDIT: As roganjosh pointed out, I was not clear enough in my description. Taking out the print() function from game_info[i].display() in the last for loop will fix the issue. class Info: def __init__(self, name, score): self.name = name self.score = score def display(self): print(f"Name :- {self.name}, Score :- {self.score}") game_info = [] for i in range(3): n = input("Enter Your Name :- ") s = int(input("Enter Your Score :- ")) game_info.append(Info(n, s)) print() for i in range(3): game_info[i].display() print() Output: Enter Your Name :- Bob Enter Your Score :- 1 Enter Your Name :- Jane Enter Your Score :- 2 Enter Your Name :- Sally Enter Your Score :- 3 Name :- Bob, Score :- 1 Name :- Jane, Score :- 2 Name :- Sally, Score :- 3

http://stackoverflow.com/a/48934072
has body: def finditbaby(path): endtime = time.time() + 10 #only 10 second for test while time.time() &lt; endtime: if pyautogui.locateOnScreen(path) != None: print("image found") # click on image break maybe you can change to this... you don't need declare a variable to image I guess
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48930892
downvote count: 0

http://stackoverflow.com/q/48920850
tagged with: python
has title: how can I extract multiple random sub-sequences from a numpy array
score: 2
type: AnsweredQuestion
type: Question
tagged with: numpy
downvote count: 0
answer count: 1
has body: say I have a sequence s and I'd like to select n random sub sequences from it each with length l and store in a matrix. Is there a more numpy way of doing that than s = np.arange(0, 1000) n = 5 l = 10 i = np.random.randint(0, len(s)-10, 5) ss = np.array([s[x:x+l] for x in i])
has answer: http://stackoverflow.com/a/48920925
linked to: http://stackoverflow.com/q/47982894
favorite count: 0
accepted answer: http://stackoverflow.com/a/48920925
linked to: http://stackoverflow.com/q/48380129
upvote count: 2
linked to: http://stackoverflow.com/q/48191060

http://stackoverflow.com/comment/84893115
type: Comment
type: QuestionComment
has text: I've mentioned this as pseudo. but the concept is required in python.
comment on: http://stackoverflow.com/q/48943285
score: 0

http://stackoverflow.com/comment/84893089
score: 3
type: Comment
type: QuestionComment
has text: this isn't Python!
comment on: http://stackoverflow.com/q/48943285

http://stackoverflow.com/comment/84720809
score: 0
has text: What have you tried? Have you seen [this thread](https://stackoverflow.com/questions/8749158/removing-duplicates-from-dictionary) or [this site](https://www.w3resource.com/python-exercises/dictionary/python-data-type-dictionary-exercise-17.php)? Just Googling around....
type: QuestionComment
comment on: http://stackoverflow.com/q/48858683
type: Comment

http://stackoverflow.com/q/48877502
tagged with: python
tagged with: opencv
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48879914
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48878120
type: Question
has title: How to fix "TypeError: a float is required" message?
has answer: http://stackoverflow.com/a/48879914
answer count: 2
upvote count: 1
favorite count: 0
has body: I'm using Python and I get this error: TypeError: a float is required. Here is my code: cv2.putText(img,str(sampleNum + 1), (x,y+h+30),font, (255,255,255))
possible better answer: http://stackoverflow.com/a/48878120

http://stackoverflow.com/comment/85059085
type: Comment
comment on: http://stackoverflow.com/a/48960509
has text: @Aphid I have pasted the Iframe content can you help.
score: 0
type: AnswerComment

http://stackoverflow.com/q/48912695
has comment: http://stackoverflow.com/comment/84831929
has comment: http://stackoverflow.com/comment/84832207
has comment: http://stackoverflow.com/comment/84832888
has body: I'm an electronics hobbist, who trying to use ML for modelling errors in sensors, I've trained the model on sensor data in my PC using SVM in scikit-learn in python. But the use-case for the filtered data is very instantaneous, i.e the sensor data is used to maintain flight of a quadcopter and the raw sensor data should filter through learned model at-least at the rate of 200 Hz, sure my PC can do it, but I cant put my PC on quadcopter, hence I need that model running on a tiny CPU/microcontroller but, no suitable microcontroller of my choice supports python. So how can I get/extract the mathematical essence of the learned model, in other words, how can I get that function which was approximated by training so that I can implement it in any microcontroller of my choice. Just a beginner trying to learn, any help would be appreciated.
has answer: http://stackoverflow.com/a/48919018
answer count: 1
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/84844447
favorite count: 0
has title: How to extract learned ML model for distinct implementation?
tagged with: python-3.x
tagged with: python
upvote count: 4
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/8360253
downvote count: 0
has comment: http://stackoverflow.com/comment/84833338
tagged with: machine-learning
type: Question
has comment: http://stackoverflow.com/comment/84832289
has comment: http://stackoverflow.com/comment/84831847
accepted answer: http://stackoverflow.com/a/48919018
score: 4
tagged with: svm

http://stackoverflow.com/q/48856775
has answer: http://stackoverflow.com/a/48856798
tagged with: python
tagged with: regex
downvote count: 0
tagged with: negation
type: AnsweredQuestion
score: 3
has title: re.sub with exception or condition
type: Question
tagged with: replace
answer count: 1
accepted answer: http://stackoverflow.com/a/48856798
favorite count: 0
upvote count: 3
has body: I want to sub use re.sub to substitute all the words with parentheses but not the word (k), I want to use some negation conditions but it seems not working to my example. I've tried \((?&lt;!k)\w+\) Is there any suggestions? re.sub(r'\((?&lt;!k)\w+\)', '', '(k) i am, us dep economy (applause) (ph)', flags= re.IGNORECASE) Desired result would be (k) i am, us dep economy

http://stackoverflow.com/comment/84862450
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48928026
has text: have you tried this : `df = df[np.isfinite(df['EPS'])]`

http://stackoverflow.com/comment/84929709
has text: would you mind to show me a solution using my script ? I did hear about threading package., but I honestly dont have ideia to how include multiple tasks at this code.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48961738
score: 0

http://stackoverflow.com/q/48879920
accepted answer: http://stackoverflow.com/a/48912833
score: 13
tagged with: airflow-scheduler
upvote count: 13
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/58219024
type: Question
tagged with: airflow
downvote count: 0
has answer: http://stackoverflow.com/a/48912833
has answer: http://stackoverflow.com/a/63043513
has answer: http://stackoverflow.com/a/50629425
tagged with: python
answer count: 4
has title: Airflow Worker Configuration
has body: I am a newbie to Airflow. I'm trying to setup Distributed Mode of Airflow Using Celery Executor by Refering this article https://stlong0521.github.io/20161023%20-%20Airflow.html Before getting into detail about the specification I would like to confirm that I've installed PostgreSQL on a seperate instance. The specification of the setup is detailed below: Airflow core/server computer Python 3.5 airflow (AIRFLOW_HOME = ~/airflow) celery psycogp2 RabbitMQ Configurations made in airflow.cfg: sql_alchemy_conn = postgresql+psycopg2://username:password@192.168.2.12:5432/airflow executor = CeleryExecutor broker_url = amqp://username:password@192.168.1.12:5672// celery_result_backend = db+postgresql://username:password@192.168.2.12:5432/airflow Tests performed: RabbitMQ is running Can connect to PostgreSQL and have confirmed that Airflow has created tables Can start and view the webserver (including custom dags) Airflow worker computer Has the following installed: Python 3.5 with airflow (AIRFLOW_HOME = ~/airflow) celery psycogp2 Configurations made in airflow.cfg are exactly the same as in the server: sql_alchemy_conn = postgresql+psycopg2://username:password@192.168.2.12:5432/airflow executor = CeleryExecutor broker_url = amqp://username:password@192.168.1.12:5672// celery_result_backend = db+postgresql://username:password@192.168.2.12:5432/airflow Output from commands run on the worker machine: When running airflow flower: [2018-02-19 14:58:14,276] {__init__.py:57} INFO - Using executor CeleryExecutor [2018-02-19 14:58:14,360] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python3.5/lib2to3/Grammar.txt [2018-02-19 14:58:14,384] {driver.py:120} INFO - Generating grammar tables from /usr/lib/python3.5/lib2to3/PatternGrammar.txt [I 180219 14:58:15 command:139] Visit me at http://0.0.0.0:5555 [I 180219 14:58:15 command:144] Broker: amqp://username:password@192.168.1.12:5672// [I 180219 14:58:15 command:147] Registered tasks: ['celery.accumulate', 'celery.back…
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/50629425

http://stackoverflow.com/comment/84894141
type: Comment
score: 0
has text: which version of python are you using?
type: AnswerComment
comment on: http://stackoverflow.com/a/48943773

http://stackoverflow.com/a/48912308
upvote count: 2
score: 2
has body: It sounds like the software is trying to mix Gtk2 and Gtk3 which is not supported. I would contact the developers.
downvote count: 0
answers question: http://stackoverflow.com/q/48911135
type: Answer

http://stackoverflow.com/a/48948737
upvote count: 1
downvote count: 0
has body: Use cumcount for new indices created by set_index and then unstack: print (df) Serial No. Data One Data Two 0 01 0.258625 0.667996 1 01 0.192356 0.723055 2 02 0.738066 0.266488 3 02 0.374525 0.059664 4 03 0.193977 0.104213 5 03 0.213749 0.366608 49 05 0.948550 0.823888 df = df.set_index([df.groupby('Serial No.').cumcount(), 'Serial No.']).unstack() print (df) Data One Data Two \ Serial No. 01 02 03 05 01 02 0 0.258625 0.738066 0.193977 0.94855 0.667996 0.266488 1 0.192356 0.374525 0.213749 NaN 0.723055 0.059664 Serial No. 03 05 0 0.104213 0.823888 1 0.366608 NaN
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48948616
accepted answer of: http://stackoverflow.com/q/48948616
type: Answer
score: 1

http://stackoverflow.com/q/48841371
has comment: http://stackoverflow.com/comment/84690076
has comment: http://stackoverflow.com/comment/84688430
upvote count: 2
has comment: http://stackoverflow.com/comment/84687566
has comment: http://stackoverflow.com/comment/84688317
has comment: http://stackoverflow.com/comment/84687899
tagged with: utf-8
has comment: http://stackoverflow.com/comment/84690493
favorite count: 0
has comment: http://stackoverflow.com/comment/84687035
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84687280
type: UnansweredQuestion
tagged with: decoding
tagged with: python
has title: Python - Decode Text (German) from Hexadecimal Value and write it to a file
score: 2
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/84688715
has body: I know there are a lot of encoding/decoding topics here and I tried it for hours, but I'm still not able to solve it. Hence I want to raise a question: I have a string with hexadecimal values, which in the end is a text that I want to write to a text file with the correct encoding. hexvalues = "476572E2A47465646574656B746F72" In the end, the (german) result should be "Gerätedetektor" Currently I am using binascii.unhexlify() for the decoding, but it still doesn't show me the "ä" like its supposed to be, and instead, I get: &gt;&gt; result = binascii.unhexlify(hexvalues) Gerâ¤tedetektor I tried to do result.decode("utf-8") and a lot of other things but either the script crashes or it also doesn't return what I want to see. In the end, I want to write the word in the correct way to a file. Any help would be highly appreciated! Edit: As I wrote before, I tried many things so it is kind of hard to give the ONE code that I'm using but here is an excerpt from the current version: #!/usr/bin/env python # -*- coding: utf-8 -*- import binascii resultfile = "text_GER.txt" fpx = open(resultfile, 'wb') hexvalues = "476572E2A47465646574656B746F72" result= binascii.unhexlify(hexvalues ) result= result.decode("utf-8") print(result) fpx.write(result) This one makes the script crash, but no further indicators why it does. If i skip result= result.decode("utf-8") then my result print of result looks like this: b'Ger\xe2\xa4tedetektor'
type: Question
tagged with: encoding
has comment: http://stackoverflow.com/comment/84687707
has comment: http://stackoverflow.com/comment/84688522

http://stackoverflow.com/comment/84774170
comment on: http://stackoverflow.com/q/48884821
type: QuestionComment
type: Comment
has text: This is just an idea. But output 2 different cells. One filled with markdown and another filled with sagemath. In the markdown file have comments that are placeholders for sagemath results. parse the sagemath and insert them back into the placeholders.
score: 1

http://stackoverflow.com/q/48841854
tagged with: pandas
has comment: http://stackoverflow.com/comment/84687647
downvote count: 0
has title: pandas DataFrame pivot with sort
favorite count: 0
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48841903
has answer: http://stackoverflow.com/a/48841960
score: 4
has answer: http://stackoverflow.com/a/48841893
answer count: 3
has body: I'm having a problem presenting data in the required way. My dataframe is formatted and then sorted by 'Site ID'. I need to present the data by Site ID with all date instances grouped alongside. I'm 90% there in terms of how I want it to look using pivot_table df_pivot = pd.pivot_table(df, index=['Site Ref','Site Name', 'Date']) however the date column is not sorted. (The tiny example output appears sorted however the ****Thu Jan 11 2018 10:43:20 entry**** illustrates my issue on large data sets) I cannot figure out how to present it like below but also with the dates sorted per site ID Any help is gratefully accepted df = pd.DataFrame.from_dict([{'Site Ref': '1234567', 'Site Name': 'Building A', 'Date': 'Mon Jan 08 2018 10:43:20', 'Duration': 120}, {'Site Ref': '1245678', 'Site Name':'Building B', 'Date': 'Mon Jan 08 2018 10:43:20', 'Duration': 120}, {'Site Ref': '1245678', 'Site Name':'Building B', 'Date': 'Tue Jan 09 2018 10:43:20', 'Duration': 70}, {'Site Ref': '1245678', 'Site Name':'Building B', 'Date': 'Wed Jan 10 2018 10:43:20', 'Duration': 120}, {'Site Ref': '1212345', 'Site Name':'Building C', 'Date': 'Fri Jan 12 2018 10:43:20', 'Duration': 100}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Thu Jan 11 2018 10:43:20', 'Duration': 80}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Fri Jan 12 2018 12:22:20', 'Duration': 80}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Mon Jan 15 2018 11:43:20', 'Duration': 90}, {'Site Ref': '1123456', 'Site Name':'Building D', 'Date': 'Wed Jan 17 2018 10:43:20', 'Duration': 220}]) df = DataFrame(df, columns=['Site Ref', 'Site Name', 'Date', 'Duration']) df = df.sort_values(by=['Site Ref']) df Site Ref Site Name Date Duration 5 1123456 Building D Thu Jan 11 2018 10:43:20 80 6 1123456 Building D Fri Jan 12 2018 12:22:20 80 7 1123456 Building D Mon Jan 15 2018 11:43:20 90 8 1123456 Building D Wed Jan 17 2018 10:43:20 220 4 1212345 Building C Fri Jan 12 2018 10:43:20 100 0 1234567 Buildin…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84688835
upvote count: 4

http://stackoverflow.com/comment/84909634
score: 0
type: Comment
has text: @Jaffer, that is really weird. Don't get it why random would show different behaviors. Maybe you can try to run it on a different interpreter, I am using Python 3.6.4. I've made a notebook as well: https://github.com/joaoavf/misc/blob/master/stackoverflow/forecast.ipynb
comment on: http://stackoverflow.com/a/48886754
type: AnswerComment

http://stackoverflow.com/a/48899859
downvote count: 0
has comment: http://stackoverflow.com/comment/84846022
has comment: http://stackoverflow.com/comment/84845757
has comment: http://stackoverflow.com/comment/84888288
has comment: http://stackoverflow.com/comment/84883841
accepted answer of: http://stackoverflow.com/q/48898080
type: Answer
has body: It works when you declared 'option2' in the Optionmenu() widget. More examples can be read from here and here. from tkinter import * main = Tk() var = StringVar() options = OptionMenu(main, var, 'option1', 'option2') options.grid() #options['menu'].add_command(label='option2') main.mainloop() I found that the menu option is used for creating items in a Menu() widget but not for a Optionmenu() widget. This is stated here. You can read more about how to declare a .Menu() widget here. All the best to your tkinter developments. Edit1: The reason why it was failing was because you did not declare the command option associated with the .add_command method. Having done this alone, you will notice that the Optionmenu still does not get updated with the new label of the added menu item. To resolve this issue, you have to use the .set() method of the Control Variable StringVar to do the updating. See revised script below. from tkinter import * def _print1(value): # By default, callback to OptionMenu has a positional argument for the # menu item's label. print(value) print(var.get()) def _print2(): var.set('option2') print(var.get()) main = Tk() var = StringVar() options = OptionMenu(main, var, 'option1',command=_print1) options.grid() options['menu'].add_command(label='option2', command=_print2) # To add more clickable menu items, the 'add_command' method requires you to # to declare it's options 'label' and 'command'. main.mainloop() Edit2: Remark, I have added the command aspect to options in Edit1. I did not address earlier but thought it needed to be shown for completeness. Responding to your question in your UPDATE, to do what you want, I rewrote the script as a class object. Also I used the internal class _setit found in tkinter, which the OptionMenu widget had used to do configure the callback used by command. This approach overcame the issue you encountered. Revised Code: from tkinter import * class App(Tk): def __init__(self, parent=None): Tk.__init__(self, parent) s…
has comment: http://stackoverflow.com/comment/84932327
answers question: http://stackoverflow.com/q/48898080
upvote count: 2
has comment: http://stackoverflow.com/comment/84840832
score: 2
has comment: http://stackoverflow.com/comment/84878941
has comment: http://stackoverflow.com/comment/84945632
has comment: http://stackoverflow.com/comment/84884376
type: AcceptedAnswer

http://stackoverflow.com/q/48911094
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84870799
tagged with: python-packaging
tagged with: setuptools
tagged with: alpine-linux
has body: I have the following dockerfile: FROM python:alpine3.6 ENV PORT 5000 ENV APP /usr/src ENV FLASK_APP pkg_name/app.py RUN apk update RUN apk upgrade RUN apk add build-base postgresql-dev git gcc RUN apk add musl-dev python3-dev libffi-dev ADD . / RUN python setup.py install # RUN pip install . EXPOSE $PORT CMD flask run the configuration above work perfectly in standard python image but not in alpine image. Both python setup.py install or pip install . will install the package correctly but when I run flask run it complain that the installed module is not found: Traceback (most recent call last): File "pkg_name/app.py", line 6, in &lt;module&gt; from pkg_name.api import api ModuleNotFoundError: No module named 'pkg_name' Running pip freeze shows that the project in the list of installed packages. Trying to import the project in the python interpreter &gt;&gt;&gt; import pkg_name works also fine, which is weird. Question: Does any one has an explanation why the pkg could not be imported on run time despite it's installed and imported correctly in the interpeter. How can I fix it.
type: Question
accepted answer: http://stackoverflow.com/a/49010192
has comment: http://stackoverflow.com/comment/84870855
score: 4
tagged with: docker
upvote count: 4
has comment: http://stackoverflow.com/comment/84870590
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84881279
has title: python setup.py install doesn't work properly on alpine image
favorite count: 0
has comment: http://stackoverflow.com/comment/84878699
has answer: http://stackoverflow.com/a/49010192

http://stackoverflow.com/comment/84687686
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48841019
has text: In that link, [Capital "Dodoma"] is match on its own rather than an attribute under [Country "Tanzania"]\n` Also, please see my edits to the question to clarify the examples.
score: 0

http://stackoverflow.com/a/48889067
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48883070
accepted answer of: http://stackoverflow.com/q/48883070
has body: This done with Condition object. self.conditon = threading.Condition() For waiting to timeout or pulse, do: with service.conditon: service.conditon.wait(5) For notify: with self.conditon: self.conditon.notifyAll()

http://stackoverflow.com/q/48935408
score: -2
has answer: http://stackoverflow.com/a/48935497
duplicate of: http://stackoverflow.com/q/37980655
has title: Getting the following error for datetime
answer count: 2
downvote count: 3
upvote count: 1
has body: I have the following imports from datetime import datetime, timedelta dt = datetime.fromtimestamp(int(key)) dt_formatted = dt.strftime('%H:%M:%S') time_source.append(dt_formatted) start_time = time_source[0] t_end = start_time + datetime.timedelta(minutes=60) Getting this error, AttributeError: type object 'datetime.datetime' has no attribute 'timedelta'
favorite count: 0
tagged with: datetime
linked to: http://stackoverflow.com/q/37980655
tagged with: python
accepted answer: http://stackoverflow.com/a/48935516
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48935516
possible better answer: http://stackoverflow.com/a/48935497
type: Question
duplicate of: http://stackoverflow.com/q/47672643

http://stackoverflow.com/q/48825600
downvote count: 0
has comment: http://stackoverflow.com/comment/84655164
tagged with: postgresql
tagged with: pandas
upvote count: 1
has title: Unable to upload section of pandas dataframe using one psycopg2 sql query to postgresql
favorite count: 0
type: UnansweredQuestion
tagged with: python
tagged with: psycopg2
has comment: http://stackoverflow.com/comment/84655036
has comment: http://stackoverflow.com/comment/84685489
answer count: 0
has comment: http://stackoverflow.com/comment/84654882
score: 1
has comment: http://stackoverflow.com/comment/84655838
has body: I have a pandas dataframe that I wish to upload to a PostgreSQL 10.2 database. The dataframe looks as so: c1 c2 c3 c4 c5 c6 c7 c8 c9 text text integer integer integer integer integer text geog I am trying to upload the dataframe using psycopg2, in essence upload the first 8 columns (not spatial data) then upload the final column (spatial data), to the database using the following code: import pandas as pd import psycopg2 as ps d = {'c1':['a', 'b', 'c'], 'c2':['a', 'b', 'c'], 'c3':[0, 1, 2], 'c4':[0, 1, 2], 'c5':[0, 1, 2], 'c6':[0, 1, 2], 'c7':[0, 1, 2], 'c8':['aa|0', 'bb|1', 'cc|2'], 'c9':['87.579 36.798', '88.012 36.234', '87.007 36.009']} df = pd.DataFrame(data=d) conn_string = "host='localhost' dbname='postgis_24_sample' user='user' password='pwd'" conn = ps.connect(conn_string) cursor = conn.cursor() for i in range(len(self.df)): i = i + 1 upload1 = ('''INSERT INTO public."Table" ("c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8") VALUES ('"'{}'"', '"'{}'"', {}, {}, {}, {}, {}, '"'{}'"');''').format(self.df.iloc[0:i, 0:1], self.df.iloc[0:i, 1:2], self.df.iloc[0:i, 2:3], self.df.iloc[0:i, 3:4], self.df.iloc[0:i, 4:5], self.df.iloc[0:i, 5:6], sdf.iloc[0:i, 6:7], self.df.iloc[0:i, 7:8]) upload2 = ('''INSERT INTO public."Table" ("c9”) VALUES (ST_GeomFromText('POINT('"'{}'"')', 4326))).format(self.iloc[0:i, 8:9]) cursor.execute(upload1) cursor.execute(upload2) conn.commit() cursor.close() conn.close() However I have the following error: "ProgrammingError: syntax error at or near "c1" LINE 1: ...", "c7", "c8", "c9") VALUES ('"' c1" I am at a loss for what to do in order to move forward and any advice would be much appreciated.
type: Question
has comment: http://stackoverflow.com/comment/84657026

http://stackoverflow.com/a/48915148
accepted answer of: http://stackoverflow.com/q/48915075
has body: You could do: df[df['col1'].isin(list1) &amp; df['col2'].isin(list2)] This will return the rows of df where the value of col1 exists in list1 and the value of col2 exists in list2. &amp; is the bitwise AND operator, and will return True on the indices where both the operands are True.
answers question: http://stackoverflow.com/q/48915075
has comment: http://stackoverflow.com/comment/84836760
has comment: http://stackoverflow.com/comment/84837598
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84837555
has comment: http://stackoverflow.com/comment/84885351
type: Answer
has comment: http://stackoverflow.com/comment/84837214
has comment: http://stackoverflow.com/comment/84836957
has comment: http://stackoverflow.com/comment/84836738
upvote count: 3
score: 3

http://stackoverflow.com/q/48947923
type: Question
has body: I am working with an autoregressive model in Python using Statsmodels. The package is great and I am getting the exact results I need. However, testing for residual correlation (Breusch-Godfrey LM-test) doesn't seem to work, because I get an error message. My code: import pandas as pd import datetime import numpy as np from statsmodels.tsa.api import VAR import statsmodels.api as sm df = pd.read_csv('US_data.csv') # converting str formatted dates to datetime and setting the index j = [] for i in df['Date']: j.append(datetime.datetime.strptime(i, '%Y-%m-%d').date()) df['Date'] = j df = df.set_index('Date') # dataframe contains three columns (GDP, INV and CONS) # log difference df = pd.DataFrame(np.log(df)*100) df = df.diff() p = 4 # order model = VAR(df[1:]) results = model.fit(p, method='ols') sm.stats.diagnostic.acorr_breusch_godfrey(results) Error message: --------------------------------------------------------------------------- ValueError Traceback (most recent call last) &lt;ipython-input-6-11abf518baae&gt; in &lt;module&gt;() ----&gt; 1 sm.stats.diagnostic.acorr_breusch_godfrey(results) /home/****/anaconda3/lib/python3.6/site-packages/statsmodels/sandbox/stats/diagnostic.py in acorr_breusch_godfrey(results, nlags, store) 501 nlags = int(nlags) 502 --&gt; 503 x = np.concatenate((np.zeros(nlags), x)) 504 505 #xdiff = np.diff(x) ValueError: all the input arrays must have same number of dimensions A similar question was asked here over five months ago, but with no luck. Does anybody have an idea how to resolve this? Thank you very much in advance!
answer count: 1
accepted answer: http://stackoverflow.com/a/48956129
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/48956129
type: AnsweredQuestion
tagged with: statsmodels
has title: Statsmodels (Python): Breusch Godfrey Lagrange Multiplier tests
linked to: http://stackoverflow.com/q/46302347

http://stackoverflow.com/a/48892182
downvote count: 0
score: 1
has body: In your code, you assign values to a and b, these two variables have numbers in them, and are of type int. When you run text = (a)(b) You're essentially calling this: 1(2), which is invalid. I assume you want to output both of those to the text file so replace that statement with this: text = "({})({})".format(a, b)
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48892101
has comment: http://stackoverflow.com/comment/84789879

http://stackoverflow.com/q/48870673
tagged with: kivy
type: Question
has answer: http://stackoverflow.com/a/48872095
score: 0
answer count: 1
has title: Python KIVY: delete a tab
has body: I would like to delete a tab on a button press, using TabbedPanel widget. I have two tabs on my pannel, and I want to delete the second one so that the pannel has only one tab. from kivy.app import App from kivy.uix.tabbedpanel import TabbedPanel from kivy.lang import Builder Builder.load_string(""" &lt;Test&gt;: size_hint: .5, .5 pos_hint: {'center_x': .5, 'center_y': .5} do_default_tab: False TabbedPanelItem: text: 'first tab' Label: text: 'First tab content area' TabbedPanelItem: text: 'tab2' BoxLayout: Label: text: 'Second tab content area' Button: text: 'Button that deletes tab 2' background_color: (1, 0, 0, 1) """) class Test(TabbedPanel): pass class TabbedPanelApp(App): def build(self): return Test() if __name__ == '__main__': TabbedPanelApp().run()
type: UnansweredQuestion
tagged with: python

http://stackoverflow.com/a/72453270
type: Answer
answers question: http://stackoverflow.com/q/48919761
score: 0
has body: If the .so file exposes a PyInit_&lt;module_name&gt; function, its path (or parent directory's path) can be added to the environment variable PYTHONPATH. Then you can import the module via import &lt;module_name&gt;. Note: it looks like the name of the .so file must match the module name &lt;module_name&gt; that's exposed. More information here: https://docs.python.org/3/extending/building.html Adding this answer for reference.

http://stackoverflow.com/q/48944703
has comment: http://stackoverflow.com/comment/84896149
has answer: http://stackoverflow.com/a/48944961
upvote count: 2
tagged with: python-2.7
score: 0
downvote count: 2
tagged with: scons
answer count: 1
tagged with: macos
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84896342
has body: I have this code in a scons build file: with io.open(target[0].get_path(), 'w', encoding="utf-8") as target_file: target_file.write( unicode("std::string {} = R\"~~~~({})~~~~\";").format(varName,content)) The content variable will contain non-ascii characters. On OSX I don't have a problem, but on Linux I get a UnicodeDecodeError: 'ascii' codec can't decode byte error. Oddly, if I use just open instead, remove the encoding, and drop the unicode bit the reverse happens: it works on Linux and not on OSX. with open(target[0].get_path(), 'w') as target_file: target_file.write( "std::string {} = R\"~~~~({})~~~~\";".format(varName,content)) What is wrong and how do I fix it? Versions: OSX Python: 2.7.10 OSX Scons: 3.0.1 Linux Python: 2.7.12 Linux Scons: 2.4.1
has comment: http://stackoverflow.com/comment/84896222
type: Question
has title: Why does my `write` give UnicodeDecodeError on OSX but not Linux?

http://stackoverflow.com/q/48929486
has comment: http://stackoverflow.com/comment/84865497
tagged with: python
tagged with: merge
favorite count: 0
upvote count: 0
has body: Relatively new to Python. I have two csv files with two columns each, and I am trying to merge them and create one file. so, say, they are: Table1 enter image description here Table2 enter image description here I'm trying to write a code to merge the two tables into one, such that: A country is only entered twice if the description is different in both tables Table 1 is the master list, or table, and the code will check the description and and if the description in table1 is very close to table2, except for a few words or letters, then it will take that of table1. The country name should be entered for as many descriptions as are available in the two tables One of the problems I'm having is that the text in the description cannot be out in a dictionary. This is the code I have tried so far, and it did not work well: import csv file1 = open('dataset.csv', 'rb') file2 = open('dataset2.csv', 'rb') data_a = csv.reader(file1) data_b = dict(csv.reader(file2)) # &lt;-- dict file3 = open('out.csv', 'wb') csv_out = csv.writer(file3) for country, description in data_a: csv_out.writerow([country, description, data_b.get(country, '')])
has answer: http://stackoverflow.com/a/48930312
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84865728
type: Question
downvote count: 2
score: -2
answer count: 1
has title: merging two tables and correcting the strings in python

http://stackoverflow.com/a/48820201
upvote count: 2
has comment: http://stackoverflow.com/comment/117391505
has body: I came up with a very simple and non fancy code. I could just comment it but I still don't have enough reputation for that. Just convert your hour to minutes like this import time def time_to_min(hour, minute): return hour*60+minute timenow = time.localtime() open_time = time_to_min(9, 15) close_time = time_to_min(15, 30) current_time = time_to_min(timenow.tm_hour, timenow.tm_min) if current_time &gt;= open_time and current_time &lt;= close_time: print 'Store opened' else: print 'Store closed'
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48820057
score: 2

http://stackoverflow.com/q/48953418
type: UnansweredQuestion
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/84917559
has comment: http://stackoverflow.com/comment/84914243
has comment: http://stackoverflow.com/comment/84915666
has title: Python3 Tabulate issues with printing Asian characters
has comment: http://stackoverflow.com/comment/84914178
has comment: http://stackoverflow.com/comment/84913557
has comment: http://stackoverflow.com/comment/84915003
score: 0
has body: I am currently having an issue with Tabulate adding weird trailing space after during the printing of Asian characters, my code is as follows: def createFormatList(): n = 10 lists = [[] for _ in range(n)] return lists def formatMatchOutput(listsFormatter, listPlacement, name, rank, gamesPlayed, rankedWinrate): listsFormatter[listPlacement].append(name) listsFormatter[listPlacement].append(rank) listsFormatter[listPlacement].append(gamesPlayed) listsFormatter[listPlacement].append(rankedWinrate) return listsFormatter formatter = list() listsFormatter = createFormatList() for i in range(0, 5): name = str(currentMatchResponse['participants'][i]['summonerName']) print(repr(name)) responseData = requestSummonerData(region, name, APIKey) summID = str(responseData['id']) responseData2 = requestRankedData(region, summID, APIKey) if not responseData2: gamesPlayed = "-" rankedWinrate = "-" rank = "-" else: rank = (str(responseData2[0]['tier']) + " " + str(responseData2[0]['rank']) + " (" + str(responseData2[0]['leaguePoints']) + "LP)") summW = int(responseData2[0]['wins']) summL = int(responseData2[0]['losses']) gamesPlayed = summW + summL rankedWinrate = calculateWinrate(summW, summL) formatter = formatMatchOutput(listsFormatter, i, name, rank, gamesPlayed, rankedWinrate) for i in range(5, 10): name = str(currentMatchResponse['participants'][i]['summonerName']) responseData = requestSummonerData(region, name, APIKey) summID = str(responseData['id']) responseData2 = requestRankedData(region, summID, APIKey) if not responseData2: gamesPlayed = "-" rankedWinrate = "-" rank = "-" else: rank = (str(responseData2[0]['tier']) + " " + str(responseData2[0]['rank']) + " (" + str(responseData2[0]['leaguePoints']) + "LP)") summW = int(responseData2[0]['wins']) summL = int(responseData2[0]['losses']) gamesPlayed = summW + summL rankedWinrate = calculateWinrate(summW, summL) formatter = formatMatchOutput(listsFormatter, i, name, rank, gamesPlayed, rankedWinrate) print(colored(tabulate(for…
answer count: 0

http://stackoverflow.com/q/48863068
has answer: http://stackoverflow.com/a/48863259
tagged with: python
has comment: http://stackoverflow.com/comment/84729351
has title: Generate n sets of random numbers without a loop
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48863259
has body: so when I generate 1000 sets of random numbers (0..2000) in Python, I can easily do something like this: iters = 1000 randIdx = [] numbers = range(0, 2000) for i in range(iters): randIdx.append(random.sample(numbers, 8)) The problem is that the code is VERY slow. Is there a way to avoid the for loop to tell the function to just put out 1000 sets or is there some kind of workaround? I thought of just generating 8000 random numbers but the problem occurs that it is not possible to do that when in a set of 8 numbers duplicates aren't allowed! Example: randIdx=[] indexRange = range(0, 3) for i in range(5): randIdx.append(random.sample(indexRange, 2)) [[0, 1], [2, 1], [2, 0], [1, 0], [2, 1]]
has comment: http://stackoverflow.com/comment/84729464
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/47675003
duplicate of: http://stackoverflow.com/q/47675003
score: 0
tagged with: random
answer count: 1
tagged with: python-3.x

http://stackoverflow.com/comment/84768912
has text: `customuser.MyUser: (auth.E003) 'MyUser.username' must be unique because it is named as the 'USERNAME_FI ELD'.` This is the error i get
score: 1
comment on: http://stackoverflow.com/q/48881838
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48932820
type: Answer
downvote count: 1
score: 0
upvote count: 1
has body: Yes, min(queue) will find minimum in the list and not in the enclosed dictionary Do this: key_of_min_val = min(queue[0], key=queue[0].get) print((key_of_min_val , queue[0][key_of_min_val]))
answers question: http://stackoverflow.com/q/48932732

http://stackoverflow.com/comment/84863533
comment on: http://stackoverflow.com/a/48928441
type: Comment
score: 0
type: AnswerComment
has text: Yeah, 2nd option will suit you the best. Nice procedure will simplify implementation.

http://stackoverflow.com/q/48809312
has title: Python Tkinter - How to make a child frame with image inside a set width
has comment: http://stackoverflow.com/comment/84621982
tagged with: python-2.7
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48811041
has answer: http://stackoverflow.com/a/48811041
has comment: http://stackoverflow.com/comment/84625482
favorite count: 0
has comment: http://stackoverflow.com/comment/84622044
has answer: http://stackoverflow.com/a/48811065
type: Question
tagged with: python
score: -1
tagged with: tkinter
downvote count: 2
answer count: 2
upvote count: 1
accepted answer: http://stackoverflow.com/a/48811065
has body: I'm working on a program, which I'm building using python's tkinter gui library. My 2 Problems I'm trying to make a frame which will house a screenshot of the selected website. I have the frame and image created, but the frame is not anchoring to the right side of the window as expected. When the label element inside the frame has an image the frame is the expected length But, when the selected site does not have an image yet the frame is not stretching all the way to the right side of the window. Below is the portion of my code where I set up the image container/frame and respective image. self.frame_ImageContainer = Frame(self.tab_Details, width=320, height=180, bg='black', bd=2) self.frame_ImageContainer.grid(column=4, row=0, rowspan=11, columnspan=3, sticky=(N, S, E, W)) self.button_TakeScreenshot = Button(self.frame_ImageContainer, text='Take Screenshot', command=self.fn_RunScraper) self.button_TakeScreenshot.grid(column=1, row=5, sticky=(E, W)) self.widget_Image = Label(self.frame_ImageContainer, compound='top') self.widget_Image.grid(column=0, row=0, rowspan=12, columnspan=3, sticky=N) self.frame_ImageContainer.grid_columnconfigure(0, weight=1) self.frame_ImageContainer.grid_columnconfigure(1, weight=1) self.frame_ImageContainer.grid_columnconfigure(2, weight=1) self.frame_ImageContainer.grid_rowconfigure(0, weight=1) self.frame_ImageContainer.grid_rowconfigure(1, weight=1) self.frame_ImageContainer.grid_rowconfigure(2, weight=1) self.frame_ImageContainer.grid_rowconfigure(3, weight=1) self.frame_ImageContainer.grid_rowconfigure(4, weight=1) self.frame_ImageContainer.grid_rowconfigure(5, weight=1) self.frame_ImageContainer.grid_rowconfigure(6, weight=1) self.frame_ImageContainer.grid_rowconfigure(7, weight=1) self.frame_ImageContainer.grid_rowconfigure(8, weight=1) self.frame_ImageContainer.grid_rowconfigure(9, weight=1) self.frame_ImageContainer.grid_rowconfigure(10, weight=1) self.frame_ImageContainer.grid_rowconfigure(11, weight=1) The Take Screenshot butt…
has comment: http://stackoverflow.com/comment/84622015
has comment: http://stackoverflow.com/comment/84621892

http://stackoverflow.com/q/48873139
has answer: http://stackoverflow.com/a/48873198
upvote count: 0
answer count: 1
favorite count: 0
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/48873198
type: AnsweredQuestion
downvote count: 1
type: Question
has title: Attributes in django form model
score: -1
has body: hi i have django form model and i to want add my custom class for it but still i getting error: TypeError: init() got an unexpected keyword argument 'attrs' My django code: class ContactForm(forms.ModelForm): class Meta: model = ContactFormModel fields = ('name', 'email', 'phoneNumber', 'message',) widgets = { 'name': CharField(attrs={'class': 'myfieldclass'}), } Thanks for your helps.

http://stackoverflow.com/comment/85186954
comment on: http://stackoverflow.com/a/48896198
type: Comment
type: AnswerComment
score: 0
has text: Still no luck, I've now got a new error, 'TypeError: 'Series' object is not callable'

http://stackoverflow.com/q/48904453
has comment: http://stackoverflow.com/comment/84815587
accepted answer: http://stackoverflow.com/a/48980082
has title: Pytest - How to use one fixture for several conftest files issue
score: 2
type: AnsweredQuestion
tagged with: pytest
type: Question
has body: I have several pytest suites and each of them has almost the same conftest file. As the conftest files contain kind of duplicate code and as they might get bigger over time and the number of suites also may increase, I have decided to move the conftest fixtures to another module in a certain path and 'import' it using pytest_plugins variable to the conftest files. There is one issue. There is one fixture that depends on a local variable of the conftest files. How do I move the fixture to another another module and also force it to use the local variable of the conftest file? new_conftest_module.py var = 1 @pytest.fixture(scope="session", autouse=True) def session_init(): do_something(var) test_dir1/conftest.py pytest_plugins = ['new_conftest_module'] var = 2 test_dir2/conftest.py pytest_plugins = ['new_conftest_module'] var = 3 This is a dummy example, but as you can see the issue is that var variable is particular to every conftest file, but the fixture that uses it is the same. Is there a workaround I could use in order to have the fixture in a common module while using particular var value for every suite?
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48980082
favorite count: 0
tagged with: python-2.7
tagged with: python
upvote count: 2

http://stackoverflow.com/a/48852601
type: Answer
has body: You could do something like this: b = 982 with open("dna.csv") as f: c = f.read().replace("\n", "") items = [c[i: i+b] for i in range(0, len(c), b)] items will be a list of strings each of length b or, in your case, 982. Of course, this is assuming that the CSV is small enough to be fit into memory all at once.
has comment: http://stackoverflow.com/comment/84709344
has comment: http://stackoverflow.com/comment/84708905
has comment: http://stackoverflow.com/comment/84708877
score: 0
answers question: http://stackoverflow.com/q/48852382

http://stackoverflow.com/comment/84670937
type: Comment
has text: If you submit on the device web page with "PRES_VAL" empty does it work as it is supposed to? Also that response looks very suspicious. Are you sure this is the actual body of the response? Not sure what you mean by "unpack the response".
comment on: http://stackoverflow.com/q/48832856
score: 0
type: QuestionComment

http://stackoverflow.com/q/48824314
upvote count: 4
tagged with: lark-parser
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48835636
downvote count: 0
type: Question
tagged with: ebnf
score: 4
has body: I'm using lark, an excellent python parsing library. It provides an Earley and LALR(1) parser and is defined through a custom EBNF format. (EBNF stands for Extended Backus–Naur form). Lowercase definitions are rules, uppercase definitions are terminals. Lark also provides a weight for uppercase definitions to prioritize the matching. I'm trying to define a grammar but I'm stuck with a behavior I can't seem to balance. I have some rules with unnamed literals (the strings or characters between double-quotes): directives: directive+ directive: "@" NAME arguments ? directive_definition: description? "directive" "@" NAME arguments? "on" directive_locations directive_locations: "SCALAR" | "OBJECT" | "ENUM" arguments: "(" argument+ ")" argument: NAME ":" value union_type_definition: description? "union" NAME directives? union_member_types? union_member_types: "=" NAME ("|" NAME)* description: STRING | LONG_STRING STRING: /("(?!"").*?(?&lt;!\\)(\\\\)*?"|'(?!'').*?(?&lt;!\\)(\\\\)*?')/i LONG_STRING: /(""".*?(?&lt;!\\)(\\\\)*?"""|'''.*?(?&lt;!\\)(\\\\)*?''')/is NAME.2: /[_A-Za-z][_0-9A-Za-z]*/ It works well for 99% of use case. But if, in my parsed language, I use a directive which is called directive, everything breaks: union Foo @something(test: 42) = Bar | Baz # This works union Foo @directive(test: 42) = Bar | Baz # This fails Here, the directive string is matched on the unnamed literal in the directive_definition rule when it should match the NAME.2 terminal. How can I balance / adjust this so there is no ambiguity possible for the LALR(1) parser ?
answer count: 1
has title: How to balance rules and terminals in python lark parser?
favorite count: 0
tagged with: parsing
accepted answer: http://stackoverflow.com/a/48835636
tagged with: python

http://stackoverflow.com/q/48842293
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84688660
accepted answer: http://stackoverflow.com/a/48842891
favorite count: 0
tagged with: seaborn
has body: I am new to Pandas and Seaborn and trying to learn. I am trying to add a trend line and a bar plot on the same graph. I have some data that looks like Year Sample Size 2000 500 2001 3000 2003 10000 2004 20000 2004 23000 I am new to pandas and seaborn and I am attempting to draw a line through the bar plot showing a decreasing or an increasing trend but struggling to do it on the same graph. Till now, I have a bar plot. Below you can find the code. sampleSizes['Sample Size'] -> is the column I am plotting. It has about 12 values for 12 years. plt.figure() ax = sampleSizes['Sample Size'].plot(kind='bar', title="Trend of Sample Sizes", figsize=(15, 10), legend=True, color = 'grey', fontsize=8) plt.show() I am struggling to add a trend line to this. I would be grateful if someone could point me in the right direction. UPDATE FinancialYear Sample Size 2001 2338 2002 3171 2003 2597 2004 2740 2005 3447 2006 3098 2007 2610 2008 2819 2009 2057 2010 2174 2011 2709 enter code here
tagged with: python
has answer: http://stackoverflow.com/a/48842891
upvote count: 4
type: AnsweredQuestion
score: 3
has title: Making a regression line through a bar char using pandas or seaborn
has comment: http://stackoverflow.com/comment/84688831
type: Question
tagged with: trendline
tagged with: matplotlib
tagged with: pandas

http://stackoverflow.com/q/48828736
type: AnsweredQuestion
tagged with: apache-spark-sql
tagged with: pyspark
accepted answer: http://stackoverflow.com/a/48829184
tagged with: apache-spark
answer count: 1
downvote count: 0
favorite count: 0
has title: Counting by distinct sub-ArrayType elements in PySpark
tagged with: python
has answer: http://stackoverflow.com/a/48829184
score: 1
upvote count: 1
has body: I have a following JSON structure: { "stuff": 1, "some_str": "srt", list_of_stuff": [ {"element_x":1, "element_y":"22x"}, {"element_x":3, "element_y":"23x"} ] }, { "stuff": 2, "some_str": "srt2", "list_of_stuff": [ {"element_x":1, "element_y":"22x"}, {"element_x":4, "element_y":"24x"} ] }, When I read it into a PySpark DataFrame as json: import pyspark.sql import json from pyspark.sql import functions as F from pyspark.sql.types import * schema = StructType([ StructField("stuff", IntegerType()), StructField("some_str", StringType()), StructField("list_of_stuff", ArrayType( StructType([ StructField("element_x", IntegerType()), StructField("element_y", StringType()), ]) )) ]) df = spark.read.json("hdfs:///path/file.json/*", schema=schema) df.show() I get the following: +--------+---------+-------------------+ | stuff | some_str| list_of_stuff | +--------+---------+-------------------+ | 1 | srt | [1,22x], [3,23x] | | 2 | srt2 | [1,22x], [4,24x] | +--------+---------+-------------------+ Seems like PySpark flattens the key names for the ArrayType, although I can still see them when I do df.printSchema(): root |-- stuff: integer (nullable = true) |-- some_str: string (nullable = true) |-- list_of_stuff: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- element_x: integer (nullable = true) | | |-- element_y: string (nullable = true) Question: I need to count the distinct occurrences of element_y within my DataFrame. So given the example JSON, I would get this output: 22x: 2, 23x: 1, 24x :1 I am not sure how to get into the ArrayType and count the distinct values of the sub-element element_y. Any help appreciated.
type: Question

http://stackoverflow.com/q/48811690
accepted answer: http://stackoverflow.com/a/48870033
score: 0
tagged with: http://stackoverflow.com/tag/csv
tagged with: bulk
tagged with: elasticsearch
possible better answer: http://stackoverflow.com/a/54363978
has title: Loading CSV to elasticsearch index with mapping using Python API
has body: Using the elasticsearch Python API I want to create an elasticsearch index with a mapping so that when I upload a CSV file the documents are uploaded according to this mapping. import argparse, elasticsearch, json from elasticsearch import Elasticsearch from elasticsearch.helpers import bulk import csv I have this (I removed some fields so the mapping doesn't look that long): mapping = '''{ "mappings": { "type": { "properties": { "@timestamp": { "type": "date" }, "@version": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "authEndStopCode": { "type": "keyword" }, "expandedTripNumber": { "type": "integer" }, "operator": { "type": "integer" }, "path": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "startStopName": { "type": "keyword" }, "userStartStopCode": { "type": "keyword" } } } } }''' I'm creating the index this way: es.indices.create(index=INDEX_NAME, ignore=400, body=mapping) This is what I do to upload the data: with open(args.file, "r", encoding="latin-1") as f: reader = csv.DictReader(f) bulk(es, reader, index=INDEX_NAME, doc_type=TYPE) Where INDEX_NAME and TYPE are strings I already defined. The CSV file is just data (it should be one document per line), doesn't have headers, but elasticsearch seems like it's trying to use the first line as the headers. I don't want this, I want to use the mapping I already added to the index. Hope someone can help. Thank you.
tagged with: python
type: AnsweredQuestion
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48870033
has answer: http://stackoverflow.com/a/54363978

http://stackoverflow.com/comment/84865453
score: 0
type: QuestionComment
has text: @MrT Yes, I am actually trying to figure out if this information can be exploited to get the results, given that we know the number at the pick_index and the length of list
comment on: http://stackoverflow.com/q/48929281
type: Comment

http://stackoverflow.com/comment/85003269
has text: Wrong question?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48996475
type: AnswerComment

http://stackoverflow.com/comment/113082455
has text: how would I just get e4 and not '4'?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48953181
type: AnswerComment

http://stackoverflow.com/comment/84699199
has text: Nice, the filter idiom is useful here, will commit to memory.
type: Comment
score: 2
comment on: http://stackoverflow.com/a/48847567
type: AnswerComment

http://stackoverflow.com/comment/84764282
has text: @rici You are right, I have added a more meaningful example to my post. However, this solution is still very helpful `re.findall(r'((\w+?)\2+)', s)` finds all the repeated blocks, getting the one with more repetition is then a piece of cake.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48870891

svm
tags question: http://stackoverflow.com/q/48836945
tag name: svm
tags question: http://stackoverflow.com/q/48912695
tags question: http://stackoverflow.com/q/48928196
type: Tag
tags question: http://stackoverflow.com/q/48815919
tags question: http://stackoverflow.com/q/48899252
tags question: http://stackoverflow.com/q/48860258

http://stackoverflow.com/a/48891513
answers question: http://stackoverflow.com/q/48891436
has comment: http://stackoverflow.com/comment/84788468
upvote count: 2
has body: You can also just use the date value without overwriting the data you have: day = pd.to_datetime(df1['Date']).dt.date df1.groupby(['Hospital', day]).sum().reset_index().groupby('Hospital').mean() Hospital A 7.333333 Hospital B 9.500000 I'm guessing that the performance problem with Grouper is what you mention, generating a large amount of rows only to discard them later. However, there is a necessary performance impact in parsing the dates with to_datetime. You can try avoiding the parsing and simply slicing the string: day = df1['Date'].str.slice(0, 10) df1.groupby(['Hospital', day]).sum().reset_index().groupby('Hospital').mean() Hospital A 7.333333 Hospital B 9.500000 Seems slightly faster in my machine, although I don't know if that would still be the case with large datasets.
type: AcceptedAnswer
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48891436
downvote count: 0

http://stackoverflow.com/comment/85214928
has text: Thanks for the information. I(client) want to create an encrypted connection initially and then start communication with the server. So how do I establish that initial encrypted connection?
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48942704

http://stackoverflow.com/q/48929049
answer count: 3
tagged with: pandas
upvote count: 1
favorite count: 0
possible better answer: http://stackoverflow.com/a/48929238
has answer: http://stackoverflow.com/a/48929238
has title: line graph with pandas
tagged with: python
has answer: http://stackoverflow.com/a/48929783
type: AnsweredQuestion
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48929359
accepted answer: http://stackoverflow.com/a/48929359
type: Question
has body: I have following data state wise patents information for the year 2000 up to 2004 States;2000;2001;2002;2003;2004 state1;12302;11610;12297;13291;13491 state2;13010;14304;13599;13761;14398 state3;1242;1228;1099;1109;1016 state4;398;399;379;408;361 state5;164;198;143;158;185 state6;1185;1427;1166;955;1105 I am loading this data in to a DataFrame using pandas patents = pd.read_csv('Patent.csv', encoding='ANSI', sep=';', header=0, skiprows=0, names=['States','Year'], index_col=['States']) but I am not sure if I am doing it correctly because my data I have two headers. (States and Years) When I use to create a graph of this data using patents.plot(kind='line') It does not display the line graph of no. of patents between states and years: Thanks for your help

http://stackoverflow.com/a/48890352
downvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48890276
upvote count: 4
score: 3
has body: In python3, map returns an iterator, not list. You need to wrap the call to map() with the list constructor: pt1 = tuple(reversed(list(map(int, pt1)))) See more: Getting a map() to return a list in Python 3.x

http://stackoverflow.com/comment/84740381
comment on: http://stackoverflow.com/a/48840610
score: 0
type: AnswerComment
has text: Muller ,Any solution to this.
type: Comment

http://stackoverflow.com/q/48833850
score: 3
tagged with: matplotlib
has body: I want to reproduce this image using matplotlib. The example docs have a numpy logo, but all the voxel cubes are homogenous in color. I could imagine perhaps making a separate surface plot for each face I want to change but that seems impractical. Here's the code for the example docs numpy logo: import matplotlib.pyplot as plt import numpy as np from mpl_toolkits.mplot3d import Axes3D def explode(data): size = np.array(data.shape)*2 data_e = np.zeros(size - 1, dtype=data.dtype) data_e[::2, ::2, ::2] = data return data_e # build up the numpy logo n_voxels = np.zeros((4, 3, 4), dtype=bool) n_voxels[0, 0, :] = True n_voxels[-1, 0, :] = True n_voxels[1, 0, 2] = True n_voxels[2, 0, 1] = True facecolors = np.where(n_voxels, '#FFD65DC0', '#7A88CCC0') edgecolors = np.where(n_voxels, '#BFAB6E', '#7D84A6') filled = np.ones(n_voxels.shape) # upscale the above voxel image, leaving gaps filled_2 = explode(filled) fcolors_2 = explode(facecolors) ecolors_2 = explode(edgecolors) # Shrink the gaps x, y, z = np.indices(np.array(filled_2.shape) + 1).astype(float) // 2 x[0::2, :, :] += 0.05 y[:, 0::2, :] += 0.05 z[:, :, 0::2] += 0.05 x[1::2, :, :] += 0.95 y[:, 1::2, :] += 0.95 z[:, :, 1::2] += 0.95 fig = plt.figure() ax = fig.gca(projection='3d') ax.voxels(x, y, z, filled_2, facecolors=fcolors_2, edgecolors=ecolors_2) plt.show()
type: Question
has comment: http://stackoverflow.com/comment/84711353
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84676918
favorite count: 0
has answer: http://stackoverflow.com/a/49055142
has title: matplotlib: changing a single voxel face color
tagged with: python
accepted answer: http://stackoverflow.com/a/49055142
has comment: http://stackoverflow.com/comment/84711470
upvote count: 3
has comment: http://stackoverflow.com/comment/84672108
type: AnsweredQuestion

http://stackoverflow.com/comment/84673571
comment on: http://stackoverflow.com/q/48833908
has text: When it comes to Tkinter do not use `sleep`. The `after` method is what you would use here. This goes for anything that requires a timed delay in tkinter.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48909885
type: Question
tagged with: django-filebrowser
has comment: http://stackoverflow.com/comment/84826153
has comment: http://stackoverflow.com/comment/84825870
has title: ImportError: No module named 'filebrowser'
has answer: http://stackoverflow.com/a/48910427
has comment: http://stackoverflow.com/comment/84825875
score: 0
answer count: 1
has body: I have just installed django-filebrowser on my django site hosted on pythonanywhere and using python 3.5 and django 1.11.7. I followed the instructions in the docs to set it up. The apps are installed in settings.py, and I have used manage.py collecstatic to collect those files in the currect location (I am using whitenoise to serve static files through an Amazon CDN). My urls.py declarations are as follows: url(r'^filebrowser/', include('filebrowser.urls')), url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', admin.site.urls), I also used site.urls, but was informed that 'site' is undefined. The error I receive on the present settings is: ImportError: No module named 'filebrowser.urls' Edit: I should also note that if I change the urls to 'app.urls' instead of 'filebrowser.urls' that site loads generally, but the page on which I attempt to load filebrowser (a form for submitting blog posts), presents this error: NoReverseMatch: 'filebrowser' is not a registered namespace
has comment: http://stackoverflow.com/comment/84826041
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84826369
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48910427

http://stackoverflow.com/q/48959947
tagged with: python
tagged with: jupyter-notebook
score: 1
upvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48971287
type: Question
answer count: 3
has title: TensorFlow variable reuse error in Jupyter notebook
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48965274
has answer: http://stackoverflow.com/a/50441648
has body: I'm trying to run the following code from a Kaggle tutorial on my machine (Windows 10 Home v.1709 build 16299.248, Python 3.6.3, JupyterLab 0.31.8): from keras.models import Sequential from keras.layers import Dense, Flatten, GlobalAveragePooling2D from keras.applications import ResNet50 num_classes = 2 resnet_weights_path = '../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5' my_new_model = Sequential() my_new_model.add(ResNet50(include_top=False, pooling='avg', weights=resnet_weights_path)) my_new_model.add(Dense(num_classes, activation='softmax')) and I'm getting the following error: ValueError Traceback (most recent call last) &lt;ipython-input-2-7f139a1e52fa&gt; in &lt;module&gt;() 7 8 my_new_model = Sequential() ----&gt; 9 my_new_model.add(ResNet50(include_top=False, pooling='avg', weights=resnet_weights_path)) 10 my_new_model.add(Dense(num_classes, activation='softmax')) ~\Anaconda3\lib\site-packages\keras\models.py in add(self, layer) 465 # and create the node connecting the current layer 466 # to the input layer we just created. --&gt; 467 layer(x) 468 469 if len(layer._inbound_nodes[-1].output_tensors) != 1: ~\Anaconda3\lib\site-packages\keras\engine\topology.py in __call__(self, inputs, **kwargs) 615 616 # Actually call the layer, collecting output(s), mask(s), and shape(s). --&gt; 617 output = self.call(inputs, **kwargs) 618 output_mask = self.compute_mask(inputs, previous_mask) 619 ~\Anaconda3\lib\site-packages\keras\engine\topology.py in call(self, inputs, mask) 2076 return self._output_tensor_cache[cache_key] 2077 else: -&gt; 2078 output_tensors, _, _ = self.run_internal_graph(inputs, masks) 2079 return output_tensors 2080 ~\Anaconda3\lib\site-packages\keras\engine\topology.py in run_internal_graph(self, inputs, masks) 2227 if 'mask' not in kwargs: 2228 kwargs['mask'] = computed_mask -&gt; 2229 output_tensors = _to_list(layer.call(computed_tensor, **kwargs)) 2230 output_masks = _to_list(layer.compute_mask(computed_tensor, 2231 comp…
type: UnansweredQuestion

http://stackoverflow.com/comment/84918779
comment on: http://stackoverflow.com/q/48955901
type: Comment
has text: I have a follow-up, see my edit.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84767154
has text: I mean, you can just break the line with `\\`... it's a trivial question ;)
comment on: http://stackoverflow.com/q/48881530
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/a/48916686
accepted answer of: http://stackoverflow.com/q/48916514
has comment: http://stackoverflow.com/comment/84876347
has comment: http://stackoverflow.com/comment/84868308
has comment: http://stackoverflow.com/comment/84868899
upvote count: 1
has body: This is how you could use BeautifulSoup to replace the href attribute. from bs4 import BeautifulSoup import time data = r'data.html' #html file location #load the file current_time = time.strftime("_%m%d%Y") with open(data) as inf: txt = inf.read() soup = BeautifulSoup(txt, 'html.parser') a = soup.find('a') a['href'] = ("WillCounty_AddressPoint%s.zip" % current_time) print (soup) #save the file again with open (data, "w") as outf: outf.write(str(soup)) Outputs: Address Points (updated weekly) And writes to the file UPDATED to use data from supplied file. from bs4 import BeautifulSoup import time data = r'data.html' #html file location #load the file current_time = time.strftime("_%m%d%Y") with open(data) as inf: txt = inf.read() soup = BeautifulSoup(txt, 'html.parser') # Find the a element you want to change by finding it's text and selecting parent. a = soup.find(text="Address Points").parent a['href'] = ("WillCounty_AddressPoint%s.zip" % current_time) print (soup) #save the file again with open (data, "w") as outf: outf.write(str(soup)) It will however, take out blank lines but otherwise leave your HTML code exactly as it was. Using a diff tool to see differences in the original and modified files: diff data\ \(copy\).html data.html 77c77 < Address Points (updated weekly) --- > Address Points (updated weekly) 116,120d115 < < < < < 154d148 <
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84868494
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48916514

http://stackoverflow.com/a/48935804
downvote count: 0
has body: Use data = ctypes.py_object(foo). ctypes.py_object represents the PyObject * type in C.
accepted answer of: http://stackoverflow.com/q/48935590
score: 5
answers question: http://stackoverflow.com/q/48935590
type: AcceptedAnswer
upvote count: 5
type: Answer

http://stackoverflow.com/comment/84954579
has text: Then your locator is not correct. Please refer to my comment on the below answer where I give you two xpaths to try.
comment on: http://stackoverflow.com/a/48969382
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84643407
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48819053
score: 0
has text: Hope this SO Answer would help you to solve the issue, https://stackoverflow.com/questions/38390177/what-is-a-noreversematch-error-and-how-do-i-fix-it

http://stackoverflow.com/a/48877215
downvote count: 0
type: Answer
upvote count: 1
has body: Having a link to actual data would be helpful, but I can make a few recommendations without the data. First, converting x to np.log(x) is so easy that it is probably worth the effort. Second, the definition for Gaussian doesn't normally include 1./x -- it might be a small effect, but your values of x are changing by an order of magnitude, so maybe not. Third, you're providing the same starting value for mu for all three Gaussians. This makes the fit much harder. Try to give starting points that are closer to the actual expected values, and if possible bounds on those values. To help address these points, you might find lmfit (https://lmfit.github.io/lmfit-py/) helpful. It will definitely make your script shorter, perhaps something like import numpy as np import matplotlib.pyplot as plt from lmfit.models import GaussianModel y, bin_edges = np.histogram(Density, bins=np.logspace(np.log10(MIN), np.log10(MAX), 32)) x = np.log((bin_edges[:-1] + bin_edges[1:])/2.0) #take log here # build a model as a sum of 3 Gaussians model = (GaussianModel(prefix='g1_') + GaussianModel(prefix='g2_') + GaussianModel(prefix='g3_')) # build Parameters with initial values params = model.make_params(g1_amplitude=60, g1_center=-1.0, g1_sigma=1, g2_amplitude=30, g2_center= 0.0, g1_sigma=1, g2_amplitude=10, g2_center= 1.0, g1_sigma=1) # optionally, set bound / constraints on Parameters: params['g1_center'].max = 0 params['g2_center'].min = -1.0 params['g2_center'].max = 1.0 params['g3_center'].min = 0 # perform the actual fit result = model.fit(y, params, x=x) # print fit statistics and values and uncertainties for variables print(result.fit_report()) # evaluate the model components ('g1_', 'g2_', and 'g3_') comps = result.eval_components(result.params, x=x) # plot the results plt.plot(x, y, label='data') plt.plot(x, result.best_fit, label='best fit') plt.plot(x, comps['g1_'], label='gaussian1') plt.plot(x, comps['g2_'], label='gaussian2') plt.plot(x, comps['g3_'], label='gaussian3') # other pl…
score: 1
has comment: http://stackoverflow.com/comment/84775848
answers question: http://stackoverflow.com/q/48874733
has comment: http://stackoverflow.com/comment/84794432
has comment: http://stackoverflow.com/comment/84771682

http://stackoverflow.com/q/48903434
has comment: http://stackoverflow.com/comment/84812317
has title: Collapse Python list, keeping unique columns and highest value
tagged with: python
accepted answer: http://stackoverflow.com/a/48903630
tagged with: list
has answer: http://stackoverflow.com/a/48904810
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/48903741
downvote count: 1
has answer: http://stackoverflow.com/a/48903630
type: Question
type: AnsweredQuestion
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84812705
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/84812466
possible better answer: http://stackoverflow.com/a/48903741
has body: I have a list of lists data = [ ['fruit', 'apple', 'v1', 'data 1'], ['fruit', 'apple', 'v2', 'data 2'], ['fruit', 'apple', 'v3', 'data 3'], ['fruit', 'banana', 'v1', 'data 4'], ['fruit', 'banana', 'v2', 'data 5'], ['animal', 'dog', 'v1', 'data 6'] ] How can I collapse based on the first 2 column and using the data from the highest v ? result = [ ['fruit', 'apple', 'v3', 'data 3'], ['fruit', 'banana', 'v2', 'data 5'], ['animal', 'dog', 'v1', 'data 6'] ] The list was sorted in the first column, but second column is not. My solution was based on assumption that both column were sorted so it does not work and I have no idea where to go from here. previous = [] result = [] for a, b, c, d in data: if not all(x in previous for x in [a, b]): final.append([a, b, c, d]) previous = [a, b, c, d] else: if previous[2] &lt; c: final[-1][2] = c final[-1][3] = d previous = [a, b, c, d] print result
favorite count: 0

http://stackoverflow.com/a/48958685
has body: This is as expected as lst[0:-1] selects everything from the first element, up to one before the last element: lst[0:-1] &gt;&gt;&gt; [2]
type: Answer
answers question: http://stackoverflow.com/q/48958658
upvote count: 1
downvote count: 1
score: 0

http://stackoverflow.com/comment/84828932
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48911166
type: Comment
has text: Possible duplicate of [django.db.utils.IntegrityError: (1062, "Duplicate entry '' for key 'slug'")](https://stackoverflow.com/questions/32383766/django-db-utils-integrityerror-1062-duplicate-entry-for-key-slug)

http://stackoverflow.com/q/48819506
upvote count: 3
duplicate of: http://stackoverflow.com/q/11264521
downvote count: 1
accepted answer: http://stackoverflow.com/a/48819551
favorite count: 0
has body: I've got a matplotlib plot which I'm creating with the following code: # Plot times for completion print "Plotting Completion Times" plt.plot(x, y) plt.title("Completion Times") plt.xlabel("Times (In Seconds)") plt.xticks(x, x) plt.ylabel("Percentage of completion") plt.show() The plot comes out correctly, but the xticks which I have set on the x-axis end up overlapping and now I can't read them properly. The resultant x-axis ticks look like this: You can see that there are five marked points, but I don't know what any of their full values are. Is there a way I can make the values display at an angle so that they are all fully visible?
tagged with: python
has answer: http://stackoverflow.com/a/48819551
linked to: http://stackoverflow.com/q/11264521
score: 2
type: AnsweredQuestion
tagged with: matplotlib
type: Question
has title: How to make x-ticks more visible?
answer count: 1

http://stackoverflow.com/comment/84884394
type: Comment
comment on: http://stackoverflow.com/a/48935639
type: AnswerComment
score: 0
has text: Thanks for your solution. Yes, it is simple, but I wanted to think in different ways.

http://stackoverflow.com/a/48876980
has comment: http://stackoverflow.com/comment/84759072
score: 3
downvote count: 0
has body: itertools.cycle + itertools.islice Efficient cycling and iteration — no copies were harmed in the process of writing this solution. from itertools import cycle, islice l = list(range(9)) repeats = 8 [list(islice(cycle(l), i, len(l) + i)) for i in range(repeats)] [[0, 1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8, 0], [2, 3, 4, 5, 6, 7, 8, 0, 1], [3, 4, 5, 6, 7, 8, 0, 1, 2], [4, 5, 6, 7, 8, 0, 1, 2, 3], [5, 6, 7, 8, 0, 1, 2, 3, 4], [6, 7, 8, 0, 1, 2, 3, 4, 5], [7, 8, 0, 1, 2, 3, 4, 5, 6]] Or, if you don't want to preserve the indices: for i in range(repeats): idx = list(islice(cycle(l), i, len(l) + i)) ... # do something with idx List Comprehension The choice of users looking for performance. [l[i:] + l[:i] for i in range(repeats)] [[0, 1, 2, 3, 4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7, 8, 0], [2, 3, 4, 5, 6, 7, 8, 0, 1], [3, 4, 5, 6, 7, 8, 0, 1, 2], [4, 5, 6, 7, 8, 0, 1, 2, 3], [5, 6, 7, 8, 0, 1, 2, 3, 4], [6, 7, 8, 0, 1, 2, 3, 4, 5], [7, 8, 0, 1, 2, 3, 4, 5, 6]]
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/48876888
has comment: http://stackoverflow.com/comment/84759100

http://stackoverflow.com/comment/84630119
has text: I edited to remove the ambiguity caused by having a problem caused by a VM on the *host OS*. I think that might be the reason for a downvote.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48812979
score: 0

http://stackoverflow.com/q/48818676
possible better answer: http://stackoverflow.com/a/48818705
has answer: http://stackoverflow.com/a/48818705
answer count: 2
upvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84641237
accepted answer: http://stackoverflow.com/a/48818746
tagged with: python
type: AnsweredQuestion
tagged with: syntax
downvote count: 2
type: Question
has title: python syntax error on line 64 (really new to this)
has comment: http://stackoverflow.com/comment/84641259
has comment: http://stackoverflow.com/comment/84641257
has body: So I'm really new to python and coding in general but I'm trying to make a program that calculates the processing power and power usage of a computer based on each part and its specifications. However, i keep getting this message. Traceback (most recent call last): File "python", line 64 drive() ^ SyntaxError: invalid syntax I just don't get it. What is wrong with my code? I know it's trash but I'm new and still learning. It's probably a super simple thing. Any way here's the code: def start(): print("* Welcome to Spicy's Processing Power / TDP Calculator! (SPPTDPC) *") print("* Version 0.0.5 *") print("** This program is still in alpha stage and isn't perfect **") print("If you are unsure about one of the questions, look up the specs of the part on a website like PCPartPicker or TechPowerUP") cpu() def cpu(): global r global cpus global cputdp name = input("What is the name of your processor?") c = float(input("How many cores does the "+name+" have?")) t = float(input("How many threads does the "+name+" have?")) l1 = float(input("How much L1 cache (in total) does the "+name+" have in KB?")) l2 = float(input("How much L2 cache (in total) does the "+name+" have in MB?")) l3 = float(input("How much L3 cache (in total) does the "+name+" have in MB?")) g = float(input("What is the clock speed (in GHz) of the "+name+"?")) n = float(input("What is the fabrication process of the "+name+" in nm?")) r = float(input("What type of RAM does the "+name+" use? Enter 3 for DDR3, 4 for DDR4, etc.")) cputdp = float(input("What is the TDP of the "+name+"?")) cpus = (c+t+g+r+l2+(l1/100)+(.3*l3))/n #CPU Processing Power Formula print("** The "+name+" has a score of "+str(cpus)+". **") ram() def ram(): global rtdp global rams g = float(input("How much RAM does your system have (in GB?)")) m = float(input("What is the speed of your slowest installed DIMM? (in MHz)")) rtdp = float(input("How many DIMMs do you have installed?")) rtdp = rtdp*4 rams = ((r+(m/500))*g)/150 #RAM Processing Powe…
score: -2
has answer: http://stackoverflow.com/a/48818746

http://stackoverflow.com/a/48937818
accepted answer of: http://stackoverflow.com/q/48937769
type: Answer
has comment: http://stackoverflow.com/comment/84882774
has comment: http://stackoverflow.com/comment/84882643
has comment: http://stackoverflow.com/comment/84882661
score: 0
answers question: http://stackoverflow.com/q/48937769
has body: def main(): menu() t=choice() if t==1: option1() elif t==2: option2() elif t==3: option3() elif t==4: option4() else: option5() main() Revised code.
type: AcceptedAnswer

http://stackoverflow.com/comment/84779110
has text: you sir are my guru, could you explain what the .mask does in this instance? works perfectly! could you also explain if I could use a for loop with multiple column names? (I assume this would make the code cleaner)?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48886918
type: Comment

http://stackoverflow.com/comment/84612847
comment on: http://stackoverflow.com/q/48805035
type: Comment
type: QuestionComment
has text: are there only `1`s and `0`s in the original list?
score: 2

http://stackoverflow.com/comment/84875987
comment on: http://stackoverflow.com/a/48932552
has text: Try printing the data frame after read_csv - likely it's some problem with reading in the headers correctly. Actually after looking at it I bet it's creating three columns, one with name 'Average', another 'Snow', another 'Fall'. Take out the spaces and try it again
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/91905464
comment on: http://stackoverflow.com/a/52346280
type: Comment
score: 0
has text: Didn't work. Instead first downloading the zip using wget and then unzipping it worked.
type: AnswerComment

http://stackoverflow.com/a/48891811
has body: Your parse() method always makes the exact same request to the same url, and parse_mag() gets called with the response. So it's not that parse_mag() is called multiple times for a single POST request, it is called once per request, with the same arguments, returning the same result. Using https://doc.scrapy.org/en/latest/topics/downloader-middleware.html#std:reqmeta-cookiejar def start_requests(self): # full path with open('file.csv') as csvfile: reader = csv.DictReader(csvfile) for i, row in enumerate(reader): # check empty value magasin_id = row['Id'] if row['Id'][0] == '0': magasin_id = row['Id'][1:] formdata = {'city' : row['City'], 'market' : row['Brand'], 'idPdv' : magasin_id} #print(row['City'], row['Brand'], row['Id']) yield scrapy.FormRequest(url='http://www.bricomarche.com/bma_popin/Geolocalisation/choisirMagasin', formdata=formdata, dont_filter=True, callback=self.parse, meta={'cookiejar': i}) def parse(self, response): yield scrapy.Request('http://www.bricomarche.com/l/nos-produits/jardin/abri-garage-carport-et-rangement/abri-de-jardin/les-abris-bois-1121.html?limit=90', dont_filter=True, callback=self.parse_mag, meta={'cookiejar': response.meta['cookiejar']})
type: Answer
accepted answer of: http://stackoverflow.com/q/48891574
answers question: http://stackoverflow.com/q/48891574
upvote count: 1
type: AcceptedAnswer
downvote count: 0
score: 1

http://stackoverflow.com/a/48841903
downvote count: 0
score: 3
upvote count: 3
has comment: http://stackoverflow.com/comment/84687841
type: Answer
answers question: http://stackoverflow.com/q/48841854
has body: It's sorted lexicographically, because Date has object (string) dtype Workaround - add a new column of datetime dtype, use it before Date in the pivot_table and drop it afterwards: In [74]: (df.assign(x=pd.to_datetime(df['Date'])) .pivot_table(df, index=['Site Ref','Site Name', 'x', 'Date']) .reset_index(level='x', drop=True)) Out[74]: Duration Site Ref Site Name Date 1123456 Building D Thu Jan 11 2018 10:43:20 80 Fri Jan 12 2018 12:22:20 80 Mon Jan 15 2018 11:43:20 90 Wed Jan 17 2018 10:43:20 220 1212345 Building C Fri Jan 12 2018 10:43:20 100 1234567 Building A Mon Jan 08 2018 10:43:20 120 1245678 Building B Mon Jan 08 2018 10:43:20 120 Tue Jan 09 2018 10:43:20 70 Wed Jan 10 2018 10:43:20 120

http://stackoverflow.com/comment/103057920
score: 0
type: AnswerComment
has text: why `apply_async().get` is little faster than `apply()`? `[pool.apply(os.getpid, ()) for i in range(4)]` uses the same process number.
type: Comment
comment on: http://stackoverflow.com/a/48807949

http://stackoverflow.com/comment/84752505
score: 0
type: AnswerComment
type: Comment
has text: This is actually somewhat helpful, as it would allow me to implement attempt 2 correctly in the general case. E.g. `def substitute_match(match, orig, template): return orig[:match.start()] + match.expand(template) + orig[match.end():]`. I won't be adding another capture group for the non-matched string (this has nontrivial implications in connection with `regex.match(..., pos=n)`).
comment on: http://stackoverflow.com/a/48874126

http://stackoverflow.com/q/48888513
has comment: http://stackoverflow.com/comment/84929580
tagged with: python
has comment: http://stackoverflow.com/comment/84810698
has comment: http://stackoverflow.com/comment/84929067
score: 0
has comment: http://stackoverflow.com/comment/84930679
has comment: http://stackoverflow.com/comment/84929429
answer count: 1
has answer: http://stackoverflow.com/a/51360125
has comment: http://stackoverflow.com/comment/84988353
has comment: http://stackoverflow.com/comment/84929541
has body: I have some data containing spelling errors. I'm correcting them and scoring how close the spelling is using the following code: import pandas as pd import difflib Li_A = ["potato", "tomato", "squash", "apple", "pear"] Q = {'one' : pd.Series(["potat0", "toma3o", "s5uash", "ap8le", "pea7"], index=['a', 'b', 'c', 'd', 'e']), 'two' : pd.Series(["po1ato", "2omato", "squ0sh", "2pple", "p3ar"], index=['a', 'b', 'c', 'd', 'e'])} df_Q = pd.DataFrame(Q) # Define the function that Corrects &amp; Scores the Spelling def Spelling(ask): a = difflib.get_close_matches(ask, Li_A, n=5, cutoff=0.1) # List comprehension for all values of a b = [difflib.SequenceMatcher(None, ask, x).ratio() for x in a] return pd.Series(a + b) # Apply the function that Corrects &amp; Scores the Spelling df_A = df_Q['one'].apply(Spelling) # Get the column names on the A dataframe c = len(df_A.columns) // 2 df_A.columns = ['Spelling_{}'.format(x) for x in range(c)] + \ ['Score_{}'.format(y) for y in range(c)] # Join the Q &amp; A dataframes df_QA = df_Q.join(df_A) This gives the result: df_QA one two Spelling_0 Spelling_1 Spelling_2 Spelling_3 Spelling_4 \ a potat0 po1ato potato tomato pear apple squash b toma3o 2omato tomato potato pear apple squash c s5uash squ0sh squash pear apple tomato potato d ap8le 2pple apple pear tomato squash potato e pea7 p3ar pear potato apple tomato squash Score_0 Score_1 Score_2 Score_3 Score_4 a 0.833333 0.500000 0.400000 0.181818 0.166667 b 0.833333 0.333333 0.200000 0.181818 0.166667 c 0.833333 0.200000 0.181818 0.166667 0.166667 d 0.800000 0.222222 0.181818 0.181818 0.181818 e 0.750000 0.400000 0.444444 0.200000 0.200000 For row "e", "potato" is in row 1 and "apple" in row 2. However, apple got a higher score than potato. This is the wrong way round for my application. How do I get the higher scoring results the be consistently to the left please? Edit 1: I tried a simpler code: import difflib Li_A = ["potato", "tomato", "squash", "apple", "pear"] Q = "pea7" A = difflib.…
has title: Multiple Spelling Results in a Dataframe 1
tagged with: spelling
has comment: http://stackoverflow.com/comment/84929663
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84988414
has comment: http://stackoverflow.com/comment/84929526
has comment: http://stackoverflow.com/comment/86892561
type: AnsweredQuestion
tagged with: difflib
has comment: http://stackoverflow.com/comment/84988088
has comment: http://stackoverflow.com/comment/85057909
accepted answer: http://stackoverflow.com/a/51360125
has comment: http://stackoverflow.com/comment/84786253
tagged with: fuzzywuzzy
has comment: http://stackoverflow.com/comment/84809477
has comment: http://stackoverflow.com/comment/84929561
type: Question

http://stackoverflow.com/comment/84830212
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48891486
type: Comment
has text: I'd suggest returning `None` from `get_credentials` instead of the redirect, then putting the code in your if statement into the view.

http://stackoverflow.com/comment/84883867
type: AnswerComment
has text: Nice dude :-) !
comment on: http://stackoverflow.com/a/48938322
type: Comment
score: 1

http://stackoverflow.com/comment/84882106
has text: @roganjosh https://stackoverflow.com/a/1609688/607846
type: QuestionComment
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48937336

http://stackoverflow.com/a/48956472
type: AcceptedAnswer
score: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48955901
answers question: http://stackoverflow.com/q/48955901
has body: Add plt.figure(figsize=[14,10]) # set image size plt.subplots_adjust(wspace = 0.5)# set distance between the subplots before your for loop. You might have to play with the numbers to get the best look.

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

http://stackoverflow.com/comment/84819284
score: 1
has text: I think you are misunderstanding grid search. Grid search applies to hyperparameters, which aren't directly learned from the models. Linear regression models don't have hyperparameters, though in the case of sklearn, it would be the parameters in the class constructor, (e.g. `fit_intercept`, `normalize`). If you want to leave a variable out in your modeling, then you would remove the variable column out of your dataset.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48906534

http://stackoverflow.com/comment/84758495
comment on: http://stackoverflow.com/q/48877207
score: 1
type: Comment
type: QuestionComment
has text: Have you made any attempt whatsoever? Given the information you provide, it is extremely unclear how you came up with the first line but are unable to make it work.

http://stackoverflow.com/a/69544407
upvote count: 2
has body: None of these answers work if you are arriving from google, I finally found a solution (credit to this answer) from IPython.utils import io with io.capture_output() as captured: foo()
score: 2
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48828824

http://stackoverflow.com/comment/84891185
comment on: http://stackoverflow.com/q/48942243
score: 1
has text: Possible duplicate of [Python dictionary : TypeError: unhashable type: 'list'](https://stackoverflow.com/questions/8532146/python-dictionary-typeerror-unhashable-type-list)
type: Comment
type: QuestionComment

pdftotext
tags question: http://stackoverflow.com/q/48880228
type: Tag
tag name: pdftotext

http://stackoverflow.com/q/48937703
has title: Python HTTPS download fails due to "<urlopen error unknown url type: https>"
accepted answer: http://stackoverflow.com/a/48940966
linked to: http://stackoverflow.com/q/26559709
has body: I'm trying to build a Python 2.7 from source on a pretty minimal system (Ubuntu 16.04 docker image) which doesn't cause HTTPS downloads to fail due to &lt;urlopen error unknown url type: https&gt;. I don't want to use a package manager, but am aware that this would solve the problem easily. I went through Unknown url type error in urllib2 and applied the different referenced patches to setup.py, set the SSL variable in Modules/Setup and Modules/Setup.dist to the installation prefix which I passed to ./config --prefix of OpenSSL 1.1.1 and set LD_LIBRARY_PATH to the OpenSSL installation prefix. I suspect that one such a minimal system more things have to be fixed than suggested in the other answer. Why is there no --with-ssl switch for configure? The build script is apt-get update &amp;&amp; apt-get install --yes wget xz-utils make gcc patch wget http://www.cpan.org/src/5.0/perl-5.26.1.tar.gz &amp;&amp; tar xf perl-5.26.1.tar.gz &amp;&amp; cd perl-5.26.1 &amp;&amp; ./configure.gnu &amp;&amp; make -j16 &amp;&amp; make install &amp;&amp; cd .. wget https://ftp.gnu.org/pub/gnu/gettext/gettext-0.19.8.1.tar.xz &amp;&amp; tar xf gettext-0.19.8.1.tar.xz &amp;&amp; cd gettext-0.19.8.1 &amp;&amp; ./configure &amp;&amp; make -j16 &amp;&amp; make install &amp;&amp; cd .. wget https://www.zlib.net/zlib-1.2.11.tar.gz &amp;&amp; tar xf zlib-1.2.11.tar.gz &amp;&amp; cd zlib-1.2.11 &amp;&amp; ./configure &amp;&amp; make -j16 &amp;&amp; make install &amp;&amp; cd .. wget https://www.kernel.org/pub/software/scm/git/git-2.13.3.tar.gz &amp;&amp; tar xf git-2.13.3.tar.gz &amp;&amp; cd git-2.13.3 &amp;&amp; ./configure --with-perl=/usr/local/bin/perl &amp;&amp; make -j16 &amp;&amp; make install &amp;&amp; cd .. # need `--with-perl` passed to `configure` because the `/usr/local/bin/perl` isn't picked up regardless where it's found in PATH, see https://stackoverflow.com/questions/48931247/cant-locate-extutils-makemaker-pm-in-inc-during-git-build for details wget https://www.openssl.org/sourc…
tagged with: docker
tagged with: openssl
score: 0
has comment: http://stackoverflow.com/comment/84912386
answer count: 1
has comment: http://stackoverflow.com/comment/84913453
has comment: http://stackoverflow.com/comment/84912114
tagged with: python
has answer: http://stackoverflow.com/a/48940966
has comment: http://stackoverflow.com/comment/84911297
type: AnsweredQuestion
tagged with: build
linked to: http://stackoverflow.com/q/48931247
tagged with: ssl
has comment: http://stackoverflow.com/comment/84906947
has comment: http://stackoverflow.com/comment/84911768
has comment: http://stackoverflow.com/comment/84913667
type: Question

http://stackoverflow.com/comment/84932495
has text: Sure, I'll get the code when I'm at my work PC on Monday. For the network architecture I copied the Atari DQN paper's architecture as closely as I could. 3 convolution layers and a fully connected layer then the output.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48898104
score: 0

http://stackoverflow.com/comment/84701366
has text: @julo6: Yeah, unfortunately the only sure way to deal with that is to delete the venv and make it again. (So if you already did that, it was the best option.)
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48822656
type: Comment

http://stackoverflow.com/comment/84693535
score: 0
type: Comment
has text: Print the urls first before saving them to make sure my string formatting adjustments work ok. Try using the .format method for string substitution, it's cleaner than the concatenation.
comment on: http://stackoverflow.com/a/48844643
type: AnswerComment

infinite-scroll
tag name: infinite-scroll
type: Tag
tags question: http://stackoverflow.com/q/48876520

http://stackoverflow.com/q/48951677
upvote count: 1
has answer: http://stackoverflow.com/a/48953578
type: Question
tagged with: default-constructor
has title: Allow the deafult constructor to accept an instance and return it unchainged
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/19608134
has body: I would like to allow my class constructor to accept an instance of this class and in that case to return this same instance instead of creating a new object. Like what tuple does: &gt;&gt;&gt; t = (1, 2, 3) &gt;&gt;&gt; tuple(t) is t True I imagine I need to override the __new__ method for this, and additionally take care of this special case in the __init__ method. Are there any recipes for this? I would have preferred to completely skip __init__ when the constructor is given a class instance that it is going to return unchanged, but I see no way. I am also a bit suspicious about the triple use of cls in the line with super: class C: @staticmethod def __new__(cls, x=None): if isinstance(x, cls): return x else: return super(cls, cls).__new__(cls) def __init__(self, x=None): if x is self: return # Can I just skip __init__ instead? self.x = x (I know about super() without arguments, but I do not like inconsistent magic.) After learning more about super and about MRO in Python, i've figure out that this code is not good. For example, subclassing C results in &gt;&gt;&gt; class D(C): pass &gt;&gt;&gt; d = D(1) ...... RecursionError: maximum recursion depth exceeded while calling a Python object I am so terrified by super() without arguments that magically extracts its arguments from the (lexical or dynamic?) context, that rather than using it I've decided to add a "callback" to finalise the class definition: class C2: @classmethod def finalise(this_cls_yes_this_one): @staticmethod def __new__(cls, x=None): if isinstance(x, cls): return x else: return super(this_cls_yes_this_one, cls).__new__(cls) this_cls_yes_this_one.__new__ = __new__ del this_cls_yes_this_one.finalise def __init__(self, x=None): if x is self: return self.x = x C2.finalise()
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84922605
tagged with: python
has comment: http://stackoverflow.com/comment/84922631
score: 1

http://stackoverflow.com/comment/84827677
type: Comment
has text: Hmm, that is strange @MathieuGalant. Are you _sure_ you're not pressing enter twice?
type: QuestionComment
comment on: http://stackoverflow.com/q/48910537
score: 0

http://stackoverflow.com/a/48889660
score: 1
has body: Sklearn's CountVectorizer is the standard way from sklearn.feature_extraction import text vectorizer = text.CountVectorizer() vec = vectorizer.fit_transform(descriptions) And if you want to see the counts as a dict: count_dict = {k:v for k,v in zip(vectorizer.get_feature_names(), vec.toarray()[0]) if v&gt;0} print (count_dict) The default is unigrams, you can use bigrams or higher ngrams with the ngram_range parameter
upvote count: 1
answers question: http://stackoverflow.com/q/48885233
type: Answer
downvote count: 0

http://stackoverflow.com/q/48868845
type: Question
upvote count: 2
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has comment: http://stackoverflow.com/comment/84742067
has comment: http://stackoverflow.com/comment/84741567
has body: I have troubles to read correctly a csv file with pandas. I've already search a solution to my issue, but I didn't find one. So, my file contains informations about tracks, but the structure of it is a bit special. This is the header structure, and most of the rows respect it. artist, trackname, albumname, tracknum, year, mp3genre Anton Cosmo, Cry, The In Between, 12, 2010, Electro Rock But some rows have a different structure like this one : artist, trackname, albumname, tracknum, year, mp3genre Anne Garner, "Home, Outbound","Long Journey Here, 1, 2011, Electronica I've tried many ways to read this csv file into a pandas DataFrame but I didn't succeed. I thought that: df = pd.read_csv("songs.csv", quotechar="\"") would work but it gives me a line like this one : artist Anne Garner trackname "Home, Outbound" , Long Journey Here albumname 1 tracknum 2011 year Electronica mp3genre NaN instead of : artist Anne Garner trackname Home, Outbound albumname Long Journey Here tracknum 1 year 2011 mp3genre Electronica Do you know a way to do this reading properly? Thanks in advance
has title: Read csv files with quotes with pandas
answer count: 1
has answer: http://stackoverflow.com/a/48943577
has comment: http://stackoverflow.com/comment/84743384
type: UnansweredQuestion
tagged with: pandas
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84742885
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84741883

http://stackoverflow.com/comment/87453712
comment on: http://stackoverflow.com/q/48910821
has text: Good to hear, you should answer the question yourself (for the benefit of others) or delete it then.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48937669
upvote count: 1
has comment: http://stackoverflow.com/comment/84882895
downvote count: 1
possible better answer: http://stackoverflow.com/a/48938445
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48938445
has comment: http://stackoverflow.com/comment/84882557
type: Question
linked to: http://stackoverflow.com/q/11421651
answer count: 2
has answer: http://stackoverflow.com/a/48972862
score: 0
tagged with: linux
has comment: http://stackoverflow.com/comment/84887738
has comment: http://stackoverflow.com/comment/84882461
linked to: http://stackoverflow.com/q/552744
tagged with: python
has body: I have a script that's performing an independent task on about 1200 different files. It loops through each file and checks if it has already been completed or is in progress, if it hasn't been done and isn't being actively worked on (which it wouldn't be if it's not being run in parallel) then it performs a task with the file. This follows the general outline below: myScript.py: for file in directory: fileStatus = getFileStatus(file) if fileStatus != 'Complete' and fileStatus != 'inProgress': setFileStatus(file, 'inProgress') doTask(file) setFileStatus(file, 'Complete') doTask() takes 20-40 minutes on my machine and will arc from minimal RAM requirements at the beginning to about 8GB toward the middle, and back down to minimal requirements at the end. Depending on the file this will occur over a variable amount of time. I would like to run this script in parallel with itself so that all tasks are completed in the least amount of time possible, using the maximum amount of my machine's resources. Assuming (in ignorance) the limiting resource is RAM (of which my machine has 64GB), and that the scripts will all have peak RAM consumption at the same time, I could mimic the response to this question in a manner such as: python myScript.py &amp; python myScript.py &amp; python myScript.py &amp; python myScript.py &amp; python myScript.py &amp; python myScript.py &amp; python myScript.py &amp; python myScript.py &amp; However, I imagine I could fit more in depending on where each process is in its execution. Is there a way to dynamically determine how many resources I have available and accordingly create, destroy or pause instances of this script so that the machine is working at maximum efficiency with respect to time? I would like to avoid making changes to myScript and instead call it from another which would handle the creating, destroying and pausing.
accepted answer: http://stackoverflow.com/a/48972862
linked to: http://stackoverflow.com/q/1023038
favorite count: 0
linked to: http://stackoverflow.com/q/28549641
has comment: http://stackoverflow.com/comment/84885944
has title: How to run an optimal number of instances of a single python script on linux

http://stackoverflow.com/q/48914556
has body: I'm pretty new to python flask, Just wanted to check my code below, where I'm doing things wrong. As when I'm running when on URL like (localhost:5000/submit?name=dial&id=565337) it's running properly, though it's not running when I'm passing values on the form and producing an error. from flask import Flask, request, redirect, url_for import Eoc_Summary import Eoc_Daily import Eoc_AdSize import Eoc_Video import Eoc_Intraction import EOC_definition from config import Config app = Flask(__name__) form = ''' Enter Name: Enter id: ''' @app.route("/") def index(): if request.method == 'GET': return form elif request.method == 'POST': name = request.form['name'] id = request.form['id'] return submit(name, id) @app.route('/submit') def submit(): name = request.args.get('name') id = request.args.get('id') c = Config(name, int(id)) obj_summary=Eoc_Summary.Summary(c) obj_summary.main() obj_daily=Eoc_Daily.Daily(c) obj_daily.main() obj_adSize=Eoc_AdSize.ad_Size(c) obj_adSize.main() obj_Video=Eoc_Video.Video(c) obj_Video.main() obj_Intraction=Eoc_Intraction.Intraction(c) obj_Intraction.main() obj_definition=EOC_definition.definition(c) obj_definition.main() c.saveAndCloseWriter() return 'Report Generated' if __name__ == '__main__': app.run()
has comment: http://stackoverflow.com/comment/84836021
has answer: http://stackoverflow.com/a/48914770
answer count: 1
score: 1
tagged with: flask
tagged with: data-science
favorite count: 0
has comment: http://stackoverflow.com/comment/84836962
has comment: http://stackoverflow.com/comment/84835666
has title: Python(Flask) User Input form
has comment: http://stackoverflow.com/comment/84835766
has comment: http://stackoverflow.com/comment/84835844
tagged with: python
accepted answer: http://stackoverflow.com/a/48914770
type: AnsweredQuestion
upvote count: 2
downvote count: 1
type: Question

http://stackoverflow.com/a/48885830
type: AcceptedAnswer
downvote count: 0
has body: Your line if (playerVX &gt; 0.0 and playerVX &lt; maxSpeed) or is not a complete statement, so you need to indicate to Python that it continues onto the next line. You can do this with more parentheses: if ((playerVX &gt; 0.0 and playerVX &lt; maxSpeed) or (playerVX &lt; 0.0 and playerVX &gt; -maxSpeed)): or using a backslash if (playerVX &gt; 0.0 and playerVX &lt; maxSpeed) or \ (playerVX &lt; 0.0 and playerVX &gt; -maxSpeed): Subsequently, the line if not haveJumped and (leftDown or rightDown) is missing a colon :
has comment: http://stackoverflow.com/comment/84776947
type: Answer
accepted answer of: http://stackoverflow.com/q/48885785
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48885785
has comment: http://stackoverflow.com/comment/84778752
has comment: http://stackoverflow.com/comment/84779617

http://stackoverflow.com/q/48901011
has title: How to embed unembedded fonts in PDF with Python
upvote count: 1
answer count: 1
favorite count: 0
score: 0
tagged with: http://stackoverflow.com/tag/pdf
downvote count: 1
has body: Did some searching, came across this to recognize fonts that aren't embedded but are referenced in a PDF. I need to re-create the PDF having them embedded. I have looked at recreating the PDF with Py2PDF2 or pdfrw but neither of them have an option to embed fonts. Does anybody know of a solution? I don't need pure Python. Alternatively I could start trying to read about the PDF format and try to create a font embed-er myself, but that seems daunting / too big for my current Python/programming skills.
tagged with: python
tagged with: ghostscript
has answer: http://stackoverflow.com/a/48901828
type: UnansweredQuestion
type: Question

http://stackoverflow.com/q/48809574
possible better answer: http://stackoverflow.com/a/48809803
has title: unstacking a list of lists into a pandas dataframe
has answer: http://stackoverflow.com/a/48809803
has answer: http://stackoverflow.com/a/48809606
has body: Say I have the below dataframe: x = pd.DataFrame({'a':['x, y', 'x, t, x, r', 'y, t'], 'b':[1, 0, 1]}) a b 0 x, y 1 1 x, t, x, r 0 2 y, t 1 I would like to get to letter num 0 x 1 1 y 1 2 x 0 3 t 0 4 x 0 5 r 0 6 y 1 7 t 1 I have solved the issue the following way, but I feel like i'm making it more complicated than it needs to be. x.a = x.a.str.split(",") empty = [] for b, a in zip(x.b, x.a): empty.append([b] * len(a)) t = [item for sublist in empty for item in sublist] y = [item for sublist in x.a for item in sublist] pd.DataFrame({'letter':t, 'num':y}) letter num 0 1 x 1 1 y 2 0 x 3 0 t 4 0 x 5 0 r 6 1 y 7 1 t Is there a better way to solve this problem?
tagged with: pandas
type: AnsweredQuestion
score: 3
linked to: http://stackoverflow.com/q/12680754
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48809606
has answer: http://stackoverflow.com/a/48811124
duplicate of: http://stackoverflow.com/q/12680754
type: Question
tagged with: python
upvote count: 3
answer count: 3

http://stackoverflow.com/a/48963655
answers question: http://stackoverflow.com/q/48950420
upvote count: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48950420
has comment: http://stackoverflow.com/comment/84934047
type: Answer
has body: The function plt.Circle() does not allow to specify the number of vertexes to plot. So, you need to write up your own code. Here is my code that you may try: # Plot circle with 36 vertexes phi = np.linspace(0, 2.*np.pi, 36) #36 points r = np.radians(40) x = np.radians(35) + r*np.cos(phi) y = np.radians(30) + r*np.sin(phi) ax.plot(x, y, color="g") Use my code in place of yours 2 lines: circle1 = plt.Circle((np.radians(35), np.radians(30)), np.radians(40), color='g', fill = False) # Circle parameters ax.add_artist(circle1) The resulting image:
score: 1

http://stackoverflow.com/q/48812379
type: AnsweredQuestion
has body: I have got this query in Peewee: return c = Products.get(Products.sku == article).get() How to check if it returns data? I tried: if c.count() &gt; 0: if len(c) &gt; 0 It does not work for me This is full code: try: r = self.isProductExist(row['sku']) ## if (r.count() == 0): except peewee.DoesNotExist: # Insert product def isProductExist(self, article): return Products.get(Products.sku == article).get()
downvote count: 0
score: 1
tagged with: flask-peewee
has comment: http://stackoverflow.com/comment/84628726
type: Question
has title: How to check (count) are returned data?
tagged with: peewee
possible better answer: http://stackoverflow.com/a/48995544
answer count: 2
has comment: http://stackoverflow.com/comment/84628464
upvote count: 1
accepted answer: http://stackoverflow.com/a/49015093
has comment: http://stackoverflow.com/comment/84628334
has comment: http://stackoverflow.com/comment/85034999
favorite count: 0
has comment: http://stackoverflow.com/comment/84628422
has comment: http://stackoverflow.com/comment/84628704
has answer: http://stackoverflow.com/a/49015093
tagged with: python
has answer: http://stackoverflow.com/a/48995544

http://stackoverflow.com/a/56869141
type: Answer
downvote count: 1
score: 44
has comment: http://stackoverflow.com/comment/104066814
upvote count: 45
has comment: http://stackoverflow.com/comment/101170649
has comment: http://stackoverflow.com/comment/102340619
answers question: http://stackoverflow.com/q/48828478
has body: Sometimes you just want a drop-in replacement for a built-in activation layer, and not having to add extra activation layers just for this purpose. For that, you can use the fact that the activation argument can be a callable object. lrelu = lambda x: tf.keras.activations.relu(x, alpha=0.1) model.add(Conv2D(..., activation=lrelu, ...) Since a Layer is also a callable object, you could also simply use model.add(Conv2D(..., activation=tf.keras.layers.LeakyReLU(alpha=0.1), ...) which now works in TF2. This is a better solution as this avoids the need to use a custom_object during loading as @ChristophorusReyhan mentionned.

http://stackoverflow.com/comment/84885173
type: Comment
type: QuestionComment
has text: Your attempt using `execute_script` is looking for `input_4` instead of `input_3`? Is there any way you could give a link to the actual website to look at?
comment on: http://stackoverflow.com/q/48938988
score: 0

http://stackoverflow.com/comment/84832764
type: AnswerComment
has text: Ah-ha! That worked and thank you for the educational answer.
type: Comment
comment on: http://stackoverflow.com/a/48912706
score: 0

http://stackoverflow.com/comment/84645043
comment on: http://stackoverflow.com/q/48820483
has text: This is happening because you are executing the GET and POST requests at the exact same time. Give me just a few minutes and I will rewrite your code for you in an answer that will make more sense.
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48824326
has title: How to change the input language when an entry gets focused in Gtk Python
tagged with: ubuntu
has answer: http://stackoverflow.com/a/48836546
tagged with: keyboard-layout
has body: I want to change the input language when an entry gets focused (or dialog is shown) in Gtk Python. In my program, a dialog appears many times and the user must enter some texts. In systems which allow different keyboard layout for each window, the user must change the input language each time the dialog is appearing. I am programming on ubuntu ...
tagged with: input-language
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48836546
tagged with: gtk
type: AnsweredQuestion
upvote count: 3
type: Question
score: 3

http://stackoverflow.com/comment/84806762
score: 0
type: Comment
type: QuestionComment
has text: Actually, i have dumped the twitter response to a file. Now it is string format. I need to convert it back to json.
comment on: http://stackoverflow.com/q/48900647

http://stackoverflow.com/a/48854241
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84712448
has body: As the position variable changes this is overwritten by it only prints the last one, if you want it not to be overwritten you must pass it as an argument to the lambda function, besides. And for this you must also pass as an argument the variable that sends the signal, in your case use the following: combo.currentIndexChanged.connect( lambda ix, p=position: self.logChange(comboList['combo{0}'.format(p)]))
type: Answer
has comment: http://stackoverflow.com/comment/84712643
downvote count: 0
has comment: http://stackoverflow.com/comment/84712358
accepted answer of: http://stackoverflow.com/q/48854020
score: 3
answers question: http://stackoverflow.com/q/48854020
upvote count: 3

http://stackoverflow.com/comment/84836272
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48914146
has text: Sure. Every component is only affecting the output in a growing-way. Using all lower-bounds gives the minimum objective subject to those bounds. And this objective is still far away from what you want.

http://stackoverflow.com/comment/84797691
score: 0
type: Comment
has text: Then let the OP clarify . The title doesn't say "only." And the OP hasn't shown any error messages or output. And there is no specific question asked, anywhere.
comment on: http://stackoverflow.com/a/48895679
type: AnswerComment

http://stackoverflow.com/a/48815471
downvote count: 0
type: Answer
score: 2
upvote count: 2
has body: Yes, just use result[i][j]. Here's a contrived example: &gt;&gt;&gt; from ctypes import * &gt;&gt;&gt; ppus = POINTER(POINTER(c_ushort)) &gt;&gt;&gt; ppus &lt;class '__main__.LP_LP_c_ushort'&gt; &gt;&gt;&gt; # This creates an array of pointers to ushort[5] arrays &gt;&gt;&gt; x=(POINTER(c_ushort)*5)(*[cast((c_ushort*5)(n,n+1,n+2,n+3,n+4),POINTER(c_ushort)) for n in range(0,25,5)]) &gt;&gt;&gt; a = cast(x,ppus) # gets a ushort** &gt;&gt;&gt; a &lt;__main__.LP_LP_c_ushort object at 0x00000000026F39C8&gt; &gt;&gt;&gt; a[0] # deref to get the first ushort[5] array &lt;__main__.LP_c_ushort object at 0x00000000026F33C8&gt; &gt;&gt;&gt; a[0][0] # get an item from a row 0 &gt;&gt;&gt; a[0][1] 1 &gt;&gt;&gt; &gt;&gt;&gt; a[1][0] 5 So if you are returning the ushort** correctly from C, it should "just work".
accepted answer of: http://stackoverflow.com/q/48804889
has comment: http://stackoverflow.com/comment/84652500
answers question: http://stackoverflow.com/q/48804889
type: AcceptedAnswer

http://stackoverflow.com/a/48818701
type: Answer
accepted answer of: http://stackoverflow.com/q/48805457
has body: I found, the answer. It seems I was running the test code just fine, but against an old version of the module. In the previous version of my code, ClassB did not exist, while ClassA did. After updating my code, I should have run the following to install it. sudo pip install ./ --upgrade Upon installing the updated module running pytest produced the correct results (because i was using the correct code base). [procyclinsur@localhost unit]$ pytest ============================================== test session starts ============================================= platform linux2 -- Python 2.7.14, pytest-3.2.3, py-1.4.34, pluggy-0.4.0 rootdir: /home/procyclinsur/Documents/Projects/xxxxxx/xxxxxx/xxxxxx/tests, inifile: pytest.ini collected 9 items test_File2.py ssss.. test_File1.py ... ====================================== 5 passed, 4 skipped in 0.87 seconds =====================================
answers question: http://stackoverflow.com/q/48805457
upvote count: 1
score: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84756137
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48876081
has text: but still that text after the bold tag can't be extracted.
type: AnswerComment

http://stackoverflow.com/comment/84915287
comment on: http://stackoverflow.com/a/48934390
has text: Hmm, interesting, makes sense! Then I feel @JohanL solution is more suitable. And yeah async func call in multiprocess is better than blocking it till each func returns the result which is in the case of Pool.apply.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48917405
has comment: http://stackoverflow.com/comment/84841320
downvote count: 1
has comment: http://stackoverflow.com/comment/84841301
accepted answer: http://stackoverflow.com/a/48917481
type: Question
has comment: http://stackoverflow.com/comment/84841387
has comment: http://stackoverflow.com/comment/84841544
has comment: http://stackoverflow.com/comment/84841706
has title: Is it possible to use substrings without having to store them in a seperate variable
answer count: 6
upvote count: 4
has comment: http://stackoverflow.com/comment/84841306
has answer: http://stackoverflow.com/a/48917429
tagged with: string
favorite count: 0
possible better answer: http://stackoverflow.com/a/48917496
has comment: http://stackoverflow.com/comment/84842444
has comment: http://stackoverflow.com/comment/84841375
has answer: http://stackoverflow.com/a/48917549
has answer: http://stackoverflow.com/a/48917496
has comment: http://stackoverflow.com/comment/84841500
has comment: http://stackoverflow.com/comment/84841592
tagged with: python
has comment: http://stackoverflow.com/comment/84841343
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84841836
score: 3
has comment: http://stackoverflow.com/comment/84841461
has answer: http://stackoverflow.com/a/48917560
has answer: http://stackoverflow.com/a/48917481
has comment: http://stackoverflow.com/comment/84841881
has comment: http://stackoverflow.com/comment/84841655
has answer: http://stackoverflow.com/a/48917536
has comment: http://stackoverflow.com/comment/84841403
has body: I want to be able to check what the first substring in the string: random_string = "fox is bright orange" is without needing to split the string and then read from the list, or store it some other variable. Is it possible to do this? the string I am using here is just an example, so there is not a designated string being used. I want to be able to figure out the substring (if it were split by ' ') of any string without having to use a list

http://stackoverflow.com/q/48817226
tagged with: django-views
type: Question
has title: Returning Request.Post data from template in Django
answer count: 1
has answer: http://stackoverflow.com/a/48818206
score: 0
tagged with: python
has body: I am trying to get the quantity of single product in cart using request.post but its not returning anything. This is what my views.py file looks like: def test_view(request): cart_obj, new_obj = Cart.objects.new_or_get(request) my_carts_current_entries = Entry.objects.filter(cart=cart_obj) entry_quantity = request.POST.get('entry_quantity') print(entry_quantity) return render(request, 'carts/test.html', {'my_cart': cart_obj, 'my_carts_current_entries': my_carts_current_entries}) This is what my template looks like at the moment: These are the current items in your Basket {% csrf_token %} {% for cart in my_carts_current_entries %} {{ cart.quantity }} x {{ cart.product }} {% endfor %} Add to Basket I am expecting a console printout of the request.post entry quantity. Thanks in advance.
type: UnansweredQuestion
tagged with: django

http://stackoverflow.com/a/48867028
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48866178
type: Answer
has body: Provide the encoding parameter to the ExcelWriter constructor, not in the to_excel() call: &gt;&gt;&gt; writer = pd.ExcelWriter('/path/to/file.xls', encoding='utf-8') &gt;&gt;&gt; df.to_excel(writer,'Sheet1',index=False) &gt;&gt;&gt; writer.save()
has comment: http://stackoverflow.com/comment/84738296
has comment: http://stackoverflow.com/comment/84738769
score: 0
accepted answer of: http://stackoverflow.com/q/48866178

http://stackoverflow.com/q/48961622
tagged with: django-2.0
has body: Im using https://github.com/python-social-auth/social-app-django to make it easy to add new oauths to my django app. I have added it to my settings files and filled in the keys. urls.py urlpatterns = [ path('', include('home.urls')), path('admin/', admin.site.urls), path('auth/', include('social_django.urls', namespace='social')), ] settings.py SOCIAL_AUTH_COINBASE_KEY = os.environ.get('COINBASE_ID') SOCIAL_AUTH_COINBASE_SECRET = os.environ.get('COINBASE_SECRET') AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'social_core.backends.coinbase.CoinbaseOAuth2', # for Coinbase authentication 'django.contrib.auth.backends.ModelBackend', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', 'social_django.context_processors.backends', # &lt;- Here 'social_django.context_processors.login_redirect', # &lt;- Here ], }, }, ] INSTALLED_APPS = [ 'user.apps.UserConfig', 'django.contrib.humanize', 'social_django', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] However when I see the oauth screen of coinbase, I press next, I get redirected to my redirect uri, Then it gives me an error HTTPError at /auth/complete/coinbase/ 403 Client Error: Forbidden for url: https://api.coinbase.com/v2/user I have been trying to fix this issue for hours now but I cant seem to find anything on this
score: 1
tagged with: python-3.x
answer count: 0
type: UnansweredQuestion
tagged with: oauth-2.0
tagged with: django
upvote count: 1
tagged with: python
type: Question
downvote count: 0
has title: Django Social Auth issue with Coinbase
favorite count: 0

http://stackoverflow.com/a/48830858
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48830707
has comment: http://stackoverflow.com/comment/84929645
has body: At the time the offending print statement is executed, the number2 attribute on your Test instance has not been defined. The first time the number2 attribute gets set is in the test_func() method. i.e. Attempting to access number2 before calling test_func() will result in the error you are observing. You should assign a default value to self.number2 in the initializer for the Test class. You could also call test_func() before calling my_func(). But, either way, it's still good practice to initialize all instance attributes in Test.__init__. The interpreter will raise an exception for the same reason when you try to access the undefined attribute __secret_number_2 in my_func().
has comment: http://stackoverflow.com/comment/84666314
type: Answer
downvote count: 0
score: 2
has comment: http://stackoverflow.com/comment/84666292
upvote count: 2
has comment: http://stackoverflow.com/comment/84665992
has comment: http://stackoverflow.com/comment/84666151
answers question: http://stackoverflow.com/q/48830707

http://stackoverflow.com/comment/84617508
comment on: http://stackoverflow.com/a/48807149
type: Comment
has text: Thank you for answering! pip install -U pyautoit first? Or some other approach?
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84879604
comment on: http://stackoverflow.com/a/48917199
score: 0
type: AnswerComment
type: Comment
has text: I was trying to avoid this. I am in the middle of calculating the loss term and want to use the output from the random vector running through the encoder for one section of the loss, with the data vector being used for other section of the loss term. This is why I am having trouble figuring out how to do it.

http://stackoverflow.com/q/48819644
has title: Pandas: Comparing rows within groups
has answer: http://stackoverflow.com/a/48819700
score: 5
has body: I have a dataframe that is grouped by 'Key'. I need to compare rows within each group to identify whether I want to keep each row of the group or whether I want just one row of a group. In the condition to keep all rows of a group: if there is one row that has the color 'red' and area of '12' and shape of 'circle' AND another row (within the same group) that has a color of 'green' and an area of '13' and shape of 'square', then I want to keep all rows in that group. Otherwise if this scenario does not exist, I want to keep the row of that group with the largest 'num' value. df = pd.DataFrame({'KEY': ['100000009', '100000009', '100000009', '100000009', '100000009','100000034','100000034', '100000034'], 'Date1': [20120506, 20120506, 20120507,20120608,20120620,20120206,20120306,20120405], 'shape': ['circle', 'square', 'circle','circle','circle','circle','circle','circle'], 'num': [3,4,5,6,7,8,9,10], 'area': [12, 13, 12,12,12,12,12,12], 'color': ['red', 'green', 'red','red','red','red','red','red']}) Date1 KEY area color num shape 0 2012-05-06 100000009 12 red 3 circle 1 2012-05-06 100000009 13 green 4 square 2 2012-05-07 100000009 12 red 5 circle 3 2012-06-08 100000009 12 red 6 circle 4 2012-06-20 100000009 12 red 7 circle 5 2012-02-06 100000034 12 red 8 circle 6 2012-03-06 100000034 12 red 9 circle 7 2012-04-05 100000034 12 red 10 circle Expected result: Date1 KEY area color num shape 0 2012-05-06 100000009 12 red 3 circle 1 2012-05-06 100000009 13 green 4 square 2 2012-05-07 100000009 12 red 5 circle 3 2012-06-08 100000009 12 red 6 circle 4 2012-06-20 100000009 12 red 7 circle 7 2012-04-05 100000034 12 red 10 circle I am new to python, and groupby is throwing me a curve ball. maxnum = df.groupby('KEY')['num'].transform(max) df = df.loc[df.num == maxnum] cond1 = (df[df['area'] == 12]) &amp; (df[df['color'] == 'red']) &amp; (df[df['shape'] == 'circle']) cond2 = (df[df['area'] == 13]) &amp; (df[df['color'] == 'green']) &amp; (df[df['shape'] == 'square'])
tagged with: python
type: AnsweredQuestion
type: Question
accepted answer: http://stackoverflow.com/a/48819700
upvote count: 5
answer count: 1
downvote count: 0
tagged with: pandas-groupby
tagged with: pandas
favorite count: 0

http://stackoverflow.com/q/48906530
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84818937
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84818820
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has title: Labelling the rows of a Dataframe
has body: I would like to add a new attribute "LabelId" to my dataframe based on the following conditions: given the input dataframe DF, find the k nlargest(k, velocity) and for each value I would like add and substruc some ms e.g. 50 by applying the apply(lambda x: x - np.timedelta64( 50, 'ms' ) ) and apply(lambda x: x + np.timedelta64( 50, 'ms' ) ) and set the new attribute LabelId to 1 otherwise to 0. Input DF: considering 2 largest values of the velocity column and adding 50 ms. eventTime, velocity 1, 2017-08-19T12:53:55:050, 3 2, 2017-08-19T12:53:55:100, 4 3, 2017-08-19T12:53:55:150, 180 4, 2017-08-19T12:53:55:200, 2 5, 2017-08-19T12:53:55:250, 5 6, 2017-08-19T12:53:55:050, 3 7, 2017-08-19T12:53:55:100, 4 8, 2017-08-19T12:53:55:150, 70 9, 2017-08-19T12:53:55:200, 2 10, 2017-08-19T12:53:55:250, 5 Output DF: eventTime, velocity, LabelId 1, 2017-08-19T12:53:55:050, 3, 0 2, 2017-08-19T12:53:55:100, 4, 1 3, 2017-08-19T12:53:55:150, 180, 1 4, 2017-08-19T12:53:55:200, 2, 1 5, 2017-08-19T12:53:55:250, 5, 0 6, 2017-08-19T12:53:55:050, 3, 0 7, 2017-08-19T12:53:55:100, 4, 1 8, 2017-08-19T12:53:55:150, 70, 1 9, 2017-08-19T12:53:55:200, 2, 1 10, 2017-08-19T12:53:55:250, 5, 0 I have been using the above functions but I did not get the right results. Please, any suggestion would be very appreciated. Many Thanks, Best Regards, Carlo
type: Question
has answer: http://stackoverflow.com/a/48906763
tagged with: python
accepted answer: http://stackoverflow.com/a/48906763

http://stackoverflow.com/q/48906990
has title: IronPython access .NET instances
tagged with: python.net
has body: I developed a .NET application. It includes WinForms and public classes. I would like to add python scripting support for my application, so user can interactively access already created .NET class instances. I see IronPython maybe a good choice. I have played with it and found it can easily call my .NET dll classes but I cannot find a way to access the .NET instances. An instance would already include user inputs. Could anyone share your experience in embedding python into .NET application and how my objective can be achieved? Thank you, Hailiang
downvote count: 0
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
tagged with: ironpython
type: Question

tracking
tags question: http://stackoverflow.com/q/48943029
tags question: http://stackoverflow.com/q/48886532
tag name: tracking
type: Tag

http://stackoverflow.com/comment/84742741
comment on: http://stackoverflow.com/q/48869476
has text: Are you looking for `''.join(mylist)` ??
score: 2
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84885545
comment on: http://stackoverflow.com/q/48939119
has text: Thanks! Actually, I did: https://stackoverflow.com/a/48476719/3339058
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84911628
score: 0
type: QuestionComment
has text: you have just normal python lists... nothing `numpy` like
type: Comment
comment on: http://stackoverflow.com/q/48952443

http://stackoverflow.com/comment/84800935
type: Comment
comment on: http://stackoverflow.com/q/48897016
type: QuestionComment
has text: Could you be more specific on how you want the data structured after parsing? A dict?
score: 0

http://stackoverflow.com/q/48819569
has body: I have a use case that requires the identification of many different pieces of text between any two characters. For example, String between a single space and (: def test() would return test String between a word and space (paste), and a special character (/): @paste "game_01/01" would return "game_01 String between a single space and ( with multiple target strings: } def test2() { Hello(x, 1) would return test2 and Hello To do this, I'm attempting to write something generic that will identify the shortest string between any two characters. My current approach is (from chrisz): pattern = '{0}(.*?){1}'.format(re.escape(separator_1), re.escape(separator_2)) And for the first use case, separator_1 = \s and separator_2 = (. This isn't working so evidently I am missing something but am not sure what. tl;dr How can I write a generic regex to parse the shortest string between any two characters? Note: I know there are many examples of this but they seem quite specific and I'm looking for a general solution if possible.
tagged with: python
tagged with: regex
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84643032
has comment: http://stackoverflow.com/comment/84644600
type: Question
has comment: http://stackoverflow.com/comment/84644696
has comment: http://stackoverflow.com/comment/84642989
duplicate of: http://stackoverflow.com/q/32680030
linked to: http://stackoverflow.com/q/48846867
upvote count: 2
score: 0
downvote count: 2
answer count: 1
has answer: http://stackoverflow.com/a/48819633
accepted answer: http://stackoverflow.com/a/48819633
favorite count: 0
has title: Python/Regex: Get all strings between any two characters
has comment: http://stackoverflow.com/comment/84643005

http://stackoverflow.com/q/48829617
has comment: http://stackoverflow.com/comment/84663637
tagged with: python
has body: in pandas I have the following data frame: a b 0 0 1 1 2 1 0 0 1 0 2 1 Now I want to do the following: Create a new column c, and for each row where a = 0 fill c with 1. Then c should be filled with 1s until the first row after each column fulfilling that, where b = 1 (and here im hanging), so the output should look like this: a b c 0 0 1 1 1 1 2 1 0 0 0 1 1 0 1 2 1 1 Thanks!
upvote count: 1
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84726864
score: 1
has title: Find first row with condition after each row satisfying another condition
has answer: http://stackoverflow.com/a/48830004
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48830004
favorite count: 0
tagged with: pandas

http://stackoverflow.com/comment/84663897
type: Comment
comment on: http://stackoverflow.com/a/48829513
score: 0
type: AnswerComment
has text: I grabbed your hint, but I didn't figure out how to change your code. EDIT: I think I fixed! thank you

http://stackoverflow.com/comment/84757233
type: QuestionComment
comment on: http://stackoverflow.com/q/48876575
score: 1
type: Comment
has text: Can you show your use of the `int()` function, and the `SyntaxError` you receive? Please make sure your indentation is correct.

http://stackoverflow.com/comment/89716388
comment on: http://stackoverflow.com/a/51372242
has text: async is a reserved word in python 3.7
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84840424
comment on: http://stackoverflow.com/q/48916243
has text: You are running an old version of Hadoop. You might want to try upgrading to at least 2.7. Not sure if it'll help, though
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84706385
comment on: http://stackoverflow.com/q/48851418
score: 0
type: QuestionComment
type: Comment
has text: When using the web login py as test, it shows I am logged in by return true when my credentials are entered.

http://stackoverflow.com/comment/84711814
comment on: http://stackoverflow.com/q/48854040
type: Comment
score: 1
has text: Your english is good enough, but the problem statement isn't. What are you trying to sum? What would you sum about a `str`? You should place an expected output for both your cases (`float` or `tuple` of `float`s). And your previous comment will certainly attract lots of downvotes. I too feel that downvoting is a too powerful tool in the hands of the brainless (which would use it whenever they don't understand a question, even if it was valid), but it's not the case here.
type: QuestionComment

http://stackoverflow.com/q/48853355
accepted answer: http://stackoverflow.com/a/48853613
tagged with: dataframe
has body: I have a fake data frame below, and try to manipulate the 'contact' column. some people have only phone numbers, some only have emails, some have both number and email with a space in between. So, I want to create two more columns ('gender' and 'email') and split the contact column in 3 columns. ('gender'- (M) into Male and (F) into Female, 'phone_number', and 'email') I tried df = (df.set_index(cols)['contact'].str.split(' ',expand=True).stack() but I failed because some times it has a space between (F) and the phone number after it. employee = {'EmployeeID' : [0,1,2], 'FirstName' : ['a','b','c'], 'LastName' : ['a','b','c'], 'MiddleName' : ['a','b, None], 'Contact' : ['(M) 133-245-3123', '(F)a123@gmail.com', '(F)312-533-2442 jimmy234@gmail.com']} df = pd.DataFrame(employee) Thank you.
tagged with: pandas
upvote count: 1
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48853613
has title: Splitting a column
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 1
type: Question

http://stackoverflow.com/q/48854581
linked to: http://stackoverflow.com/q/14507794
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84713650
possible better answer: http://stackoverflow.com/a/48855160
answer count: 3
has answer: http://stackoverflow.com/a/48855160
score: 1
has comment: http://stackoverflow.com/comment/84735910
favorite count: 0
has answer: http://stackoverflow.com/a/48855216
tagged with: pandas-groupby
tagged with: pandas
has answer: http://stackoverflow.com/a/48869355
tagged with: python
accepted answer: http://stackoverflow.com/a/48855216
type: AnsweredQuestion
upvote count: 2
has body: I have a pandas DataFrame containing some values: id pair value subdir taylor_1e3c_1s_56C taylor 6_13 -0.398716 run1 taylor_1e3c_1s_56C taylor 6_13 -0.397820 run2 taylor_1e3c_1s_56C taylor 6_13 -0.397310 run3 taylor_1e3c_1s_56C taylor 6_13 -0.390520 run4 taylor_1e3c_1s_56C taylor 6_13 -0.377390 run5 taylor_1e3c_1s_56C taylor 8_11 -0.393604 run1 taylor_1e3c_1s_56C taylor 8_11 -0.392899 run2 taylor_1e3c_1s_56C taylor 8_11 -0.392473 run3 taylor_1e3c_1s_56C taylor 8_11 -0.389959 run4 taylor_1e3c_1s_56C taylor 8_11 -0.387946 run5 what I would like to do is to isolate the rows that have the same index, id, and pair, compute the mean and the standard deviation over the value column, and put it all in a new dataframe. Because I have now effectively averaged over all the possible values of subdir, that column should also be removed. So the output should look something like this id pair value error taylor_1e3c_1s_56C taylor 6_13 -0.392351 0.013213 taylor_1e3c_1s_56C taylor 8_11 -0.391376 0.016432 How should I do it in pandas? A previous question showed me how to just get the mean - but it's not clear to me how to generalise this to get the error on the mean (aka the standard deviation) as well. Thank you much to everyone :)
has title: How to create a python dataframe containing the mean and standard deviation of some rows of another dataframe
downvote count: 1
linked to: http://stackoverflow.com/q/48665042
type: Question

http://stackoverflow.com/comment/84809486
comment on: http://stackoverflow.com/a/48902128
score: 0
type: AnswerComment
type: Comment
has text: Thank you @neverwalkaloner ! If I want to replace `MY_TOKEN`, I have to pick up token somewhere or create a new one ?

http://stackoverflow.com/comment/84933723
score: 0
type: Comment
type: QuestionComment
has text: Sure, I could to give ithe url, bu you will need to get a new cookies from there before and inject in the script. The first code is working ... but it is real slow. THis is the reason I want to make a multiple thread... the first code rn very slow requesting one file per time... once the website is private, how could I share the url to you in private ?
comment on: http://stackoverflow.com/q/48961738

http://stackoverflow.com/q/48832536
type: Question
has answer: http://stackoverflow.com/a/48832681
tagged with: django
tagged with: python
has body: I want to run my function to do something in a request to url of serializer my serializer : class usersSerializer(ModelSerializer): class Meta: model=users fields="__all__" my view for serializer: class usersCreate(generics.CreateAPIView): queryset=users.objects.all() serializer_class=usersSerializer my function: def f(): now=datetime.now() now10=now + timedelta(minutes = 10) quer=users.objects.last() rcode=randint(1000,9999) a=SMS(users_id=quer,code=rcode,expireTime=now10) a.save() SMS is another table users_id ====> foreigne key to id in users table I want to when I send request to user create url changed two table : users SMS models: class users(models.Model): number=models.CharField(verbose_name="userNumber",max_length=11) name=models.CharField(verbose_name="name",max_length=40) createTime=models.DateTimeField( auto_now_add=True,auto_now=False) status=models.BooleanField(default=False) class SMS(models.Model): users_id=models.ForeignKey(users,on_delete=models.CASCADE,default=0) code=models.PositiveSmallIntegerField(verbose_name="randomCode") expireTime=models.DateTimeField() status=models.BooleanField(default=False)
tagged with: model-view-controller
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/84669257
has answer: http://stackoverflow.com/a/48832772
has answer: http://stackoverflow.com/a/48843214
tagged with: django-rest-framework
type: AnsweredQuestion
tagged with: sms-verification
accepted answer: http://stackoverflow.com/a/48832772
has title: How to run our function in Django restframwork
possible better answer: http://stackoverflow.com/a/48832681

http://stackoverflow.com/comment/84835804
score: 3
comment on: http://stackoverflow.com/q/48914411
type: Comment
type: QuestionComment
has text: @yolo that doesn't sound like writing a language at all. You are looking for data persistence. There are many ways to do this, from a simple text-file to more robust serialization methods(JSON, `pickle` etc) to full-fledge database management systems.

http://stackoverflow.com/q/48840597
has comment: http://stackoverflow.com/comment/84686731
has comment: http://stackoverflow.com/comment/84733595
has body: I am trying to do insert/update/delete using pymongo. my insert works, but update and delete does not success def update(self,test1): print "hi" client=MongoClient('localhost',27017) db=client.test collection=db.test1 # result = collection.test1.update_one({'col1': 1}, {'$set': {'col2': 'name'}}) result = collection.test1.update_one( {"col4": 'fddf'}, { "$set": { "col1":'12.0' } }, upsert=False ) Delete def Delete(self,test1): client=MongoClient('localhost',27017) db=client.test collection=db.test1 db.test1.remove({"_id": ObjectId("5a880803afe40825990e7255")}) Also it does not give any error. But when I check mongo table, it does not change. Any update much appricated.
tagged with: python-2.7
downvote count: 0
has title: How can I update and delete record in mongo using pymongo
favorite count: 0
has comment: http://stackoverflow.com/comment/84725789
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84686445
tagged with: python
answer count: 0
score: 1
tagged with: pymongo
upvote count: 1
has comment: http://stackoverflow.com/comment/84686681
type: Question
tagged with: mongodb
has comment: http://stackoverflow.com/comment/84728550
has comment: http://stackoverflow.com/comment/84702761
has comment: http://stackoverflow.com/comment/84728784

http://stackoverflow.com/q/48945035
type: AnsweredQuestion
score: 1
tagged with: matplotlib
upvote count: 1
type: Question
has title: How can I make histogram from word length in Python?
has comment: http://stackoverflow.com/comment/84896684
accepted answer: http://stackoverflow.com/a/48945500
downvote count: 0
has body: I have to make a histogram, that shows the word length frequency from a poem. I've got the frequency, but I can't represent it in a histogram. This is my code: full = "Ej mi a kő! tyúkanyó, kend A szobában lakik itt bent? Lám, csak jó az isten, jót ád, Hogy fölvitte a kend dolgát! Itt szaladgál föl és alá, Még a ládára is fölszáll, Eszébe jut, kotkodákol, S nem verik ki a szobábol. Dehogy verik, dehogy verik! Mint a galambot etetik, Válogat a kendermagban, A kiskirály sem él jobban. Ezért aztán, tyúkanyó, hát Jól megbecsűlje kend magát, Iparkodjék, ne legyen ám Tojás szűkében az anyám. – Morzsa kutyánk, hegyezd füled, Hadd beszélek mostan veled, Régi cseléd vagy a háznál, Mindig emberűl szolgáltál, Ezután is jó légy, Morzsa, Kedvet ne kapj a tyúkhusra, Élj a tyúkkal barátságba’... Anyám egyetlen jószága." vs = full.translate(string.punctuation) vers = vs.lower().split() c=[len(i) for i in vers] # gives [3, 3, 5, 5, 3, 6, 4, 4, 3, 5] counts=[0]*max(c) # gives [0, 0, 0, 0, 0, 0] for i in range(len(c)): counts[c[i]-1]+=1 # adds 1 to each index of c[i] (we subtract 1 because of 0-based indices) print(counts) plt.hist(counts, 14) What did I do wrong? The X and Y axis are inverted, it shows the word length opposive. :( Thanks in advance.
linked to: http://stackoverflow.com/q/19198920
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84896732
has comment: http://stackoverflow.com/comment/84897025
tagged with: python
has answer: http://stackoverflow.com/a/48945500

http://stackoverflow.com/comment/84852618
type: QuestionComment
type: Comment
has text: @JasonYe-MSFT I used managed disk
comment on: http://stackoverflow.com/q/48911885
score: 0

http://stackoverflow.com/q/48919331
has comment: http://stackoverflow.com/comment/84859218
has comment: http://stackoverflow.com/comment/84846941
has answer: http://stackoverflow.com/a/48919495
accepted answer: http://stackoverflow.com/a/48919495
upvote count: 4
possible better answer: http://stackoverflow.com/a/48919479
favorite count: 0
has title: How to parse a file sentence by sentence in Python
has comment: http://stackoverflow.com/comment/84847015
has comment: http://stackoverflow.com/comment/84848507
downvote count: 2
has comment: http://stackoverflow.com/comment/84865830
tagged with: python
has body: I need to read a large amount of large text files. For each file, I need to open it and read in text sentence by sentence. Most of approaches I found is read line by line. How can I do it with Python?
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84846521
tagged with: tokenize
has answer: http://stackoverflow.com/a/48919479
type: Question
answer count: 2
tagged with: nltk
has comment: http://stackoverflow.com/comment/84845316
has comment: http://stackoverflow.com/comment/84874695
has comment: http://stackoverflow.com/comment/84925259

http://stackoverflow.com/comment/84733603
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48864714
has text: ... and while _some_ numbers can be accurately represented as `float`, it would be impossible to tell whether your number is one of those, or just got rounded to one of those.

http://stackoverflow.com/comment/84765539
score: 1
comment on: http://stackoverflow.com/a/48879870
type: AnswerComment
has text: @PatrickArtner I use jupyter notebook (edited answer)! Included your stats as well
type: Comment

http://stackoverflow.com/comment/84788400
comment on: http://stackoverflow.com/q/48891003
has text: (BTW, I recommend using [`math.hypot`](https://docs.python.org/3/library/math.html#math.hypot) to shorten those long denominators.)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/a/48847094
score: 0
answers question: http://stackoverflow.com/q/48846700
type: Answer
has body: You should change your code to: search_box.get_attribute('value') That should do the trick

http://stackoverflow.com/q/48959201
tagged with: python-xarray
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84927870
has title: xarray - store strings as 'string' data-type instead of 'char' (n-dimensional character arrays) for Python2.7
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/49055035
upvote count: 2
tagged with: netcdf
has body: I am converting a text file to netCDF format using xarray. When I am using netCDF4 format and Python3, it is storing string variables as strings but when I use Python2 it stores them as n-dimensional character arrays. I have tried to set dtype='str' in encoding and that didn't make any difference. Is there a way to make these variables to have string data-type using Python2? Any thoughts would be appreciated. Here is my code: import pandas as pd import xarray as xr column_names = ['timestamp', 'air_temp', 'vtempdiff', 'rh', 'pressure', 'wind_dir', 'wind_spd'] df = pd.read_csv(args.input_file, skiprows = 1, header=None, names = column_names) ds = xr.Dataset.from_dataframe(df) encoding = {'timestamp': {'dtype': 'str'}, 'air_temp': {'_FillValue': 9.96921e+36, 'dtype': 'f4'} } ds.to_netcdf(op_file.nc, format = 'NETCDF4', unlimited_dims={'time':True}, encoding = encoding) When I do ncdump of the op_file.nc using Python3.6, I get: netcdf op_file { dimensions: time = UNLIMITED ; // (24 currently) variables: string timestamp(time) ; float air_temp(time) ; . . . And when I use Python2.7, I get: netcdf op_file { dimensions: time = UNLIMITED ; // (24 currently) string20 = 20 ; variables: char timestamp(time, string20) ; timestamp:_Encoding = "utf-8" ; float air_temp(time) ; . . . The sample input file looks like this: # Fields: stamp,AGO-4.air_temp,AGO-4.vtempdiff,AGO-4.rh,AGO-4.pressure,AGO-4.wind_dir,AGO-4.wind_spd 2016-11-30T00:00:00Z,-36.50,,56.00,624.60,269.00,5.80 2016-11-30T01:00:00Z,-35.70,,55.80,624.70,265.00,5.90
type: Question
type: AnsweredQuestion
tagged with: netcdf4
accepted answer: http://stackoverflow.com/a/49055035

http://stackoverflow.com/comment/84822925
score: 0
type: Comment
has text: Thank you, I didn't know about the np.ones() function. Could you elaborate on the robust estimate of the stdev part? I searched here but couldn't find anything: http://www.statsmodels.org/dev/generated/statsmodels.robust.robust_linear_model.RLMResults.html#statsmodels.robust.robust_linear_model.RLMResults
comment on: http://stackoverflow.com/a/48908412
type: AnswerComment

http://stackoverflow.com/comment/84887752
score: 0
has text: shouldn't ssl_version should be defined for both client and server?
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48939942

http://stackoverflow.com/comment/84876284
type: QuestionComment
has text: Multiply your float array by 1000, pass it in, divide the output by 1000? So if your number was 12.123, pass in 12123 as an integer.
score: 1
comment on: http://stackoverflow.com/q/48934830
type: Comment

http://stackoverflow.com/comment/84673157
score: 6
has text: Please define what you mean by "doesn't work". Do you get any output? How are you running your script?
comment on: http://stackoverflow.com/q/48834317
type: Comment
type: QuestionComment

form-submit
tags question: http://stackoverflow.com/q/48834408
tag name: form-submit
type: Tag

http://stackoverflow.com/a/48843315
answers question: http://stackoverflow.com/q/48817784
has body: I came up with a hack to solve my narrow problem so I'm posting here, but I'm accepting the answer from @Sorin because it's probably more generally applicable. To get around the fact that tf.boolean_mask() can only act on the initial indices, I just rolled the indices forward, applied the mask, and then rolled them back. In simplified form, it looks like this: indices = tf.range(tf.rank(large_array)) large_array_rolled_forward = tf.transpose( large_array, tf.concat([indices[-2:], indices[:-2]], axis=0)) large_array_rolled_forward_masked = tf.boolean_mask( large_array_rolled_forward, mask) new_indices = tf.range(tf.rank(large_array_rolled_forward_masked)) large_array_masked = tf.transpose( large_array_rolled_forward_masked, tf.concat([new_indices[1:], [0]], axis=0))
downvote count: 0
type: Answer
score: 1
upvote count: 1

http://stackoverflow.com/q/48846882
tagged with: apache-spark
answer count: 1
has comment: http://stackoverflow.com/comment/85007375
has title: pyspark : ml + streaming
accepted answer: http://stackoverflow.com/a/49003048
has body: According to Combining Spark Streaming + MLlib it is possible to make a prediction over a stream of input in spark. The issue with the given example (which works on my cluster) is that the testData is a given right on the correct format. I am trying to set up a client &lt;-> server tcp exchange based on strings of data. I can't figure out how to transform the string on the correct format. while this works : sep = ";" str_recue = '0.0;0.1;0.2;0.3;0.4;0.5' rdd = sc.parallelize([str_recue]) chemin = "hdfs://xx.xx.xx.xx:8020/cart_model_for_cycliste_v2" model = DecisionTreeClassificationModel.load(chemin) # travail sur la string rdd2 = rdd.map( lambda data : data.split(sep)) rdd3 = rdd2.map(lambda tableau: [float(x) for x in tableau]) # création df cols = ["c1", "c2", "c3", "c4", "c5", "c6"] fields = [StructField(x, FloatType(), True) for x in cols] schema = StructType(fields) df = spark.createDataFrame(rdd3, schema=schema ) # preparation d'une colonne de features schema = StructType(fields) assembler = VectorAssembler() assembler = assembler.setInputCols(cols) assembler = assembler.setOutputCol("features") df2 = assembler.transform(df) model.transform(df2).show() giving : +---+---+---+---+---+---+--------------------+-------------+-----------+----------+ | c1| c2| c3| c4| c5| c6| features|rawPrediction|probability|prediction| +---+---+---+---+---+---+--------------------+-------------+-----------+----------+ |0.0|0.1|0.2|0.3|0.4|0.5|[0.0,0.1000000014...| [0.0,3426.0]| [0.0,1.0]| 1.0| +---+---+---+---+---+---+--------------------+-------------+-----------+----------+ I can't figure out how to make it works while listening to a socket. I have my server : import socket import random import time port = 12003 ip = socket.gethostname() serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serversocket.bind((ip, port)) serversocket.listen(1) (clientsocket, address) = serversocket.accept() nb_d_envois = 10 tps_attente = 3 for i in range(nb_d_envois): time.sleep(tps_a…
tagged with: spark-streaming
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/49003048
linked to: http://stackoverflow.com/q/36838024
tagged with: apache-spark-mllib
has comment: http://stackoverflow.com/comment/84729263
score: 0

http://stackoverflow.com/q/48889769
has answer: http://stackoverflow.com/a/49462946
has title: ctc loss error - sequence_length(0) <= 3
linked to: http://stackoverflow.com/q/43422949
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/44762631
tagged with: convolution
type: UnansweredQuestion
tagged with: python
upvote count: 3
has body: i am facing an error similar to the one stated here CTC Loss InvalidArgumentError: sequence_length(b) &lt;= time but there seems to be no explanation of what the error actually means. Based on the reading i did, does it mean that the sequence length of the example "0" in the minibatch is less than 3 ? in which case why is it an error (since as explained in the tf doc and the question above, the length of all sequences has to be lesser than time, right ?) ..could anyone kindly explain how i could debug the issue and make sense of the error? i am using an existing conv2d example and trying to merge ctc loss using some audio files i had the code is present here https://github.com/takingstock/ServerSide-Algos/blob/master/ctc-conv.py and the problem occurs on line 213 (apologies for pasting the code github url instead of the code here..i felt it might be cleaner this way) the stack trace Caused by op u'CTCLoss', defined at: File "conv_train.py", line 279, in &lt;module&gt; loss = tf.nn.ctc_loss(Y , logits, seq_len) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/ctc_ops.py", line 156, in ctc_loss ignore_longer_outputs_than_inputs=ignore_longer_outputs_than_inputs) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/ops/gen_ctc_ops.py", line 224, in _ctc_loss name=name) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper op_def=op_def) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3160, in create_op op_def=op_def) File "/usr/local/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1625, in __init__ self._traceback = self._graph._extract_stack() # pylint: disable=protected-access InvalidArgumentError (see above for traceback): sequence_length(0) &lt;= 3 [[Node: CTCLoss = CTCLoss[ctc_merge_repeated=true, ignore_longer_outputs_than_inputs=false, preprocess_collapse_repeated=false, _device="/job:localhost/replica:0/ta…
tagged with: tensorflow
type: Question
score: 3

http://stackoverflow.com/comment/84872110
comment on: http://stackoverflow.com/a/48932102
score: 0
type: AnswerComment
has text: unfortunately I got the following error `AttributeError: 'list' object has no attribute 'columns'`
type: Comment

http://stackoverflow.com/comment/84644284
comment on: http://stackoverflow.com/q/48815453
type: Comment
type: QuestionComment
score: 0
has text: that is a typo,it is fixed and new information is added.eg:part of matrix of output, and code for printing image.

http://stackoverflow.com/comment/84649741
type: Comment
has text: @ChukUltima They are separated by a tab, btw.
comment on: http://stackoverflow.com/q/48822984
score: 0
type: QuestionComment

http://stackoverflow.com/a/48855762
has comment: http://stackoverflow.com/comment/84715869
score: 0
answers question: http://stackoverflow.com/q/48853323
has comment: http://stackoverflow.com/comment/84741178
type: Answer
has body: Before calling PyModule_GetDict, check that pModule isn't NULL. It would mean that PyImport_Import failed to import the module (problem with path, etc...)
has comment: http://stackoverflow.com/comment/84715312

http://stackoverflow.com/q/48950800
has title: Get "<Response [403]>" using request.post in Python
has comment: http://stackoverflow.com/comment/84908119
type: UnansweredQuestion
has body: I was trying to get search result from a website, however I got "Response[403]" message, I've found similar post solving 403 error by adding headers to request.post, however it didn't work for my problem. What should I do to correctly get the result I want? from urllib.request import urlopen import urllib.parse import urllib.request import requests from bs4 import BeautifulSoup url="https://www.metal-archives.com/" html= urlopen(url) print("The keyword you entered to search is: %s\n" % 'Bathory') 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'} result=requests.post(url, data='Bathory', headers=headers) print(result.content)
tagged with: python
has comment: http://stackoverflow.com/comment/84908181
tagged with: urlopen
tagged with: web-scraping
tagged with: python-requests
type: Question
has answer: http://stackoverflow.com/a/48951070
has comment: http://stackoverflow.com/comment/84908549
score: 0
answer count: 2
tagged with: beautifulsoup
has comment: http://stackoverflow.com/comment/84986207
has answer: http://stackoverflow.com/a/48955303

python-3.5
tags question: http://stackoverflow.com/q/48875213
type: Tag
tags question: http://stackoverflow.com/q/48891184
tags question: http://stackoverflow.com/q/48891742
tags question: http://stackoverflow.com/q/48840282
tags question: http://stackoverflow.com/q/48843193
tags question: http://stackoverflow.com/q/48872304
tag name: python-3.5
tags question: http://stackoverflow.com/q/48903282
tags question: http://stackoverflow.com/q/48895294
tags question: http://stackoverflow.com/q/48812500
tags question: http://stackoverflow.com/q/48941432
tags question: http://stackoverflow.com/q/48883647
tags question: http://stackoverflow.com/q/48908634
tags question: http://stackoverflow.com/q/48914590
tags question: http://stackoverflow.com/q/48874110
tags question: http://stackoverflow.com/q/48837553

http://stackoverflow.com/comment/84659731
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48811850
has text: Hope you would not mind the injected [us]-resolution timing tools. **Would you mind to re-run and benchmark your proposal** on your machine so as to make the concept quantitatively comparable with the other approach, given better performance is the target?

http://stackoverflow.com/a/48963420
downvote count: 0
has body: The problem is that execute's second parameter expects a tuple. You've got an array, basically, from item.values(). To convert to a tuple, use: self.cur.execute(sql.format(col, placeholders), tuple(item.values())) You were thinking along the right lines, but, for example, your attempt (item.values(),) produces a tuple containing a single value, which is the whole of the array you get back from values(). tuple(item.values()) converts the array of values into a tuple containing each value as an individual element. Say your Items are { 'name1': 'value1', 'name2': 'value2'}. Then (item.values(),) is the tuple (['value1', 'value2']), i.e. a tuple with one value containing an array. But tuple(item.values()) is ('value1', 'value2'), i.e. a tuple containing a value for every item that was in the array, which is what's needed.
type: Answer
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48961297

http://stackoverflow.com/a/48838373
has comment: http://stackoverflow.com/comment/84681448
type: Answer
has comment: http://stackoverflow.com/comment/84681826
has comment: http://stackoverflow.com/comment/84681259
has comment: http://stackoverflow.com/comment/84681498
has comment: http://stackoverflow.com/comment/84681352
accepted answer of: http://stackoverflow.com/q/48838342
has comment: http://stackoverflow.com/comment/84681314
has comment: http://stackoverflow.com/comment/84681561
has comment: http://stackoverflow.com/comment/84681295
has comment: http://stackoverflow.com/comment/84681374
has comment: http://stackoverflow.com/comment/84681397
score: 0
has body: Here's what you need try: start = 5000 end = 50000 step = 10 # define the interval here for i in range(start, end, step): url = 'https://testesite.com/Fatura/Pdf?nrFatura='+str(i).zfill(len(str(end))) print(url) q.put(url) q.join()
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84681537
answers question: http://stackoverflow.com/q/48838342
has comment: http://stackoverflow.com/comment/84681293

http://stackoverflow.com/comment/84922677
has text: What exactly are you trying to achieve? This isn't a multiple-choice field, so clicking each `option` just changes the focus on every iteration
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48957805

http://stackoverflow.com/a/48942331
score: 3
downvote count: 0
answers question: http://stackoverflow.com/q/48938828
upvote count: 3
has comment: http://stackoverflow.com/comment/84950849
type: Answer
has body: You are passing the parameter value n_fold=1 This doesn't make sense. Cross validation is all about partitioning the data in several partitions and validating the model holding out one partition among them. so 1 is an invalid value, try n_fold=3 or higher. Then your error should be gone. Read more about cross validation here. http://scikit-learn.org/stable/modules/cross_validation.html

http://stackoverflow.com/comment/94712577
type: AnswerComment
type: Comment
has text: testing.postgres starts a local postgres server - you don't point it at anything - I'm not sure I understand the question?
score: 1
comment on: http://stackoverflow.com/a/48815977

http://stackoverflow.com/comment/84721354
has text: @coldspeed sorry for mis-confusion before I didn't assign the result back so I got that error, now I'm getting error TypeError: the JSON object must be str, not 'dict'
comment on: http://stackoverflow.com/a/48858735
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48869423
has title: How do I copy the contents of a word document?
has body: I want to write a program that copies text from a Word document and pastes it to another. I'm trying to do that using the python-docx library. I was able to do that with the following code, but it does not copy the bold, italic, underlined nor colored parts as they are and only their text: from docx import Document input = Document('SomeDoc.docx') paragraphs = [] for para in input.paragraphs: p = para.text paragraphs.append(p) output = Document() for item in paragraphs: output.add_paragraph(item) output.save('OutputDoc.docx') I've also tried copying the paragraph object directly into the output document, but it doesn't work either: from docx import Document input = Document('SomeDoc.docx') output = Document() for para in input.paragraphs: output.add_paragraph(para) output.save('OutputDoc.docx')
type: Question
has answer: http://stackoverflow.com/a/78245478
answer count: 2
has answer: http://stackoverflow.com/a/48925828
has comment: http://stackoverflow.com/comment/84751515
downvote count: 0
tagged with: python-docx
tagged with: ms-word
favorite count: 0
score: 8
accepted answer: http://stackoverflow.com/a/48925828
upvote count: 8
has comment: http://stackoverflow.com/comment/84743497
tagged with: python
tagged with: styles
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/78245478

http://stackoverflow.com/q/48857367
favorite count: 0
upvote count: 2
has title: PyQt: QDialogButtonBox with 3 options
tagged with: python
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48860703
type: Question
has body: I'm trying to create an alert for a user via a three button dialog box asking if they'd like to save their changes or not, or just cancel out of the operation altogether. I can manage the yes and the canceling out, but the 'don't save' option isn't working. Here is what I have: import logging import Qt # from functools import wraps from Qt import QtGui, QtCore, QtWidgets dialog = QtWidgets.QDialog() #parent=parent) dialog.setWindowTitle("Foo") dialog.verticalLayout = QtWidgets.QVBoxLayout(dialog) # Create the dialogs main message (Qlabel) dialog.label = QtWidgets.QLabel(dialog) dialog.label.setAlignment(QtCore.Qt.AlignCenter) dialog.label.setTextInteractionFlags(dialog.label.textInteractionFlags() | QtCore.Qt.TextBrowserInteraction) dialog.label.setTextFormat(QtCore.Qt.RichText) dialog.label.setOpenExternalLinks(True) dialog.label.setText("Magoo?") dialog.verticalLayout.addWidget(dialog.label) dialog.widget = QtWidgets.QWidget(dialog) dialog.horizontalLayout = QtWidgets.QHBoxLayout(dialog.widget) dialog.horizontalLayout.setContentsMargins(-1, -1, -1, 0) dialog.horizontalLayout.setObjectName("horizontalLayout") dialog.verticalLayout.addWidget(dialog.widget) # Create the buttonbox with options dialog.buttonBox = QtWidgets.QDialogButtonBox(dialog.widget) dialog.buttonBox.setOrientation(QtCore.Qt.Horizontal) dialog.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Discard | QtWidgets.QDialogButtonBox.Cancel | QtWidgets.QDialogButtonBox.Yes) dialog.horizontalLayout.addWidget(dialog.buttonBox) # Connect the buttonbox signals dialog.buttonBox.accepted.connect(dialog.accept) dialog.buttonBox.rejected.connect(dialog.reject) QtCore.QMetaObject.connectSlotsByName(dialog) # Resize the dialog box to scale to its contents dialog.adjustSize() # Launch the dialog yes = dialog.exec_() dont_notify_again = dialog.checkBox.isChecked() I am probably missing what the connection to the signals should be, but I'm not sure what those are.
tagged with: pyqt
answer count: 1
downvote count: 0
accepted answer: http://stackoverflow.com/a/48860703

http://stackoverflow.com/q/48893256
has body: I want to test if a string has a negative leading character, and then delete that character if True. I've tried: value_a = "-50.1342" temp_a = value_a.split(".") #needed for other purposes if temp_a[0].startswith('-'): del temp_a[0] print temp_a The result is an empty []. What could be the reason...?
tagged with: string
linked to: http://stackoverflow.com/q/509211
favorite count: 0
has comment: http://stackoverflow.com/comment/84792268
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/48893353
has comment: http://stackoverflow.com/comment/84792150
tagged with: python
has comment: http://stackoverflow.com/comment/84792204
answer count: 4
tagged with: negative-number
has comment: http://stackoverflow.com/comment/84794640
has title: python remove leading negative sign in string
type: Question
has comment: http://stackoverflow.com/comment/84792163
has comment: http://stackoverflow.com/comment/84792501
has answer: http://stackoverflow.com/a/48893366
has comment: http://stackoverflow.com/comment/84792297
has answer: http://stackoverflow.com/a/48893461
has answer: http://stackoverflow.com/a/48893348
upvote count: 0
score: -2

http://stackoverflow.com/comment/84671300
has text: You don't need that `if` statement at all.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48833362

http://stackoverflow.com/a/48911268
has comment: http://stackoverflow.com/comment/84829151
has comment: http://stackoverflow.com/comment/84831594
has comment: http://stackoverflow.com/comment/84830819
has comment: http://stackoverflow.com/comment/84830947
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84829632
answers question: http://stackoverflow.com/q/48910713
type: Answer
has comment: http://stackoverflow.com/comment/84828968
accepted answer of: http://stackoverflow.com/q/48910713
has comment: http://stackoverflow.com/comment/84830401
score: 1
has comment: http://stackoverflow.com/comment/84830152
has comment: http://stackoverflow.com/comment/84831111
upvote count: 1
has comment: http://stackoverflow.com/comment/84829566
has comment: http://stackoverflow.com/comment/84831139
has body: For invoice lines(account.invoice.line) there are many required fields like name(description), qty etc.In your example you have passed only name. Try passing all required fields.
has comment: http://stackoverflow.com/comment/84829872
has comment: http://stackoverflow.com/comment/84830752
has comment: http://stackoverflow.com/comment/84831312

http://stackoverflow.com/comment/84779434
comment on: http://stackoverflow.com/q/48887198
score: 0
type: QuestionComment
type: Comment
has text: Yes A.keys() sorry

http://stackoverflow.com/comment/84814983
comment on: http://stackoverflow.com/q/48904574
has text: The [`strip`](https://docs.python.org/2/library/stdtypes.html#str.strip) method of `str` objects is not deprecated. What is deprecated is calling the [`strip`](https://docs.python.org/2/library/string.html#string.strip) function from the [`string`](https://docs.python.org/2/library/string.html) module.
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/84901715
comment on: http://stackoverflow.com/a/48936080
type: Comment
type: AnswerComment
has text: Hi @saraswatmks, thanks for taking the time to respond. I'm not sure you've understood what im asking for or if I have explained it correctly as your output isnt the result I'm trying to get to and I'm not sure what the Pay_Value relates to? The number of months should be based on the duration text, so for row 0 the ouput should be 12 months not -1. And row 3 should be 5 not -1.
score: 0

http://stackoverflow.com/comment/84691286
type: Comment
has text: What is 'S{k}'?
comment on: http://stackoverflow.com/a/48843378
score: 0
type: AnswerComment

http://stackoverflow.com/q/48955382
has answer: http://stackoverflow.com/a/48955902
has comment: http://stackoverflow.com/comment/84918642
tagged with: machine-learning
tagged with: python
score: 3
upvote count: 3
tagged with: tensorflow-serving
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/55563531
has title: ValueError: Cannot feed value of shape () for Tensor 'input_example_tensor:0', which has shape '(?,)'
has body: Why this error appear? I cannot find similar to mine case with an answer with an explanation why that's happening. There are a lot of info there for such errors, but seems like it depends on a lot of reasons and for different cases, it can have different solutions. So I am trying to load TensorFlow trained model, then convert it into TensorFlow Serving model format and that makes a prediction. iris_data.py file from import bellow. That's how I export my model (train already did, I just load it from disk): import tensorflow as tf import iris_data from tensorflow.contrib import predictor # Fetch the data (train_x, train_y), (test_x, test_y) = iris_data.load_data() # Feature columns describe how to use the input. my_feature_columns = [] for key in train_x.keys(): my_feature_columns.append(tf.feature_column.numeric_column(key=key)) # Build 2 hidden layer DNN with 10, 10 units respectively. classifier = tf.estimator.DNNClassifier( feature_columns=my_feature_columns, # Two hidden layers of 10 nodes each. hidden_units=[10, 10], # The model must choose between 3 classes. n_classes=3, model_dir='G:\AI models') #converting into TensorFlow Serving model format path = 'G:\AI models\serve' feature_spec = tf.feature_column.make_parse_example_spec(my_feature_columns) export_input_fn = tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec) servable_model_path = classifier.export_savedmodel(path, export_input_fn, as_text=True) Here is how I try to get a prediction using TensorFlow Serving model: expected = ['Setosa', 'Versicolor', 'Virginica'] predict_x = { 'SepalLength': [5.1, 5.9, 6.9], 'SepalWidth': [3.3, 3.0, 3.1], 'PetalLength': [1.7, 4.2, 5.4], 'PetalWidth': [0.5, 1.5, 2.1], } path = 'G:\AI models\serve\\1519413839' predict_fn = predictor.from_saved_model(path) predictions = predict_fn( {"inputs": predict_x}) And finally get an error: ValueError: Cannot feed value of shape () for Tensor 'input_example_tensor:0', which has shape '(?,)'
has answer: http://stackoverflow.com/a/48956013
answer count: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84918661
favorite count: 0
type: UnansweredQuestion

http://stackoverflow.com/a/48955090
has comment: http://stackoverflow.com/comment/84917091
has comment: http://stackoverflow.com/comment/84917660
has body: Let's simplify the visual a bit: key_list = ['a', 'c', 'f'] wrong_list = ['a', 'b', 'c', 'd', 'e', 'f'] wrong_list_fixed = [['a', 'b'], ['c', 'd', 'e'], ['f']] This will be semantically identical to what you have, but I think it is easier to see without all the extra nested brackets. You could use itertools.groupby, if you could only come up with a clever key. Luckily, the mapping of key_list to wrong_list givs you exactly what you want: class key: def __init__(self, key_list): self.last = -1 self.key_list = key_list def __call__(self, item): try: self.last = self.key_list.index(item, self.last + 1) except ValueError: pass return self.last wrong_list_fixed = [list(g) for k, g in itertools.groupby(wrong_list, key(key_list))] The key maps elements of wrong_list to key_list using index. For missing indices, it just returns the last one successfully found, ensuring that groups are not split until a new index is found. By starting the search from the next available index, you can ensure that duplicate entries in key_list get handled correctly. [IDEOne Link]
downvote count: 0
has comment: http://stackoverflow.com/comment/84917126
has comment: http://stackoverflow.com/comment/84917626
has comment: http://stackoverflow.com/comment/84917629
has comment: http://stackoverflow.com/comment/84917018
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/84917829
has comment: http://stackoverflow.com/comment/84917798
has comment: http://stackoverflow.com/comment/84917179
has comment: http://stackoverflow.com/comment/84916944
answers question: http://stackoverflow.com/q/48954408
upvote count: 3
has comment: http://stackoverflow.com/comment/84917030
has comment: http://stackoverflow.com/comment/84917468
has comment: http://stackoverflow.com/comment/84916921

http://stackoverflow.com/a/48806015
has comment: http://stackoverflow.com/comment/84615350
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48805828
has body: Probably the device echoes back what it got and then sends its reply. Have you tried to increase the number of bytes you receive? There is a chance that if you do y = ser.read(100) (with timeout enabled), you will get everything you asked for. An alternative is to read exactly as many bytes as there are available: y = ser.read(ser.in_waiting) or y = ser.read(ser.inWaiting()) (depending on the version of pyserial).
answers question: http://stackoverflow.com/q/48805828
type: Answer
has comment: http://stackoverflow.com/comment/84620745

http://stackoverflow.com/q/48960196
favorite count: 0
type: UnansweredQuestion
tagged with: input
tagged with: output
upvote count: 0
tagged with: anaconda
has body: I want to install anaconda 3 ,however, I got this message. How can I solve it? plus. is there any binary code for anaconda3? installing: python-3.6.3-hc9025b9_1 ... tar: lib/python3.6/distutils/log.py: Cannot open: Input/output error tar: Exiting with failure status due to previous errors
score: -1
has answer: http://stackoverflow.com/a/48960436
type: Question
has title: Can't install anaconda3 because of the input output error
tagged with: linux
answer count: 1
downvote count: 1
tagged with: python

http://stackoverflow.com/q/48896971
type: Question
has body: In the following method, I am unsure of what .join(data_directory, d) and .join(ROOT_PATH, "TrafficSigns/Training") yields. Specifically I don't know how .join() handles these two parameters. def load_data(data_directory): directories = [d for d in os.listdir(data_directory) if os.path.isdir(os.path.join(data_directory, d))] labels = [] images = [] for d in directories: label_directory = os.path.join(data_directory, d) file_names = [os.path.join(label_directory, f) for f in os.listdir(label_directory) if f.endswith(".ppm")] for f in file_names: images.append(skimage.data.imread(f)) labels.append(int(d)) return images, labels ROOT_PATH = "/your/root/path" train_data_directory = os.path.join(ROOT_PATH, "TrafficSigns/Training") test_data_directory = os.path.join(ROOT_PATH, "TrafficSigns/Testing") images, labels = load_data(train_data_directory) A quick note, I am loading images from within the TrafficSign folder (which contains the two folders, Training and Testing).
has comment: http://stackoverflow.com/comment/84799659
score: -1
has answer: http://stackoverflow.com/a/48897030
answer count: 1
downvote count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84799771
has title: Unsure how .join() functions with two parameters
type: UnansweredQuestion
tagged with: python
upvote count: 0
tagged with: join
has comment: http://stackoverflow.com/comment/84799878

http://stackoverflow.com/a/48815963
has body: Looks like you want to implement an autoencoder since you pass the same values for inputs and targets. The lstm at the input is expecting 3 dimensions as (batch_size,sequence_length,features)and the output is just two dimensions (batch_size,features)because of return_sequences=False. Only the last element of the sequence is returned by the lstm. If you want a output of the whole sequence use: x = Input(shape=(784,1,),name='input') h = LSTM(128,return_sequences=True,name='lstm')(x) z = TimeDistributed(Dense(2),name='z_mu')(h) x_pred = TimeDistributed(Dense(128, input_dim=latent_dim, activation='relu'),name='seq_1')(z) x_pred = TimeDistributed(Dense(original_dim, activation='sigmoid'),name='seq_2')(x_pred) model = Model(inputs=[x, eps], outputs=x_pred) model.compile(optimizer='rmsprop', loss='categorical_crossentropy') vae.summary() This should work. Note, that since the lstm is now returning sequences you need something like TimeDistributed layers to copy the Dense layers along time. Another solution would be using Lambda layers to reshape the lstm output. In the end it depends on what you want to achieve. If you give more details I can comment on which structure to use.
score: 1
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84636896
answers question: http://stackoverflow.com/q/48815350
has comment: http://stackoverflow.com/comment/84636348
type: Answer
has comment: http://stackoverflow.com/comment/84636996

http://stackoverflow.com/q/48948290
tagged with: rotation
tagged with: dicom
answer count: 1
favorite count: 0
score: 0
accepted answer: http://stackoverflow.com/a/48978704
tagged with: python
has body: I have a huge data text file. I plot these data on a CT image which results can be seen on the below image. But how could I rotate my dose data axis to be same with my CT image ? My code so far: %matplotlib notebook import numpy as np import dicom import matplotlib.pyplot as plt from itertools import islice import matplotlib.colors as colors import matplotlib.cm as cm data = dicom.read_file("NEW.dcm") plt.set_cmap("gray") pixel_array = data.pixel_array plt.pcolormesh(pixel_array) plt.gca().set_aspect("equal") plt.show() CS=plt.contour(xi,yi,zi,cmap=plt.cm.jet) import numpy as np import matplotlib.pyplot as plt a = np.loadtxt('New.txt') i = a[:,1] j = a[:,2] energies = a[:,3] xi = np.linspace(i.min(), i.max()) yi = np.linspace(j.min(), j.max()) zi = scipy.interpolate.griddata((i, j), energies, (xi[None,:], yi[:,None]), method='cubic') fig = plt.figure() CS=plt.contour(xi, yi, zi,colors='k', norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) CS = plt.contourf(xi,yi,zi,15,cmap=plt.cm.jet) Data extract 30 1 2 0.00951305 30 1 3 0.0110269 30 1 4 0.0141366 30 1 5 0.00468656 30 1 6 0.0144487 30 1 7 0.0253241 30 1 8 0.0239877 30 1 9 0.0175475 30 1 10 0.0134009 … (Full code and data available here) Thanks you.
upvote count: 2
has comment: http://stackoverflow.com/comment/84905258
downvote count: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84902910
has title: Contour data rotation in python in dicom image
tagged with: matplotlib
has answer: http://stackoverflow.com/a/48978704
type: Question

http://stackoverflow.com/comment/84627246
has text: @ZaxR Yep sure, but I'm pretty sure that'd be slower than just list multiplication and concatenation.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48811504
type: AnswerComment

http://stackoverflow.com/q/48904835
has comment: http://stackoverflow.com/comment/84842520
has comment: http://stackoverflow.com/comment/84820609
has title: High Speed-High Resolution Image Capture with Raspberry Pi 3 Model B (and Pi Camera)
type: Question
tagged with: camera
has comment: http://stackoverflow.com/comment/84842011
has answer: http://stackoverflow.com/a/48904915
has comment: http://stackoverflow.com/comment/84842706
score: 0
answer count: 1
tagged with: raspberry-pi3
favorite count: 0
type: UnansweredQuestion
has body: Is there a way to lessen the time taken by the raspberry pi 3 in capturing at least 1 image while being on the move? It’s like point and shoot setup. Currently, what I have is that the raspberry pi 3 takes at least 2-3secs to capture 1 image with the 8-megapixel pi-camera (read-write). Since the raspberry pi is attach on a drone, being on the move while taking photo causes a blurry output (the ave. speed of the drone is around 4.5ft/sec), I can still slow it down depending in your advice. I only need to take 1 image once my object of interest is spotted. As much as possible I don't want to sacrifice the quality of the image since I'll be using it for another analysis. I'm hoping that you can give me direction on this one. Thanks in advance!
upvote count: 1
tagged with: python
downvote count: 1
tagged with: opencv

http://stackoverflow.com/comment/116489463
comment on: http://stackoverflow.com/q/48805188
score: 0
type: Comment
type: QuestionComment
has text: I think you can find the answer why there is only one legend item [here](https://discourse.bokeh.org/t/cant-order-legend-entries-in-hbar-plot/3816/5).

http://stackoverflow.com/a/48858428
accepted answer of: http://stackoverflow.com/q/48855930
upvote count: 1
answers question: http://stackoverflow.com/q/48855930
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84727731
has body: If leaf_cleaned is a boolean-array like used for masks, you can just do: image[~leaf_cleaned] = 0 which follows numpy's boolean-indexing docs. Keep in mind, that sklearn is heavily based on numpy! So numpy's docs are often relevant!
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/84748060
comment on: http://stackoverflow.com/q/48872113
has text: `A` and `B` refer to the same backing data. Actually, in this case it's even stronger: they refer to the same *object!*
type: Comment
type: QuestionComment
score: 2

http://stackoverflow.com/comment/84680297
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48837781
has text: data = request.form.to_dict() might be easier

http://stackoverflow.com/a/48931044
has comment: http://stackoverflow.com/comment/84967802
has comment: http://stackoverflow.com/comment/84890704
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84989550
downvote count: 0
has comment: http://stackoverflow.com/comment/84890778
has comment: http://stackoverflow.com/comment/84911453
has comment: http://stackoverflow.com/comment/84912618
accepted answer of: http://stackoverflow.com/q/48918639
has body: This emulates the input you are showing in your screenshot: import pandas as pd import numpy as np df = pd.DataFrame({"type": ["a", "c", "d", "a", "b", "a", "a", "c"], "tags": ["col_t1, col_red, large", np.nan, "col_t2, col_black, small", "col_t4, large, col_yellow", "col_gold, col_fancy,", "col_t1, thick, col_k", np.nan, "col_t3, fancy, red"], "theme": ["t2", "t1", "t2", "t3", "t2", "t1", np.nan, "t3"]}) df.set_index(np.arange(1, len(df)+1), inplace=True) print df Output: tags theme type 1 col_t1, col_red, large t2 a 2 NaN t1 c 3 col_t2, col_black, small t2 d 4 col_t4, large, col_yellow t3 a 5 col_gold, col_fancy, t2 b 6 col_t1, thick, col_k t1 a 7 NaN NaN a 8 col_t3, fancy, red t3 c Code that produces the desired output: prefix = "col_" # Iterate over rows with non-empty theme for row in df[df["theme"].notnull()].itertuples(): if pd.isnull(row.tags): # Replace NaN in tags column with a single tag from theme column df.loc[row.Index, "tags"] = prefix + row.theme else: # Extract existing tags with prefix inferred_tags = [t.replace(prefix, "") for t in row.tags.split(",") if prefix in t] if row.theme not in inferred_tags: df.loc[row.Index, "tags"] = row.tags.rstrip(" ,") + ", " + prefix + row.theme print df Output: tags theme type 1 col_t1, col_red, large, col_t2 t2 a 2 col_t1 t1 c 3 col_t2, col_black, small t2 d 4 col_t4, large, col_yellow, col_t3 t3 a 5 col_gold, col_fancy, col_t2 t2 b 6 col_t1, thick, col_k t1 a 7 NaN NaN a 8 col_t3, fancy, red t3 c Hopefully this is what you are looking for. itertuples() is claimed to be faster for iterating over all rows than iterrows(). Also, keep in mind that I used numpy and specifically np.nan to emulate NaNs in your input, but if your data comes from csv, you won't need numpy. --- UPDATE --- As explained in the comments, the code should replace tags that match themes. Here is the updated solution: prefix = "col_" # Find all unique themes (notnull() excludes nan from the list) themes = df[df["theme"].notnull()]["theme"].uniqu…
answers question: http://stackoverflow.com/q/48918639
type: Answer
score: 1

http://stackoverflow.com/q/48954908
tagged with: pycharm
answer count: 0
has comment: http://stackoverflow.com/comment/84916938
linked to: http://stackoverflow.com/q/36137671
downvote count: 1
type: Question
score: 5
has title: PyCharm keeps throwing "Memory Error" even after heap size increase/reset
has comment: http://stackoverflow.com/comment/84917175
has body: So I have this script, using pandas dataframe mostly to deal with my data. The script works when I process about 10 days worth of data; but if I do 11 days worth of data, it'll start complaining "MemoryError". I've read through almost all the posts I think are relevant. Sample ones that I feel like are most related: PyCharm Running Out of Memory https://superuser.com/questions/919204/how-can-i-increase-the-memory-heap-in-pycharm/1141412#1141412?newreg=8c1cf6510b64441a987d6ef0e0cab23d http://web.archive.org/web/20160503095110/http://www.avricot.com/blog/?post/2010/05/03/Get-started-with-java-JVM-memory-(heap,-stack,-xss-xms-xmx-xmn...) I've changed my max heap size to 1024 (according to above posts, 1024 is the maximum?) and I've also increased the min to 256 (it was 1/2 of that originally). Specs about my laptop: 32GB RAM. CPU = 2 cores max speed = 2.81GHz Logical processors = 4 When I run the program/script, I do not see spike in memory consumption; it's pretty steady... so I'm now confused. But I do see a lot spikes in CPU consumption. Could that be a problem? Any help is appreciated!
has comment: http://stackoverflow.com/comment/84960831
favorite count: 0
has comment: http://stackoverflow.com/comment/84917224
tagged with: out-of-memory
type: UnansweredQuestion
tagged with: python
upvote count: 6

http://stackoverflow.com/comment/84747368
comment on: http://stackoverflow.com/a/48871150
has text: @jp_data_analysis I promise you I'm not getting defensive. Tone is lost in comments and chat and other such medium. When I comment to people I don't know, I try to be as matter of fact as I can. Among those I'm more familiar, I may attempt humor. But if you read my comment again, take out the tone and all that's left is me being honest about my choices. I suspect I'll see you answering quite a few questions. I'd rather we understand each other and together we all can be more helpful to the community... Til the next question (-:
type: Comment
type: AnswerComment
score: 0

http://stackoverflow.com/a/48869318
answers question: http://stackoverflow.com/q/48869292
upvote count: 2
has body: Try this: mask = df.reg_region == df.live_region df.loc[mask, 'city_reg'] = df.loc[mask, 'city_live'] # city_reg city_live reg_region live_region # 0 Moscow Tver 77 69 # 1 Tumen' Tumen' 86 86 The reason this works is that the indices are aligned between the left and right hand sides of the assignment when you apply the same mask.
type: Answer
score: 2
downvote count: 0

indentation
tags question: http://stackoverflow.com/q/48880847
tags question: http://stackoverflow.com/q/48812562
tag name: indentation
tags question: http://stackoverflow.com/q/48940994
type: Tag

http://stackoverflow.com/comment/84679980
type: AnswerComment
type: Comment
has text: ends with a space? I want it to end with \? thats what your code does though right?
comment on: http://stackoverflow.com/a/48837633
score: 0

http://stackoverflow.com/comment/84622018
has text: @Coder, please put a sample input and desired data sets into your question...
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48809276

http://stackoverflow.com/comment/84699498
type: AnswerComment
comment on: http://stackoverflow.com/a/48847671
score: 0
type: Comment
has text: Then you should be good if you ensure hashes you get for them don't use whitespaces.

http://stackoverflow.com/comment/84968570
comment on: http://stackoverflow.com/a/48919441
score: 0
type: Comment
has text: Im really new to python so the things you first mentioned didnt make much sense but the last one made sense thank you.
type: AnswerComment

http://stackoverflow.com/a/48877735
type: Answer
score: 2
has body: Option 1 Use filter + tolist. You don't need the apply here. df.filter(regex='.*Date$').values.tolist() [['1997-06-30', '2006-06-13', '1996-06-14'], ['1997-05-31', '2006-06-13', '1996-06-14']] Option 2 Alternatively, using str.endswith + loc: df.loc[:, df.columns.str.endswith('Date')].values.tolist() [['1997-06-30', '2006-06-13', '1996-06-14'], ['1997-05-31', '2006-06-13', '1996-06-14']] Option 3 Column indexing df'Current Date', 'End Date', 'Begin Date'.values.tolist() [['1997-06-30', '2006-06-13', '1996-06-14'], ['1997-05-31', '2006-06-13', '1996-06-14']]
upvote count: 2
has comment: http://stackoverflow.com/comment/84777062
answers question: http://stackoverflow.com/q/48877547
downvote count: 0

http://stackoverflow.com/a/48879608
answers question: http://stackoverflow.com/q/48879453
type: Answer
has body: You could try this: " ".join('@#'.join([e for e in tokens if '&lt;/' not in e]).replace("&lt;h1&gt;","\n Heading:").replace("&lt;p&gt;","\n Paragraph:").split("@#")) Given that your string doesn't have a @#.
score: 0

http://stackoverflow.com/comment/84916012
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48954515
has text: Your concise version is what I would recommend. Don't mess with a list as you iterate through it, just create a new one.
score: 0

http://stackoverflow.com/comment/84752236
type: Comment
comment on: http://stackoverflow.com/q/48858829
score: 0
has text: Thankyou, I'll try and let you know
type: QuestionComment

http://stackoverflow.com/q/48849745
tagged with: python
linked to: http://stackoverflow.com/q/38796548
duplicate of: http://stackoverflow.com/q/38796548
type: Question
tagged with: numpy
has title: operands could not be broadcast together with shapes - Subtracting series from each row in a dataframe
has comment: http://stackoverflow.com/comment/84703088
has comment: http://stackoverflow.com/comment/84703127
score: 0
tagged with: pandas
answer count: 0
has comment: http://stackoverflow.com/comment/84703125
type: UnansweredQuestion
has body: 0 21 1 305 2 100 3 0 4 196 5 10 6 959 7 705 8 20 9 49 Name: 0, dtype: object I'm trying to subtract the above series from each row in this dataframe below. 0 1 2 3 4 5 6 7 8 9 0 69 320 127 164 211 6 721 723 2 20 1 85 140.2 44.8 234.9 171.3 5.5 1047.6 704 23.5 52.5 2 36 275 99 127 184 13 810 790 25.75 64.5 3 10 304 0 140 214 6 895 722 19 51 4 46 318 126 0 210 6 861 737 17.5 48 This doesn't seem to work for index, row in test.iterrows(): print(row.iloc[:-1]) print(X.head(5)) print((X.sub(row.iloc[:-1], axis=1))) ValueError: operands could not be broadcast together with shapes (930,) (10,)

http://stackoverflow.com/comment/85210933
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48862172
has text: Thank you very much for taking the time. Not only do both parts of your answer (generating xx and comparing it against y) stay inside NumPy, timeit() shows they're *significantly* faster than the other options here. In fact, both aspects of your solution appeared to be over an order of magnitude faster than many of the other possibilities when I scaled my y up to hundreds of thousands of sequences and x to over 1 million possibilities. Well written as the other options here may be, Python has its bottlenecks.

http://stackoverflow.com/q/48930933
tagged with: python
has title: Convert Estimator to TPUEstimator
upvote count: 4
type: AnsweredQuestion
downvote count: 0
tagged with: tensorflow
type: Question
tagged with: keras
score: 4
tagged with: tensorflow-estimator
has body: Is it possible to convert an Estimator to a TPUEstimator in TensorFlow without significant effort in rewriting its functions? I have a model in Estimator form that works nicely on a CPU, but I don't know a convenient way to convert it to a TPUEstimator without having to rewrite the model_fn and input_fn. The reason this requires significant work to do manually is that I am using Keras to create my model, and then the following helper function to create the Estimator: my_keras_model.compile( optimizer=tf.keras.optimizers.SGD(lr=0.0001, momentum=0.9), loss='categorical_crossentropy', metric='accuracy') estimator = tf.keras.estimator.model_to_estimator(keras_model=my_keras_model) It would be great if I could do something like estimator.to_TPU_estimator() or something like that -- perhaps someone knows of a solution?
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48996293
accepted answer: http://stackoverflow.com/a/48996293
tagged with: machine-learning

http://stackoverflow.com/a/48881395
type: Answer
has comment: http://stackoverflow.com/comment/84768475
has body: the setUp functions is called before each test so yeah you have the vader entry in your db (because you request conversation_id=4 which exists since setUp was called before testing). That said, casting to bool doesn't make a lot of sense, if your trying to see if you have the entry or not you should user : self.assertIsNone(vader) or self.assertTrue(vader is None) This way you know exactly what you are testing
has comment: http://stackoverflow.com/comment/84769266
has comment: http://stackoverflow.com/comment/84777748
upvote count: 4
has comment: http://stackoverflow.com/comment/84770545
downvote count: 0
has comment: http://stackoverflow.com/comment/84768553
score: 4
answers question: http://stackoverflow.com/q/48881296
has comment: http://stackoverflow.com/comment/84767753
has comment: http://stackoverflow.com/comment/84770057

http://stackoverflow.com/q/48847927
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
has title: Need help writing to a CSV file Python 3.5
has answer: http://stackoverflow.com/a/48847950
upvote count: 1
answer count: 1
has body: My code writes to a CSV file titled 'output' here is a link to past help on this code When I run my code my CSV file is being rewritten over in the body row. I want to write to a new row every time there is new information being scraped from the table of the stock table URL. Here is what my CSV file looks like: Index,P/E,EPS (ttm),Insider Own,Shs Outstand,Perf Week,Market Cap,Forward P/E,EPS next Y,Insider Trans,Shs Float,Perf Month,Income,PEG,EPS next Q,Inst Own,Short Float,Perf Quarter,Sales,P/S,EPS this Y,Inst Trans,Short Ratio,Perf Half Y,Book/sh,P/B,EPS next Y,ROA,Target Price,Perf Year,Cash/sh,P/C,EPS next 5Y,ROE,52W Range,Perf YTD,Dividend,P/FCF,EPS past 5Y,ROI,52W High,Beta,Dividend %,Quick Ratio,Sales past 5Y,Gross Margin,52W Low,ATR,Employees,Current Ratio,Sales Q/Q,Oper. Margin,RSI (14),Volatility,Optionable,Debt/Eq,EPS Q/Q,Profit Margin,Rel Volume,Prev Close,Shortable,LT Debt/Eq,Earnings,Payout,Avg Volume,Price,Recom,SMA20,SMA50,SMA200,Volume,Change -,-,-3.00,45.18%,5.19M,30.47%,15.78M,-,-,0.00%,2.84M,-16.48%,-14.00M,-,-,1.00%,9.24%,88.82%,18.30M,0.86,-122.00%,136.99%,0.26,88.82%,27.27,0.11,-,-,4.00,-51.44%,0.87,3.51,15.00%,-,1.30 - 8.00,-27.10%,-,-,-15.40%,0.40%,-62.00%,2.73,-,1.10,-16.40%,25.10%,133.85%,0.52,450,1.20,-58.50%,-,53.21,19.81% 17.08%,No,0.37,-,-,5.40,2.96,Yes,0.13,-,-,991.40K,3.04,3.00,1.72%,-6.24%,29.44%,"5,358,503",2.70% Here is my code: import csv import urllib.request from bs4 import BeautifulSoup twiturl = "https://twitter.com/ACInvestorBlog" twitpage = urllib.request.urlopen(twiturl) soup = BeautifulSoup(twitpage,"html.parser") print(soup.title.text) tweets = [i.text for i in soup.select('a.twitter-cashtag.pretty-link.js-nav b')] print(tweets) url_base = "https://finviz.com/quote.ashx?t=" url_list = [url_base + tckr for tckr in tweets] for url in url_list: fpage = urllib.request.urlopen(url) fsoup = BeautifulSoup(fpage, 'html.parser') #scrape single page and add data to list #write datalist with open('output.csv', 'wt') as file: writ…
linked to: http://stackoverflow.com/q/48837007
downvote count: 0
type: UnansweredQuestion
score: 1

http://stackoverflow.com/q/48958015
answer count: 1
has answer: http://stackoverflow.com/a/48958394
accepted answer: http://stackoverflow.com/a/48958394
has comment: http://stackoverflow.com/comment/84923314
favorite count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84923728
has comment: http://stackoverflow.com/comment/84923370
has title: IndexError: string index out of range, when iterating over dict of lists
has body: I'm sorry if this should be considered a duplicate, I went over several other questions and couldn't locate the mistake because it is probably to special to my case... I know the problem is somewhere here, I'm using this to draw each char in a dictionary: Edit: Alright, this was to abstract for a concrete example, I don't know where it's going wrong, so I'll post the whole code: import pygame, random, time, sys, string, itertools check_errors = pygame.init() ################### Main Variables ###################### PSwith = 460 PSheight = 460 playSurface = pygame.display.set_mode((PSwith, PSheight)) rowsCount = int(PSwith/10 - 1) columnsCount = int(PSheight/10 - 1) print('rows: ', rowsCount) print('columns: ', columnsCount) alphabet = list(string.ascii_letters + string.punctuation + string.digits) red = pygame.Color(255,0,0) blue = pygame.Color(0,0,255) green = pygame.Color(0,255,0) white = pygame.Color(255,255,255) black = pygame.Color(0,0,0) defaultColor = green activeColor = white fpsController = pygame.time.Clock() ################### Important Functions ###################### def drawChar(char, x, y, color): CharFont = pygame.font.SysFont('hermit', 15) CharSurf = CharFont.render(char, True, color) CharRect = CharSurf.get_rect() CharRect.midtop = (x, y) playSurface.blit(CharSurf, CharRect) CharPosMatrix = [] CharLibrary = [] def setCharPos(row): for column in range(1, int(PSwith/10)): CharPosMatrix.append((column*10, row*10)) for row in range(1, int(PSheight/10)): setCharPos(row) print('CharPosMatrix: ', CharPosMatrix) print('len CharPosMatrix:', len(CharPosMatrix)) ### assembling char library, with default color ### for i in range(rowsCount * columnsCount): CharLibrary.append([random.choice(alphabet), defaultColor]) print('CharLibrary: ', CharLibrary) print('len CharLibrary:', len(CharLibrary)) #MatrixDict = dict(zip(CharLibrary, CharPosMatrix)) MatrixDict = dict(zip(CharPosMatrix,CharLibrary)) #zipping each character with a x,y coord print('MatrixDict: ', Matr…
has comment: http://stackoverflow.com/comment/84922983
has comment: http://stackoverflow.com/comment/84923088
tagged with: python
type: AnsweredQuestion
downvote count: 0
has comment: http://stackoverflow.com/comment/84922979
score: 1
type: Question

http://stackoverflow.com/q/48935938
tagged with: blender
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84907622
has body: The basic question is how to write a simple script that copies one vertex position to another vertex and mirrors one axis, as well as copying and mirroring all vertex weights if possible. Two selected vertices should be mirrored, but due to user error, are slightly off and break the mirror symmetry in edit mode. I have tried using the symmetrize function already in blender, but this breaks weight painting values for the model and leaves duplicate vertices behind. Manually copying every x,y,z position and vertex weight is not efficient at all.
tagged with: 3d-modelling
type: UnansweredQuestion
tagged with: scripting
tagged with: python
score: 2
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84937755
type: Question
has title: Blender: Copy active vertex position to selected vertex position and mirror axis

http://stackoverflow.com/comment/84687751
has text: How about using [this](http://docs.python-requests.org/en/master/) package?
score: 0
comment on: http://stackoverflow.com/q/48841889
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48907573
type: Question
has title: Displaying requests module logging messages whilst using a .yaml config file for logging module
accepted answer: http://stackoverflow.com/a/48928069
tagged with: python
upvote count: 1
answer count: 1
tagged with: logging
type: AnsweredQuestion
tagged with: yaml
downvote count: 0
has answer: http://stackoverflow.com/a/48928069
has body: How might I display the requests module logging messages whilst using a .yaml file to configure the logging module? Previously I have used the following to display logging output from requests, but I'm now lost: logging.basicConfig( level=logging.DEBUG, format="%(asctime)s - %(levelname)s - %(message)s") #logging.disable(logging.CRITICAL) My .yaml file, which has replaced the above code: version: 1 disable_existing_loggers: False handlers: console: class: logging.StreamHandler stream: ext://sys.stderr formatter: basic audit_file: class: logging.FileHandler filename: bot_log.logging encoding: utf-8 formatter: basic formatters: basic: style: "{" format: "{asctime:s} {levelname:s}: {name:s}: {message:s}" datefmt: "%Y-%m-%d %H:%M:%S" loggers: verbose: handlers: [console] level: DEBUG propagate: False audit: handlers: [audit_file] level: DEBUG root: handlers: [console] level: INFO How I now load and configure the logging in my application: if __name__ == "__main__": with LoggingConfig(): with TradeHub() as th: th.run()
score: 1
favorite count: 0

binary-tree
tag name: binary-tree
type: Tag
tags question: http://stackoverflow.com/q/48875318
tags question: http://stackoverflow.com/q/48957140
tags question: http://stackoverflow.com/q/48850446

http://stackoverflow.com/q/48866753
score: 1
accepted answer: http://stackoverflow.com/a/48942162
answer count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48942162
has title: How to execute a Python script in Node.js with sudo privillege
favorite count: 0
tagged with: python
tagged with: node.js
has comment: http://stackoverflow.com/comment/84736859
has comment: http://stackoverflow.com/comment/84737610
possible better answer: http://stackoverflow.com/a/48867119
downvote count: 0
has answer: http://stackoverflow.com/a/48867119
has comment: http://stackoverflow.com/comment/84737926
has body: The script create some files in directories which need sudo permissions and executes few command that also need sudo privillage. I want to execute that script giving sudo privillage. Is there any way to do that ? I am trying to execute it with python-shell module as well as spawn child process.
type: Question
type: AnsweredQuestion

http://stackoverflow.com/a/48948077
score: 0
has comment: http://stackoverflow.com/comment/84904385
type: Answer
has comment: http://stackoverflow.com/comment/84903906
has comment: http://stackoverflow.com/comment/84903829
answers question: http://stackoverflow.com/q/48947770
has body: First: Your command does not do anything. It is cmd /C C:\Users\Documents\TEST.py which does nothing but tell you that C:\Users\Documents\TEST.py is not a command. You would need to call cmd /C start C:\Users\Documents\TEST.py for it to do something. Still this won't make your code work. The problem here is that you are invoking a cmd in there you start a python process. When you now grab the input stream you are getting the cmd input stream which is not the one you are looking for. In order to get it to work invoke python directly by calling python C:\Users\Documents\TEST.py. Make sure python is in your PATH for this to work. Your code should then look something like this: try { ProcessBuilder py = new ProcessBuilder("python", "C:\\Users\\Documents\\TEST.py"); String readLine; Process launch = py.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(launch.getInputStream())); while ((readLine = reader.readLine()) != null) { System.out.println(readLine); } } catch (IOException ex) { Logger.getLogger(Template.class.getName()).log(Level.SEVERE, null, ex); } This gives you exactly the result you were looking for.

http://stackoverflow.com/comment/84711622
comment on: http://stackoverflow.com/q/48854040
type: Comment
has text: `for x in ti` is trying to iterate `ti` - but it is a float, not an iterable.
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84628464
type: QuestionComment
type: Comment
has text: update your question with the code
comment on: http://stackoverflow.com/q/48812379
score: 0

http://stackoverflow.com/q/48855680
has comment: http://stackoverflow.com/comment/84714878
has comment: http://stackoverflow.com/comment/84714844
has comment: http://stackoverflow.com/comment/84714958
upvote count: 0
has answer: http://stackoverflow.com/a/48855729
accepted answer: http://stackoverflow.com/a/48855729
answer count: 1
has comment: http://stackoverflow.com/comment/84714822
score: -6
favorite count: 0
tagged with: python
downvote count: 6
type: AnsweredQuestion
has body: def vector(sample_list): for item in sample_list: sums = 0 square = item**2 sums = square + sums magnitude = sums**0.5 return magnitude print(vector([2,3,-4])) Why this code doesn't give the correct magnitude? It gives the last value of the vector in function call.
has title: What's wrong in this python code?
type: Question

http://stackoverflow.com/a/48837443
upvote count: 17
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84681384
has comment: http://stackoverflow.com/comment/84681404
has comment: http://stackoverflow.com/comment/84698278
accepted answer of: http://stackoverflow.com/q/48837384
has body: Use an extra comma in your tuples, and just join: a = ((1,1,1),) for i in range(2,10): a = a + ((i,i,i),) Edit: Adapting juanpa.arrivillaga's comment, if you want to stick with a loop, this is the right solution: a = [(1,1,1)] for i in range (2,10): a.append((i,i,i)) a = tuple(a)
type: Answer
answers question: http://stackoverflow.com/q/48837384
score: 17

http://stackoverflow.com/comment/84919604
has text: Your classmethod example doesn't work because y, as the first argument in squarethencube() is being considered ```self``` and the x***2 in square() is trying to square a class. You should either change both instances of y to ```self.x``` to use the value stored on __init__ or, add change the definition to ```def squarethencube(self, y)``` to allow y to be passed in as an argument
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48956231
type: AnswerComment

http://stackoverflow.com/q/48953247
tagged with: python
type: AnsweredQuestion
tagged with: set
type: Question
has body: Given some set of tuples (x,y): set([(1,2),(3,4),(3,2),(1,4)]) How do I find each tuple with the property (1,z) in the set? In this example the edges (1,2),(1,4). EDIT: Is there some other data structure that would support such a request?
has answer: http://stackoverflow.com/a/48953270
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48953270
has title: How to find some specific element in a set?
has comment: http://stackoverflow.com/comment/84913245

http://stackoverflow.com/comment/84849657
type: QuestionComment
type: Comment
has text: ok...for example bmm = tki.Button(self.root, text="name!",command = )...what is it in blank in command??
comment on: http://stackoverflow.com/q/48920136
score: 0

http://stackoverflow.com/comment/84702163
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48848869
type: QuestionComment
has text: first correct your indentation in program...

http://stackoverflow.com/comment/84873374
score: 1
type: AnswerComment
type: Comment
has text: Maybe `k.rsplit('.', 1)` is better?
comment on: http://stackoverflow.com/a/48933282

http://stackoverflow.com/q/48839381
has comment: http://stackoverflow.com/comment/84684811
favorite count: 0
has comment: http://stackoverflow.com/comment/84683537
has title: dataframe value modification randomly
type: UnansweredQuestion
tagged with: python
has body: Assume we have the following: df = pd.DataFrame({'1':[0.1,0.2,0.05,0.6],'2':[0.2,0.4,0.1,0.06],'3':[0.5,0.4,0.05,0.1]}) or: 1 2 3 0 0.10 0.20 0.50 1 0.20 0.40 0.40 2 0.05 0.10 0.05 3 0.60 0.06 0.10 Sum of columns are 0.95, 0.76, 1.05. The desired summation is 1. The goal: make every column add up to 1. Some of the columns add to a number greater than one and some to a number smaller than one. Constraint: Add or subtract only from one member in each column. Desired output: The output should be something like this: 1 2 3 0 0.15 0.20 0.50 1 0.20 0.40 0.40 2 0.05 0.10 0.05 3 0.60 0.30 0.05 Sum of all columns are now 1. However, only one element in each column has changed. My efforts: My plan has been to calculate how much a column is more/less than one as follows: 1-df.sum(axis=0) which returns: 1 0.05 2 0.24 3 -0.05 dtype: float64 This will give us a series that contain the difference of each element and one. I can select a random element of each column by: df.apply(lambda x: x.sample(1)) which returned (YMMV since it is random selection): 1 2 3 1 NaN 0.4 NaN 2 0.05 NaN NaN 3 NaN NaN 0.1 Now I cannot figure out how to add these values to a random member of each column. Any help is greatly appreciated.
has answer: http://stackoverflow.com/a/48839834
has comment: http://stackoverflow.com/comment/84683596
has answer: http://stackoverflow.com/a/48843328
upvote count: 3
has comment: http://stackoverflow.com/comment/84683568
type: Question
score: 3
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84683353
answer count: 2
tagged with: pandas
downvote count: 0

http://stackoverflow.com/a/48841110
score: 0
type: Answer
has body: cr always 5000 times 2 ( cmqm) i guess it should be like im*qm or other else
answers question: http://stackoverflow.com/q/48840881

http://stackoverflow.com/a/48899515
has body: I would say it depends on your infrastructure and how can the other application (C#) can communicate. The easiest way in my opinion would be through a REST API (http request). There are some tools in different languages to create REST endpoints easily and request REST endpoints. For example, in python, you can request the content of a URL like this: What is the quickest way to HTTP GET in Python? But it depends on what you have on the C# side. Can you update the C# code? Here are a range of solutions: REST API: need to expose REST endpoints on the communicating "service". in C#: https://learn.microsoft.com/en-us/aspnet/web-api/overview/older-versions/build-restful-apis-with-aspnet-web-api in python, I would recommend django framework if you need to create a server (but if the python only request things and don't serve as a server, you may not need it) message queue like rabbitmq or zeromq, but it requires an external service to manage queues and messages TCP/IP socket like you suggested, but it requires to manage yourself those connections
upvote count: 1
answers question: http://stackoverflow.com/q/48899303
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/84765814
type: QuestionComment
score: 0
has text: You want to convert a and not b into a boolean expression
type: Comment
comment on: http://stackoverflow.com/q/48880819

http://stackoverflow.com/comment/137477237
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/77981263
has text: Method 3 is what I would recommend. Note the that generator expression isn't necessary; `lambda l: zip(range(...), reversed(l))` is equivalent.

http://stackoverflow.com/q/48820947
answer count: 1
has title: python data scraping change currency
tagged with: screen-scraping
upvote count: 1
has body: I am trying to fetch bitcoin and ethereum historical price from coinmarketcap.com using the below script from page https://coinmarketcap.com/currencies/bitcoin/historical-data/?start=20130428&amp;end=20180216: import requests import xlwt import traceback import pandas as pd import urllib.request as req from bs4 import BeautifulSoup from pandas import ExcelWriter def process_data(data, coin, workbook): try: sheet = workbook.add_sheet(coin) soup = BeautifulSoup(data, 'lxml') table = soup.find_all('table')[0] df = pd.read_html(str(table)) k = (df[0].to_json(orient='records')) import json resp = json.loads(k) # resp format: {'Date': 'Apr 28, 2013', 'Open': 135.3, 'High': 135.98, 'Low': 132.1, 'Close': 134.21, 'Volume': '-', 'Market Cap': 1500520000} lst = [[each['Date'], each['Open'], each['High'], each['Low'], each['Close'], each['Volume'], each['Market Cap']] for each in resp] for i, l in enumerate(lst): for j, col in enumerate(l): sheet.write(i, j, col) except Exception as e: print (e) print(traceback.print_exc()) coins = ['Bitcoin', 'Ethereum'] workbook = xlwt.Workbook(encoding='ascii') if __name__ == '__main__': for each in coins: coin = each.lower() url = "https://coinmarketcap.com/currencies/"+ coin + "/historical-data/?start=20090428&amp;end=20180207" print (url) try: a = requests.get(url) process_data(a.text, each, workbook) except Exception as e: print 'error in fetching data', coin workbook.save('cmc_data_f.xls') The script gets the html response from the page and write to an excel file. The problem is the webpage is returning data in USD by default. I want the data in EURO. On the website there is a drop down to choose from multiple currencies. But when I send the request from python it is returning USD by default. Does anyone know if there a way to request webpage in EURO currency from coinmarketcap.com?
downvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48821571
score: 1
favorite count: 0
tagged with: beautifulsoup
type: Question
tagged with: web-scraping
tagged with: python

http://stackoverflow.com/comment/84927932
comment on: http://stackoverflow.com/a/48953816
score: 0
type: AnswerComment
has text: Thanks, I actually have a scenario where i need to find all connected devices on my subnet and start the req-recv for the clients. So, I am confused about how to tackle this and i thought of using two threads, one to handle udp broadcast and one to do req-rep pattern. Do you suggest any idea?
type: Comment

http://stackoverflow.com/q/48819053
has body: I got an error,NoReverseMatch at /app/index. I wrote in views.py def index(request): return render(request, 'index.html') def test1(request): return render(request, 'test1.html') def test2(request): return render(request, 'test2.html') in urls.py app_name = "app" urlpatterns = [ path('index', views.index,name='index'), path('test1', views.test1,name='test1'), path('test2', views.test2,name='test2'), ] in index.html test1 test2 When I access index method, NoReverseMatch at /app/index Reverse for 'test1' not found. 'test1' is not a valid view function or pattern name. error happens. I rewrote test1 but same error happens. I really cannot understand why I got this error.I already test1&test2 url.How should I fix this? Traceback says Traceback (most recent call last): File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrmymyapped_callback(request, *callback_args, **callback_kwargs) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrmymyapped_view return view_func(request, *args, **kwargs) File "/Users/xxx/Downloads/mymyapp/myapp/views.py", line 166, in kenshinresults return render(request, 'index.html') File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/Users/xxx/anaconda/envs/py36/lib/python3.6/site-pa…
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/49062602
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84643407
linked to: http://stackoverflow.com/q/38390177
type: Question
has answer: http://stackoverflow.com/a/48822138
upvote count: 2
has comment: http://stackoverflow.com/comment/84646450
has comment: http://stackoverflow.com/comment/84647350
answer count: 2
has comment: http://stackoverflow.com/comment/84646403
has title: NoReverseMatch at /app/index I already URL
favorite count: 0
has comment: http://stackoverflow.com/comment/84643633

ubuntu-server
type: Tag
tag name: ubuntu-server
tags question: http://stackoverflow.com/q/48924590

http://stackoverflow.com/a/48850088
has body: They are both correct. One uses flask-sqlalchemy the other just uses 'raw' sqlalchemy. The advantages of 'pure' sqlalchemy is that the models can more easily be used outside of the flask application. If you are not planning on using them outside flask, just stick with the method described in the flask-sqlalchemy docs as it will save you a lot of time and effort. Flask sqlalchemy is just a lightweight extension to make it easier to integrate sqlalchemy with flask. Simply put, it handles the database connection code integrated with flask requests, and adds some convenient functionalities, for. Instance, access Model, Column, session, engine, and other useful sqlalchemy classes directly from the db object
has comment: http://stackoverflow.com/comment/84704408
score: 0
answers question: http://stackoverflow.com/q/48846288
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48846288
type: Answer

http://stackoverflow.com/q/48911572
has answer: http://stackoverflow.com/a/66509649
type: AnsweredQuestion
downvote count: 0
score: 7
has body: In seaborn using sns.set() seems to be changing the background color of the plot. import matplotlib import matplotlib.pyplot as plt import seaborn as sns import pandas as pd df = pd.DataFrame({"type":["A", "A", "A", "A", "B", "B", "B", "B"], "value":[11, 14, 13, 16, 9, 8, 6, 10], "date":["t1", "t2", "t3", "t4", "t1", "t2", "t3", "t4"]}) grid = sns.FacetGrid(df, size=12.5, hue="type", aspect=2) grid.map(plt.plot, "date", "value") plt.show() Then if I run sns.set(font_scale=2) (or just sns.set()), repeating the same plot I get grid = sns.FacetGrid(df, size=12.5, hue="type", aspect=2) grid.map(plt.plot, "date", "value") plt.show() This seems like somewhat odd behaviour to me. I would prefer the second plotting configuration but would like to obtain this without making an arbitrary call to sns.set(), unless of course this is the recommended approach. Relevant version info print("matplotlib version: %s" % matplotlib.__version__) print("seaborn version: %s" % sns.__version__) matplotlib version: 2.1.0 seaborn version: 0.8.0
possible better answer: http://stackoverflow.com/a/66509649
type: Question
answer count: 2
upvote count: 7
has title: Seaborn sns.set() changing plot background color
favorite count: 0
tagged with: seaborn
has answer: http://stackoverflow.com/a/48924691
accepted answer: http://stackoverflow.com/a/48924691
tagged with: python

http://stackoverflow.com/q/48858882
accepted answer: http://stackoverflow.com/a/48858911
tagged with: python
favorite count: 0
score: -4
downvote count: 4
type: AnsweredQuestion
has title: How do I search for items in a list like the function "LIKE" in SQL for Python?
upvote count: 0
has body: I'm just going to put this in words as I am still learning how to write in Python. x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Let's have an example where I want to search for a specific number in a list with numbers from 1 to 10. When a specific number is on the list, it would execute/perform a function. Example: if x == 1: print("Do something")
type: Question
answer count: 1
has answer: http://stackoverflow.com/a/48858911

http://stackoverflow.com/a/48864614
downvote count: 0
has comment: http://stackoverflow.com/comment/84736881
accepted answer of: http://stackoverflow.com/q/48864496
has body: You could use Python's logging module for this, you can change the logging level argument to record the level of logging detail you want: import logging logging.basicConfig(filename='log.txt', filemode='a', level=logging.DEBUG) try: number = int(number) except ValueError as except_detail: logging.warning("ValueError: «{}»".format(except_detail)) logging.info("«{}» is not an integer".format(number)) else: logging.info("Your number {} is an integer".format(number))
answers question: http://stackoverflow.com/q/48864496
has comment: http://stackoverflow.com/comment/84736586
score: 1
upvote count: 1
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84737416

http://stackoverflow.com/q/48941783
favorite count: 0
score: 0
has comment: http://stackoverflow.com/comment/84890424
possible better answer: http://stackoverflow.com/a/48941977
has answer: http://stackoverflow.com/a/48941977
tagged with: integer
tagged with: character
has body: I'd like to know how to turn a list of characters into their ascii form (a = 97, x = 120, etc). I have tried making each individual item into decimal form by using a loop, but I wonder if there is a better way to do so. I have written this so far, but this doesn't seem to work. x = input().lower() message = list( x ) messageInt = [] i = 0 while True: messageInt.append( ord(message([i])) i += 1 print messageInt How can I get my code to result in this [ 101, 120, 101, 97, 109, 112, 108, 101 ] If the input was the word "example".
upvote count: 1
tagged with: python
has title: How to change a list of characters into ASCII form?
downvote count: 1
has answer: http://stackoverflow.com/a/48941829
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84890470
type: Question
tagged with: decimal
answer count: 2
accepted answer: http://stackoverflow.com/a/48941829

http://stackoverflow.com/q/48919738
answer count: 0
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/42733542
tagged with: virtualenv
tagged with: macos
has comment: http://stackoverflow.com/comment/84845769
duplicate of: http://stackoverflow.com/q/42733542
type: Question
has comment: http://stackoverflow.com/comment/84845878
tagged with: windows
tagged with: python
has title: Same python virtualenviroment different OS
score: 0
has body: if this is not consider a valid question or problem to solve, I can try in other category. I used to work with python virtualenvs stored on OneDrive and run the projects from different PCs. Now I have to work from Mac OS and virtual enviroments don't seem to be equals. Is there a way to accomplish this from both OS ? Thanks in advance.

http://stackoverflow.com/a/69869708
has body: here's mine (a newbie) with a bit similar problem and finally dicide not to make it as boolean propworth = input("how much is your prop worth?") finalcost=0.1*int(propworth) finalcost2=0.2*int(propworth) def funx(): while True: creditevaluation= input("is the debt credit good or bad?") if creditevaluation.lower() =="good": print(f'10% downpayment is needed') print(f'as said 10% x {propworth}') print(f'downpayment: {finalcost}$') if creditevaluation.lower() =="bad": print (f'20% down payment is needed') print(f'as said 20% x {propworth}') print (f'downpayment: {int(finalcost2)}$') else : creditevaluation.lower() != "good","bad" print("Please type good or bad") return funx() break funx() print ("""debt will be sent to your account !!! thx for choosing our service""")``` come for some rep lol
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48817461

http://stackoverflow.com/comment/84861417
comment on: http://stackoverflow.com/a/48922383
score: 0
type: AnswerComment
type: Comment
has text: https://stackoverflow.com/questions/48927671/assigning-the-value-to-a-user-depending-on-the-cluster-he-comes-from

http://stackoverflow.com/q/48944382
has answer: http://stackoverflow.com/a/49047520
score: 1
has comment: http://stackoverflow.com/comment/84895433
type: Question
has title: How to write all variables to a JSON file in the python shell
has body: Let's say I have created some variables in the python shell. I want to do something like this: &gt;&gt;&gt; animal="Cat" &gt;&gt;&gt; age="2" &gt;&gt;&gt; weight="3.8" &gt;&gt;&gt; name="Kitty" &gt;&gt;&gt; env.saveTo("./Cat.json") &gt;&gt;&gt; env.clear() &gt;&gt;&gt; env.loadFrom("./Cat.json") Is it possible? I am using xonsh.
tagged with: xonsh
upvote count: 1
has comment: http://stackoverflow.com/comment/84906123
answer count: 1
tagged with: shell
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
downvote count: 0

http://stackoverflow.com/a/48891585
has comment: http://stackoverflow.com/comment/84790579
answers question: http://stackoverflow.com/q/48891416
accepted answer of: http://stackoverflow.com/q/48891416
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84790609
score: 1
has body: There might be a more succinct solution, but this should work (will give you a dictionary of DataFrames, one for each period): df = pd.DataFrame([['ABC123', '2017-11-22'], ['ABC124', '2017-12-04'], ['ABC125', '2017-12-15']], columns=['Barcode', 'LeaveDate']) periods = [('2017-11-20', '2017-12-24'), ('2017-11-27', '2017-12-31')] results = {} for period in periods: period_df = df[(df['LeaveDate'] &gt;= period[0]) &amp; (df['LeaveDate'] &lt;= period[1])] results[period] = period_df
has comment: http://stackoverflow.com/comment/97454081

http://stackoverflow.com/comment/84892668
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48942932
has text: @UbdusSamad No. They are supposed to run sequentially. And the latter one is dependent on its previous one. So if I encounter an error in any script, it gets propagated through all the latter scripts. Hence I want to exit just as the first error is encountered.
score: 0

http://stackoverflow.com/comment/102244272
type: Comment
comment on: http://stackoverflow.com/a/54480966
score: 0
type: AnswerComment
has text: How would you actiavte a virtual environment in generel?

http://stackoverflow.com/comment/84670100
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48832896
type: Comment
has text: `dict` is not a [keyword](https://docs.python.org/3.3/reference/lexical_analysis.html#keywords). You can overwrite it (though you obviously shouldn't without good reason)

http://stackoverflow.com/comment/84798495
score: 0
comment on: http://stackoverflow.com/q/48896341
type: Comment
type: QuestionComment
has text: updated the question!!

http://stackoverflow.com/q/48896993
tagged with: flask-sqlalchemy
tagged with: postgresql
tagged with: python
accepted answer: http://stackoverflow.com/a/48913299
has comment: http://stackoverflow.com/comment/84815199
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84827310
has comment: http://stackoverflow.com/comment/84828192
has body: I'm trying to use search capability on flask application. It seems to be saving in database properly however query isn't returning me anything. DATABASE MODEL: app = Flask(__name__) csrf = CsrfProtect(app) csrf.init_app(app) db = SQLAlchemy(app) class ArticleQuery(BaseQuery, SearchQueryMixin): pass class latest_movies_scraper(db.Model): query_class = ArticleQuery __tablename__ = 'latest_movies_scraper' id = db.Column(sa.Integer, primary_key=True) name = db.Column(db.Unicode(255)) url = db.Column(db.Unicode(255)) image_url = db.Column(db.Unicode(255)) create = db.Column(db.DateTime, default=datetime.datetime.utcnow) search_vector = db.Column(TSVectorType('name')) How i'm saving to database: check_if_exists = latest_movies_scraper.query.filter_by(name=dictionary['title']).first() if check_if_exists: print check_if_exists.name print 'skipping this...' pass else: insert_to_db = latest_movies_scraper(name=dictionary['title'], url=dictionary['href'], image_url=dictionary['featured_image']) db.session.add(insert_to_db) db.session.commit() How I am using search capbilitiy functionality: name = latest_movies_scraper.query.search(u'Black Panther (2018)').limit(5).all() Name returns empty array, but it should return me the name list instead. ABOVE MY GOAL is to query the name from the database. It doesn't return me anything when in fact the name Black Panther 2018 exists in my database. So the search functionality isn't working as expected.
type: Question
tagged with: flask
has title: Flask Sqlachemy make_searchable isn't returning any results
has answer: http://stackoverflow.com/a/48913299
score: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84825771

http://stackoverflow.com/a/51788884
has body: Try change {% paginate courses1 %} to {% paginate courses1 using course %}. or {{% paginate courses1 using "course" %}
answers question: http://stackoverflow.com/q/48811136
score: 0
type: Answer

http://stackoverflow.com/q/48936463
has answer: http://stackoverflow.com/a/48937151
tagged with: python-2.7
has title: Trouble accessing object
type: Question
tagged with: django
tagged with: python
answer count: 1
has body: I've been working on an issue all day and am at my wits end. I have two models with a manytomany relationship (bookmark, and boomark group). I am trying to access the bookmarks accosiated with the bookgroup in my view. When print the context to take a peak I get None returned. I've pasted the code below in a gist...any help would be so greatly appreciated. models.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from itertools import chain import datetime import hashlib from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django_mysql.models import JSONField, Model from django.template.loader import render_to_string from django.core.mail import send_mail from django.utils import timezone from django.conf import settings class Bookmark(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) resource = models.ForeignKey("Resource", on_delete=models.CASCADE, related_name="bookmarks") bookmark_groups = models.ManyToManyField("BookmarkGroup") # meta created_at = models.DateTimeField(auto_now_add=True) modified_at = models.DateTimeField(auto_now=True) class Meta: unique_together = ('user', 'resource',) ordering = ('resource',) def __str__(self): return "{} | {}".format(self.user, self.resource) class BookmarkGroup(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(null=False, unique=True) bmark = models.ManyToManyField(Bookmark) def __str__(self): return self.name views.py from __future__ import unicode_literals import json from django.shortcuts import render, get_list_or_404 from django.http import JsonResponse from django.views import View from django.views.generic import DetailView from app.serializers import BookmarkGroupSerializer from app.models import Resource,Bookmark,ResourceShare,PrivateNote,BookmarkGroup from app.views.resources import get_enriched_resources class BookmarkGroupView(DetailView): model…
tagged with: django-views
score: 0
tagged with: django-models
type: UnansweredQuestion

http://stackoverflow.com/comment/84922737
comment on: http://stackoverflow.com/a/48829557
score: 0
type: AnswerComment
has text: @Luke, I've further expanded the answer. I hope it is clear and you find everything you need.
type: Comment

http://stackoverflow.com/comment/84619669
type: Comment
comment on: http://stackoverflow.com/a/48808302
has text: However numpy hasn't got an attribute for mode. What shall I use instead?
score: 0
type: AnswerComment

http://stackoverflow.com/a/48843971
accepted answer of: http://stackoverflow.com/q/48843887
downvote count: 0
has comment: http://stackoverflow.com/comment/99925479
upvote count: 11
has comment: http://stackoverflow.com/comment/99912865
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84692387
has body: Use lambda function: q = 0.22 df1 = df.groupby('lvl_1')['value'].agg(['min','max',lambda x: x.quantile(q)]) print (df1) min max &lt;lambda&gt; lvl_1 di 0.275401 0.530000 0.294589 fi 0.054363 0.848818 0.136555 Or is possible create f function and set it name for custom column name: q = 0.22 f = lambda x: x.quantile(q) f.__name__ = 'custom_quantile' df1 = df.groupby('lvl_1')['value'].agg(['min','max',f]) print (df1) min max custom_quantile lvl_1 di 0.275401 0.530000 0.294589 fi 0.054363 0.848818 0.136555
answers question: http://stackoverflow.com/q/48843887
type: Answer
score: 11

http://stackoverflow.com/a/48833285
type: Answer
accepted answer of: http://stackoverflow.com/q/48832832
answers question: http://stackoverflow.com/q/48832832
score: 1
has body: You should check out this example from the matplotlib website. It seems that you should be able to do the following: plt.xticks(range(0,len(average_prices), 14), dates[0:len(average_prices):14])
upvote count: 1
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48818101
tagged with: python-3.x
has title: Access the form that caused a post_save [Django]
type: UnansweredQuestion
tagged with: django
type: Question
has body: Is there a way I can access the form that caused a post_save? The use case is that I have a field (a checkbox) that isn't attached to a particular model, but it's an extra field in the form itself. I want to know whether the field was checked or unchecked when the form got saved and the model stored, and imho the post_save signal is a good place to put the logic that should process that extra field. I'm also open to suggestions where else I could put that piece of code.
answer count: 1
score: 0
has answer: http://stackoverflow.com/a/48818718
tagged with: django-1.10
tagged with: python

http://stackoverflow.com/comment/85344958
type: AnswerComment
score: 0
type: Comment
has text: Yes they are. The directory structure is similar to the one in the description.
comment on: http://stackoverflow.com/a/48980082

http://stackoverflow.com/comment/84837282
has text: Thanks. Is there any way to make it without define that signal to MyClass?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48915001

http://stackoverflow.com/q/48923813
tagged with: python
has title: Running Script on button click
has body: I am trying to run an external Python script on a button click. I think I almost have it working although it runs the external script as soon as I run the GUI class itself. I need it to run the script when the button is clicked. I think I almost have it, could someone guide me as to what I need to change. I have written a function called parseCanonical(): and this is where I am trying to set up the button click so that I can run the external script. # import Statements from PyQt5 import QtCore, QtGui, QtWidgets from reportViewerWindow import Ui_reportViewerWindow import os import CanonicalAddressesParser # Main Class that holds User Interface Objects class Ui_MainWindow(object): # Function for Opening Report Viewer Window From Main Window by clicking View Reports button def openReportViewer(self): self.window = QtWidgets.QMainWindow() self.ui = Ui_reportViewerWindow() self.ui.setupUi(self.window) self.window.show() def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.setFixedSize(834, 428) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(12) font.setBold(True) font.setWeight(75) MainWindow.setFont(font) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") # Sim Card Button self.simCardButton = QtWidgets.QPushButton(self.centralwidget) self.simCardButton.setGeometry(QtCore.QRect(30, 200, 211, 30)) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(14) self.simCardButton.setFont(font) self.simCardButton.setObjectName("simCardButton") # Call Logs Button self.callLogButton = QtWidgets.QPushButton(self.centralwidget) self.callLogButton.setGeometry(QtCore.QRect(30, 300, 211, 30)) font = QtG…
possible better answer: http://stackoverflow.com/a/48927971
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/84861556
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48928012
has answer: http://stackoverflow.com/a/48928012
has answer: http://stackoverflow.com/a/48927971
answer count: 2
has comment: http://stackoverflow.com/comment/84856880
score: 0

http://stackoverflow.com/a/48855985
answers question: http://stackoverflow.com/q/48855824
accepted answer of: http://stackoverflow.com/q/48855824
type: Answer
has body: Variables inside functions are local. Basically you need to return the playerLetter to be used in the next while Loop. Try this: board_list=["0","1","2","3","4","5","6","7","8"] # Print out the tic tac toe board # Input: list representing the tic tac toe board # Return value: none def printUglyBoard(board_list): print() counter = 0 for i in range(3): for j in range(3): print(board_list[counter], end=" ") counter += 1 print() def isValidMove(board_list,spot): if 0&lt;= spot &lt;= 8 and board_list[spot]!='x' and board_list[spot]!='o': print("True") return True else: print("Invaild. Enter another value.") return False def updateBoard(board_list,spot,playerLetter): result=isValidMove(board_list,spot) if result==True and playerLetter=='x': board_list[spot]='x' playerLetter='o' elif result==True and playerLetter=='o': board_list[spot]='o' playerLetter='x' print(board_list) print(playerLetter) printUglyBoard(board_list) return playerLetter ############### &lt;&lt;------- CHANGED def play(): playerLetter = 'o' ############### &lt;&lt;------- CHANGED printUglyBoard(board_list) while True: if playerLetter=='x': spot = int(input('Player x,enter the value:')) elif playerLetter=='o': spot = int(input('Player o,enter the value:')) isValidMove(board_list,spot) playerLetter = updateBoard(board_list,spot,playerLetter) ###### &lt;&lt;---- CHANGED play() Furthermore: You can do various changes here. Consider this for example, 4lines become 1: if playerLetter=='x': spot = int(input('Player x,enter the value:')) elif playerLetter=='o': spot = int(input('Player o,enter the value:')) Could be changed to this: spot = int(input('Player {},enter the value:'.format(playerLetter))
score: 0
type: AcceptedAnswer

http://stackoverflow.com/q/48862506
downvote count: 0
score: 1
type: Question
has title: Pandas storing the date values in wrong column
tagged with: pandas
upvote count: 1
answer count: 1
tagged with: python-2.x
has answer: http://stackoverflow.com/a/48863280
accepted answer: http://stackoverflow.com/a/48863280
favorite count: 0
tagged with: python
type: AnsweredQuestion
has body: I am trying to process the future values: last_date = df.iloc[-1] print(last_date) last_unix = last_date.Timestamp # one_day = 86400 one_minute = 60 next_unix = last_unix + one_minute matplotlib.rc('figure', figsize=(20, 10)) for i in forecast_set: next_date = datetime.datetime.fromtimestamp(next_unix) # next_date = next_unix next_unix += 60 df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i] # print(next_unix) I am getting the code running properly. After saving the dataframe I came to know that the data is not in a proper format: Timestamp Adj. Open Adj. High Adj. Low Adj. Close Adj. Volume label Forecast 35866 1518744240 10356.7 10383.1 10356.7 10383.1 0.99564597 10674.5 35867 1518744300 10398.9 10398.9 10373.1 10397 0.17246706 10637.9 35868 1518744360 10397 10409.9 10387.5 10409.9 0.91689198 10692.3 35869 1518744420 10397.3 10408.1 10381.2 10406.3 2.2375806 10691.2 2018-02-16 06:58:00 10846.7419537654 2018-02-16 06:59:00 10842.8747135627 2018-02-16 07:00:00 10832.5305557475 2018-02-16 07:01:00 10840.6966663947 2018-02-16 07:02:00 10833.9536747933 I get the date values in the serial numbers column, which is disturbing the data visualization. How to make it proper in position with the continuous serials?

reindex
tag name: reindex
tags question: http://stackoverflow.com/q/48913757
type: Tag

http://stackoverflow.com/a/53932679
score: 0
answers question: http://stackoverflow.com/q/48872724
has body: Was trying to install Python and took the latest version (3.7.2). Got the same error (or while setting it up with the installer, gave the cryptic "Access Denied" issue, which led to a different set of issues/resolutions. Finally, just changed to an earlier release (v3.5.2 for now) and that worked smoothly. Saves time, if you're trying to get other things done! As someone pointed out already, it probably has to do with PyInstaller not being supported (yet?)
type: Answer

http://stackoverflow.com/comment/84642243
has text: This is probably the best solution, I don't think a one-liner is something to aspire to. :)
score: 1
comment on: http://stackoverflow.com/a/48813105
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48882313
tagged with: python-3.x
linked to: http://stackoverflow.com/q/47177696
tagged with: django-2.0
tagged with: django
tagged with: python
duplicate of: http://stackoverflow.com/q/47177696
has answer: http://stackoverflow.com/a/48882350
type: AnsweredQuestion
score: 3
has body: Using path in project's urls.py, and using re_path in app's urls.py, I got the NoReverseMatch error, my project's urls.py: from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('user/', include('user.urls', namespace='user')) ] My app's urls.py: urlpatterns = [ re_path('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})/', views.activate_account, name='activate'), ] I can't get the correct url, the error message: django.urls.exceptions.NoReverseMatch: Reverse for 'activate' with keyword arguments '{'uidb64': b'Mjc', 'token': '4tv-d4250012f57297ad82a6'}' not found. 1 pattern(s) tried: ['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})/']
has title: Django 2.0: combine path and re_path got NoReverseMatch error
upvote count: 3
type: Question
accepted answer: http://stackoverflow.com/a/48882350
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/q/48879615
type: Question
has answer: http://stackoverflow.com/a/48879768
has title: How do I create a sublist that contains the last element, but uses a general formula for all other sublists of the same size?
has answer: http://stackoverflow.com/a/48880588
tagged with: for-loop
answer count: 3
has comment: http://stackoverflow.com/comment/84763297
linked to: http://stackoverflow.com/q/312443
downvote count: 0
tagged with: sublist
has answer: http://stackoverflow.com/a/48879870
favorite count: 0
type: UnansweredQuestion
has body: I have a long list, let's call it y. len(y) = 500. I'm not including y in the code on purpose. For each item in y, I want to find the average value of the item and its 5 proceeding values. I run into a problem when I get to the last item on the list, because I need to use 'a+1' for one of the lines below. a = 0 SMAlist = [] for each_item in y: if a &gt; 4 and a &lt; ((len(y))-1): # finding my averages begin at 6th item b = (y[a-5:a+1]) # this line doesn't work for the last item in y SMAsix = round((sum(b)/6),2) SMAlist.append(SMAsix) if a &gt; ((len(y))-2): # this line seems unnecessary. How can I avoid it? b = (y[-6:-1]+[y[a]]) # Should I just use negative values in general? SMAsix = round((sum(b)/6),2) SMAlist.append(SMAsix) a = a+1
tagged with: python
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84763214
tagged with: loops

http://stackoverflow.com/comment/84678803
comment on: http://stackoverflow.com/q/48836873
has text: `interp1d` can do varying orders of spline interpolation is that good enough?
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84897485
type: QuestionComment
comment on: http://stackoverflow.com/q/48938120
score: 0
has text: Not yet. Will give it a go . Thanks.
type: Comment

http://stackoverflow.com/q/48868819
has comment: http://stackoverflow.com/comment/84741819
downvote count: 0
answer count: 1
has title: Fast mutation of ndarray (replace part of numpy ndarray)
favorite count: 0
has comment: http://stackoverflow.com/comment/84741542
has body: I am looking for fastest way to replace parts of pre-allocated numpy ndarray. Below you can see sim_matrix (2D ndarray). "For loop" iterates over it rowwise and overwrites values given by levels (numpy.array). There are fast ways, which are found: numpy.copyto() numpy.fromiter() = assignment to slice NOTE: For simplicity, I assign the same values on each iteration, it is not the case in production setup. In actual setup, levels contains different values for each row. Thus, using shortcut as numpy.repeat or numpy.hstack is discouraged as an answer. Are there any faster ways to change parts of ndarray? numpy_overwrite.py: import numpy panel_size = 365 * 7 rows = 1 * (1+1+2*4) * 10000 # rows = 100 levels = [1778.24] * panel_size levels_array = numpy.fromiter(levels,dtype='single', count = len(levels)) sim_matrix = numpy.empty([rows, panel_size],dtype='single') def _copyto(sim_matrix_, level_): for i in range(sim_matrix_.shape[0]): numpy.copyto(sim_matrix[i], level_) def _fromiter(sim_matrix_, level_): len_level = len(level_) for i in range(sim_matrix_.shape[0]): sim_matrix[i] = numpy.fromiter(level_, dtype='single', count = len_level) def _just_assign(sim_matrix_, level_): for i in range(sim_matrix_.shape[0]): sim_matrix[i] = level_ numpy_overwrite_test.py import timeit import numpy_overwrite as npo print('_fromiter') print(timeit.timeit('npo._fromiter(npo.sim_matrix, npo.levels)', setup="import numpy_overwrite as npo;", number=3)) print(timeit.timeit('npo._fromiter(npo.sim_matrix, npo.levels_array)', setup="import numpy_overwrite as npo;", number=3)) print('_copyto') print(timeit.timeit('npo._copyto(npo.sim_matrix, npo.levels)', setup="import numpy_overwrite as npo;", number=3)) print(timeit.timeit('npo._copyto(npo.sim_matrix, npo.levels_array)', setup="import numpy_overwrite as npo;", number=3)) print('_just_assign') print(timeit.timeit('npo._just_assign(npo.sim_matrix, npo.levels)', setup="import numpy_overwrite as npo;", number=3)) print(timeit.timeit('npo._just_as…
has comment: http://stackoverflow.com/comment/84741999
has answer: http://stackoverflow.com/a/48869071
has comment: http://stackoverflow.com/comment/84746602
type: UnansweredQuestion
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84741280
has comment: http://stackoverflow.com/comment/84741682
has comment: http://stackoverflow.com/comment/84741326
score: 1
type: Question
tagged with: numpy

http://stackoverflow.com/q/48848242
tagged with: dictionary
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48848307
type: Question
has comment: http://stackoverflow.com/comment/84700402
answer count: 1
has body: My code are the followings: def hello(msg): return print(msg) def hi(msg): t = 'this is a test time' return print(t + msg) data = {0: hello, 1: hi} for i in range(2): x = data.get(i) print(x('hello world '+str(i))) However the output is: hello world 0 None this is a test timehello world 1 None Question is why I got two None?
accepted answer: http://stackoverflow.com/a/48848307
score: 0
has comment: http://stackoverflow.com/comment/84700368
has title: why I got None in my function
tagged with: python

http://stackoverflow.com/q/48868188
has body: Not Sure why my code not working. The code below generate error: ValueError: Initializer for variable while_7/Variable/ is from inside a control-flow construct, such as a loop or conditional. When creating a variable inside a loop or conditional, use a lambda as the initializer. Need a quick fix on this loop.. For each tf.while_loop, with index "i". if the minimum value of distance matrix dist[,i] &lt;= caliper then output the first min value index; i.e. (y,i). Then set dist[y,]=[None, None, None, None]. Given the example matix "myx","myy"; The while loop should output match pair indx [[0,None],[1,5],[2,4],[3,None]] import math import numpy as np import tensorflow as tf myx=np.array([2.4,0.2,0.5,1.6]) myy=np.array([10.1,3.2,7.5,8.6,1,0.1,11,18]) Xxx=np.transpose(np.repeat(myx[:, np.newaxis], myy.size , axis=1)) Yyy=np.repeat(myy[:, np.newaxis], myx.size , axis=1) X = tf.placeholder(tf.float64, shape=(myy.size,myx.size)) Y = tf.placeholder(tf.float64, shape=(myy.size,myx.size)) # define a caliper calp=tf.constant(0.5,tf.float64) with tf.device('/cpu:0'): dist = tf.abs(tf.subtract(X,Y)) # Use an explicit shape for `i`. i = tf.placeholder(dtype='int64', shape=[]) # Add a second unused argument to `condition()`. def condition(i, *arg): return i &lt;= myx.size-1 # Add a second unused argument to `b()`. def b(i, temp_pr, _): tfslic = dist[0:myy.size, i] # Drop the `axis` argument from `tf.reduce_min()` minVal=tf.reduce_min(tfslic) y = tf.cond( tf.less_equal(minVal, calp), # Reshape the output of `tf.argmin()` to be a scalar. lambda: tf.argmin(tfslic, 0), # Explicitly convert the false-branch value to `tf.int64`. lambda: tf.constant(99999, dtype=tf.int64)) ### Need to drop the matched one ### #newdist=tf.stack([dist[0:y], dist[y:myx.size-1]]) ### Need to save every match 2 dim ''' :::::::::::::PROBLEM START HERE::::::::::: For each tf.while_loop, with index "i" if the minimum value of distance matrix dist[,i] &lt;= caliper then output the first min value index. i.e. (y,i) …
tagged with: tensorflow
has title: Tensorflow While loop error
type: Question
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
answer count: 0
upvote count: 2

mcmc
tags question: http://stackoverflow.com/q/48947660
tag name: mcmc
type: Tag

http://stackoverflow.com/a/48850794
type: Answer
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84723408
has body: "Changing TkInter Scale won't update label “bg”" That is false. The Scale widgets you have have the value of 0, and you configure the label2's background to their values at the time that they are 0, thus the label is black, as '#000000' is black. In order to dynamically update something whenever a Scale's value is changed, use command option in Scale: def update(): global label2, slider1, slider2, slider3 label2.config(bg='#%02x%02x%02x' % (slider1.get(), slider2.get(), slider3.get())) ... slider1['command'] = lambda scale_value: update() slider2['command'] = lambda scale_value: update() slider3['command'] = lambda scale_value: update() Alternatively, command already passes Scale's value but it may yield extra overhead in this case.
has comment: http://stackoverflow.com/comment/84718751
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48848671
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48848671

http://stackoverflow.com/q/48834972
possible better answer: http://stackoverflow.com/a/48835163
has answer: http://stackoverflow.com/a/48835163
type: Question
has answer: http://stackoverflow.com/a/48873183
linked to: http://stackoverflow.com/q/3207219
accepted answer: http://stackoverflow.com/a/48835059
favorite count: 0
has title: Using same code for multiple text files and generate multiple text files as output using python
score: 0
has comment: http://stackoverflow.com/comment/84674687
answer count: 3
tagged with: python
upvote count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48835059
has body: I have more than 30 text files. I need to do some processing on each text file and save them again in text files with different names. Example-1: precise_case_words.txt ---- processing ---- precise_case_sentences.txt Example-2: random_case_words.txt ---- processing ---- random_case_sentences.txt Like this i need to do for all text files. present code: new_list = [] with open('precise_case_words.txt') as inputfile: for line in inputfile: new_list.append(line) final = open('precise_case_sentences.txt', 'w+') for item in new_list: final.write("%s\n" % item) Am manually copy+paste this code all the times and manually changing the names everytime. Please suggest me a solution to avoid manual job using python.
type: AnsweredQuestion

http://stackoverflow.com/comment/84683320
score: 0
type: Comment
type: QuestionComment
has text: I converted the code to Asyncio (which is written with Twisted) and there is no error message or something with the code.
comment on: http://stackoverflow.com/q/48839120

http://stackoverflow.com/comment/84929396
type: Comment
comment on: http://stackoverflow.com/q/48961297
score: 0
has text: Godsh thanks! but why `self.cur.execute(sql.format(col, placeholders), (item.values(),))` does not makes it tuple though?
type: QuestionComment

http://stackoverflow.com/comment/84777135
score: 0
type: AnswerComment
type: Comment
has text: Thank you so much my friend!
comment on: http://stackoverflow.com/a/48876875

http://stackoverflow.com/a/48849134
type: Answer
score: 2
downvote count: 0
upvote count: 2
type: AcceptedAnswer
has body: The first observation is that you seem to be using a get request in your example code instead of a post request. &lt;form action="taa_search.cfm" method="post" ...&gt; ^^^^^^^^^^^^^ After changing to a post request, I was still getting the same results as you though (html from the main search form page). After a bit of experimentation, I seem to be able to get the proper html results by adding a referer to the header. Here is the code (I only commented out the writing to file part for example purposes): import requests BASE_URL = 'https://www.doleta.gov/tradeact/taa' def get_case_decision(case_number): headers = { 'referer': '{}/taa_search_form.cfm'.format(BASE_URL) } payload = { 'form_name': 'number_search', 'input': case_number } r = requests.post( '{}/taa_search.cfm'.format(BASE_URL), data=payload, headers=headers ) r.raise_for_status() return r.text # with open('requests_results_{}.html'.format(case_number), 'wb') as f: # f.write(r.content) Testing: &gt;&gt;&gt; result = get_case_decision(10000) &gt;&gt;&gt; 'MODINE MFG. COMPANY' in result True &gt;&gt;&gt; '9/12/1980' in result True &gt;&gt;&gt; result = get_case_decision(10001) &gt;&gt;&gt; 'MUSKIN CORPORATION' in result True &gt;&gt;&gt; '2/27/1981' in result True Since you mentioned that you need to perform this ~10,000 times, you will probably want to look into using requests.Session as well.
accepted answer of: http://stackoverflow.com/q/48847881
answers question: http://stackoverflow.com/q/48847881

http://stackoverflow.com/comment/84800296
score: 0
type: QuestionComment
has text: Sounds like your default python version is set to none, which doesn't meet the regex requirement.
type: Comment
comment on: http://stackoverflow.com/q/48897342

http://stackoverflow.com/q/48951109
score: 4
has answer: http://stackoverflow.com/a/49322165
type: UnansweredQuestion
has body: I try writing a custom binary cross-entropy loss function. This is my script: def my_custom_loss(y_true,y_pred): t_loss = (-1)*(y_true * K.log(y_pred) + (1 - y_true) * K.log(1 - y_pred)) return K.mean(t_loss) When I run my script using this loss function, after few iterations, I get NaN as output for loss function. Then I looked at TensorFlow documentation, I modified the loss function into the following: t_loss = K.max(y_pred,0)-y_pred * y_true + K.log(1+K.exp((-1)*K.abs(y_pred))) The code runs without any issue. I would like to know if someone could provide some explanation why my first loss function gives a NaN output. Binary Cross-Entropy: y * log(p) + (1-y) * log(1-p) I have sigmoid function as activation for my last layer. So the value of 'p' should be between 0 and 1. Log should exist for this range. Thank you.
has title: Keras Custom Binary Cross Entropy Loss Function. Get NaN as output for loss
tagged with: loss-function
type: Question
upvote count: 4
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0
tagged with: python

http://stackoverflow.com/q/48958711
has comment: http://stackoverflow.com/comment/84924721
has comment: http://stackoverflow.com/comment/84925296
has body: I am trying to create a web crawler that crawls wikipedia and stores fetched data (title, content and links) inside an MySQL database, with beautifulsoup and pymysql libraries. After running the code a lot of times I managed to fix all the errors that were causing my program to terminate. Now the problem I have is with MemoryError. Any idea how to avoid this? Everyone online say that you can't handle this error by making an exception, or at least is not good practice. All the solutions about this online were given for specific programs with third party libraries so I couldn't make any sense. The program terminates and the error appears around after 2000 loops. import socket from urllib.error import HTTPError from urllib.error import URLError from urllib.request import urlopen from bs4 import BeautifulSoup import pymysql import re #for recursion depth from requests import Timeout, RequestException import sys sys.setrecursionlimit(80000) pages=set() conn = pymysql.connect(host='127.0.0.1', user='root', passwd='somepsw', db='mysql', charset='utf8') cur = conn.cursor() cur.execute("USE searchenginedb2") def store(title, content, link): cur.execute("INSERT INTO websites (title, content, link) VALUES (\"%s\",\"%s\",\"%s\")", (title, content, link)) cur.connection.commit() def getLinks(pageUrl): global pages try: html = urlopen("http://en.wikipedia.org" + pageUrl, timeout=10)#timeout for timeouterror except HTTPError: print("HTTP ERROR") except URLError: print("URLERROR") except socket.timeout: print("SOCKERT TIMEOUT") try: bsObj = BeautifulSoup(html,"html.parser") except UnboundLocalError: print("UnboundLocalError") try: #print(bsObj.h1.get_text()) title = bsObj.find("h1").get_text() content = bsObj.find("div", {"id": "mw-content-text"}).find("p").get_text() #print(bsObj.find(id="mw-content-text").findAll("p")[0]) store(title, content,"http://en.wikipedia.org" + pageUrl) #print(bsObj.find(id="ca-edit").find("span").find("a").attrs['href']) except AttributeError: print("At…
has comment: http://stackoverflow.com/comment/84924284
score: 0
has comment: http://stackoverflow.com/comment/84925022
has comment: http://stackoverflow.com/comment/84924755
favorite count: 0
tagged with: beautifulsoup
tagged with: python-3.x
answer count: 0
has title: Handling MemoryError in my Python code
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84924667
upvote count: 1
tagged with: python
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84924357

http://stackoverflow.com/comment/84636565
score: 2
comment on: http://stackoverflow.com/q/48816327
type: QuestionComment
has text: Can you show us the code you are using?
type: Comment

http://stackoverflow.com/comment/84887735
comment on: http://stackoverflow.com/a/48939694
type: Comment
score: 0
has text: Thanks for your response!!
type: AnswerComment

http://stackoverflow.com/comment/84686274
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48840961
has text: Viktor could You check my edit? The django return me a error when I want to save a record
type: Comment

http://stackoverflow.com/a/48967829
has comment: http://stackoverflow.com/comment/90438206
type: Answer
has body: You could do this with pandas. Update 08.08.2018: As noticed by Can Kavaklıoğlu, as_matrix() is deprecated as of pandas version 0.23.0. Changed to values. import pandas as pd df = pd.read_csv('csv_file.csv', names=['user_id', 'group_id', 'group_value']) df = df.pivot(index='user_id', columns='group_id', values='group_value') mat = df.values
score: 0
answers question: http://stackoverflow.com/q/48952140

http://stackoverflow.com/comment/84701729
comment on: http://stackoverflow.com/q/48848880
has text: hi , can you tell me where i am going wrong this is my code, I am new to this ,could please ellaborate,
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84654083
type: Comment
has text: while this is true, this does not solve the question OP asked so this should be a comment instead
comment on: http://stackoverflow.com/a/48825290
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84781295
has text: Something's weird, when you remove the `fg='white', bg='navy'` lines in the RadioButton it seems to work fine, but I couldn't reproduce it on a clean copy.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48887475
score: 0

http://stackoverflow.com/a/48903586
score: 1
answers question: http://stackoverflow.com/q/48903177
upvote count: 1
has body: Complete solution with re.sub() + re.findall() functions: import re diff_lst = ['@@ -1289,4 +1289,4 @@', '@@ -1289,2 +1289 @@', '@@ -1289 +1289,8 @@'] sub_pat, find_pat = re.compile(r'([+-]\d+)\s'), re.compile(r'[+-](\d+),(\d+)') result = [[int(d) for t in find_pat.findall(sub_pat.sub('\\1,0', s)) for d in t] for s in diff_lst] print(result) The output: [[1289, 4, 1289, 4], [1289, 2, 1289, 0], [1289, 0, 1289, 8]]
type: Answer
downvote count: 0

http://stackoverflow.com/q/48820876
has comment: http://stackoverflow.com/comment/84645581
favorite count: 0
possible better answer: http://stackoverflow.com/a/48821106
has body: I have a files in which data is something like this [1,2,3,4,5] [4,2,3,4,5,6] [3,12,3,34,5] [3,4,5,6,7,8] [2,3,4,5,6,6] [2,3,4,5,5,4,3] [1,2,3,23,2,1] i just want to convert this into numpy array, something like this [[1,2,3,4,5],[4,2,3,4,5,6]] I tried following code: import ast import numpy as np a = np.array([]) with open("test.txt","r") as f: for line in f: line = ast.literal_eval(line) np.append(line,a) it is only giving []
has answer: http://stackoverflow.com/a/48821608
accepted answer: http://stackoverflow.com/a/48821608
upvote count: 1
tagged with: python
has answer: http://stackoverflow.com/a/48821106
type: AnsweredQuestion
score: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84645327
has comment: http://stackoverflow.com/comment/84645454
has comment: http://stackoverflow.com/comment/84645703
has title: convert the lines of a file into numpy array
answer count: 2
downvote count: 0

http://stackoverflow.com/comment/84714896
type: Comment
has text: I understand. Thank you for your reply!
comment on: http://stackoverflow.com/a/48853039
score: 0
type: AnswerComment

http://stackoverflow.com/q/48940357
tagged with: mongodb
accepted answer: http://stackoverflow.com/a/48940539
type: Question
type: AnsweredQuestion
has title: Using mongodb with class-based view django
has body: I try to use class-based view like below class DetailBookVIew(DetailView): model = Book template_name = 'book/detail_book.html' with model Book is a mongodb model, so how can I use that class-based view with mongodb model, because it will cause error like AttributeError: type object 'Book' has no attribute '_default_manager', the _default_manager attribute only available for sql model.
tagged with: django
tagged with: python
answer count: 1
has answer: http://stackoverflow.com/a/48940539
score: 0
tagged with: mongoengine

http://stackoverflow.com/q/48896964
answer count: 1
tagged with: arrays
tagged with: sublist
has title: Select sublist where each element has a 1.5% chance to be included
tagged with: python
has body: tmp = [] while len(tmp) == 0: for i in range(0,385): # Multiplying by 100 in order to remove the decimal point if randint(0,10000) &lt; chance*100: tmp.append(i) return tmp This is the code I'm currently using to help clear things up. The output will be something like this. [34, 234, 243, 321] My current solution is very inefficient. I tried this: sample(range(0,385), math.ceil(chance*3.85)) But it doesn't produce the same effect. Also if you could tell me the name of what this is called that would be great.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48897023
type: Question
tagged with: numpy
score: 0
accepted answer: http://stackoverflow.com/a/48897023
tagged with: random

http://stackoverflow.com/comment/84833268
has text: I agree with you
score: 0
comment on: http://stackoverflow.com/q/48913031
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48898341
type: Answer
answers question: http://stackoverflow.com/q/48898216
score: 0
has body: As @juanpa.arrivillaga correctly observed, you should not have been inventing your formats. But since you did, and, luckily, your rows look like JSON arrays, the following code may help: import json data = """[81.48, 74.02, 4.03, 23.18, 211359232.0];[...]""" array = np.array([json.loads(row) for row in data.split(';')])

http://stackoverflow.com/comment/84878922
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48916479
has text: Was it answered?
score: 0

http://stackoverflow.com/q/48817461
has answer: http://stackoverflow.com/a/69869708
has comment: http://stackoverflow.com/comment/109970363
linked to: http://stackoverflow.com/q/23294658
tagged with: input
tagged with: python
has answer: http://stackoverflow.com/a/58681614
has answer: http://stackoverflow.com/a/73145834
upvote count: 13
has answer: http://stackoverflow.com/a/69323934
has comment: http://stackoverflow.com/comment/84638993
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48817562
downvote count: 2
score: 11
linked to: http://stackoverflow.com/q/37895568
has answer: http://stackoverflow.com/a/48817580
has comment: http://stackoverflow.com/comment/84638906
has answer: http://stackoverflow.com/a/59370112
has answer: http://stackoverflow.com/a/53537319
has answer: http://stackoverflow.com/a/62165649
has title: User input boolean in python
has comment: http://stackoverflow.com/comment/84638953
linked to: http://stackoverflow.com/q/715417
type: Question
tagged with: boolean
has answer: http://stackoverflow.com/a/60047285
has answer: http://stackoverflow.com/a/48817676
has answer: http://stackoverflow.com/a/48817835
has answer: http://stackoverflow.com/a/67005253
has comment: http://stackoverflow.com/comment/84639106
answer count: 13
favorite count: 0
has comment: http://stackoverflow.com/comment/84638904
has body: I am trying to have a user input whether or not they like spicy food and the output is supposed to be a boolean but I don't seem to be getting an output with my code below: def likes_spicyfood(): spicyfood = bool(input("Do you like spicy food? True or False?")) if spicyfood == ("True"): print("True") if spicyfood == ("False"): print("False") return(likes_spicyfood)
tagged with: python-3.x

http://stackoverflow.com/q/48842832
score: 0
answer count: 1
tagged with: python
has title: Access variables and lists from function
has comment: http://stackoverflow.com/comment/84691063
has body: I am new to unit testing with Python. I would like to test some functions in my code. In particular I need to test if the outputs have specific dimensions or the same dimensions. My Python script for unit testing looks like this: import unittest from func import * class myTests(unittest.TestCase): def setUp(self): # I am not really sure whats the purpose of this function def test_main(self): # check if outputs of the function "main" are not empty: self.assertTrue(main, msg = 'The main() function provides no return values!') # check if "run['l_modeloutputs']" and "run['l_modeloutputs']", within the main() function have the same size: self.assertCountEqual(self, run['l_modeloutputs'], run['l_dataoutputs'], msg=None) # --&gt; Doesn't work so far! # check if the dimensions of "props['k_iso']", within the main() function are (80,40,100): def tearDown(self): # I am also not sure of the purpose of this function if _name__ == "__main__": unittest.main() Here is the code under test: def main(param_file): # Load parameter file run, model, sequences, hydraulics, flowtrans, elements, mg = hu.model_setup(param_file) # some other code ... if 'l_modeloutputs' in run: if hydraulics['flag_gen'] is False: print('No hydraulic parameters generated. No model outputs saved') else: save_models(realdir, realname, mg, run['l_modeloutputs'], flowtrans, props['k_iso'], props['ktensors']) I need to access the parameters run['l_modeloutputs'] and run['l_dataoutputs'] of the main function from func.py. How can I pass the dimensions of these parameters to the unit testing script?
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48843765
type: UnansweredQuestion
tagged with: unit-testing
has comment: http://stackoverflow.com/comment/84691594
has comment: http://stackoverflow.com/comment/84690541
type: Question
has comment: http://stackoverflow.com/comment/84691559

http://stackoverflow.com/q/48941102
upvote count: 2
tagged with: python-2.7
downvote count: 4
has comment: http://stackoverflow.com/comment/84889227
has title: words that have same first and last characters in the list
has answer: http://stackoverflow.com/a/48941236
has answer: http://stackoverflow.com/a/48941785
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has body: I am trying to select words that have same first and last characters in the list below using Python : I know I need to use random_strings but I don't know how. ['xerox', 'trust', 'follow', 'blurb', 'maroon', 'ready', 'salad', 'yummy', 'evidence'] I am looking for this result: ['xerox', 'trust', 'blurb', 'yummy', 'evidence'] Thanks
tagged with: python
duplicate of: http://stackoverflow.com/q/19954593
answer count: 4
has answer: http://stackoverflow.com/a/48941207
type: Question
has comment: http://stackoverflow.com/comment/84889851
score: -2
linked to: http://stackoverflow.com/q/19954593
has answer: http://stackoverflow.com/a/48941129

http://stackoverflow.com/q/48873797
has comment: http://stackoverflow.com/comment/84751486
type: AnsweredQuestion
has title: Assign random to several values at a time
downvote count: 3
accepted answer: http://stackoverflow.com/a/48873836
upvote count: 1
has comment: http://stackoverflow.com/comment/84751491
type: Question
score: -2
tagged with: list-comprehension
tagged with: random
has comment: http://stackoverflow.com/comment/84751483
answer count: 1
has comment: http://stackoverflow.com/comment/84751537
favorite count: 0
has body: I'm trying to get used to list comprehensions, but I struggle with this- How can I assign random integers to several values at a time? My solution is this: a,b,c=random.sample(100, 3) But when I run code it gives me error: TypeError: Population must be a sequence or set. For dicts, use list(d). I think there shoud be solution to avoid simply repeating this three times like: a=random.randint(0,99) b=random.randint(0,99) c=random.randint(0,99)
tagged with: python
has answer: http://stackoverflow.com/a/48873836

http://stackoverflow.com/comment/84920097
type: QuestionComment
comment on: http://stackoverflow.com/q/48941432
score: 0
type: Comment
has text: @PYA, yes, the print does not return anything

http://stackoverflow.com/comment/84794928
type: QuestionComment
has text: `http` connections are usually stateless, so a sleep is a bit meaningless without some context. What exactly are you doing that requires it?
comment on: http://stackoverflow.com/q/48894535
score: 1
type: Comment

http://stackoverflow.com/comment/84803711
has text: alright! thank you so much! the popen seems to work! however, because there are other functions in the script, i need to test all the functionalities. do you know if the scripts that run in the /home/pi/.config/lxsession/LXDE-pi/autostart file are running as root?
comment on: http://stackoverflow.com/a/48899104
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84630609
type: Comment
has text: Looks like the `load` dictionary can be passed directly to the `loadmat`.
score: 1
comment on: http://stackoverflow.com/a/48813489
type: AnswerComment

http://stackoverflow.com/comment/84686046
type: Comment
has text: I used "print(is_numeric_dtype(dfs['ConditionScore']))" and it says true. I tried printing data[data['FinancialYear'] == '2009-10'] and it showed me all 30k columns with True where its '2009-10'. EDIT: When I do data.dtypes(), it says "'Series' object is not callable"
comment on: http://stackoverflow.com/a/48840788
type: AnswerComment
score: 0

http://stackoverflow.com/q/48940734
tagged with: odoo
type: Question
upvote count: 0
answer count: 1
downvote count: 5
tagged with: erp
favorite count: 0
has body: 1.I have two fields like "employee name" and "department".If i change the employee name in the first field,then the second filed("department") should be auto populate.please provide .py and .xml Thanx in advance
has answer: http://stackoverflow.com/a/48941369
has title: How to use onchange with many2one in odoo(formally openerp)
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84888476
score: -5

http://stackoverflow.com/a/49030391
type: Answer
score: 0
has body: I solved the issue and I share with you. output = [net_connect.send_command("ping", expect_string='#?'), net_connect.send_command("ip", expect_string=':?'), net_connect.send_command("192.168.1.254", expect_string=':?'), net_connect.send_command("1000", expect_string=':?'), net_connect.send_command("1500", expect_string=':?'), net_connect.send_command("2", expect_string=':?'), net_connect.send_command("n", expect_string=':?'), net_connect.send_command("n", expect_string=':?', delay_factor=140)] print output[-1] Best regards
answers question: http://stackoverflow.com/q/48915073

http://stackoverflow.com/comment/84626871
comment on: http://stackoverflow.com/q/48811189
score: 0
has text: The solution I've suggested is basically there (except you've swapped the df names now) but you need to clarify which df 'some_variable' needs to be x in. Both?
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84676974
type: Comment
comment on: http://stackoverflow.com/q/48833443
has text: If you aren't using mod_wsgi, why does it show mod_wsgi errors in the error logs you included.
score: 0
type: QuestionComment

http://stackoverflow.com/a/48873836
has body: The population of random.sample i.e. the first argument needs to be a sequence or a set, but you have given an integer. Based on what you want to get, range(101) as the population should do: In [41]: a, b, c = random.sample(range(101), 3) In [42]: a Out[42]: 16 In [43]: b Out[43]: 61 In [44]: c Out[44]: 13
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48873797
accepted answer of: http://stackoverflow.com/q/48873797
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48815134
has comment: http://stackoverflow.com/comment/84634161
has answer: http://stackoverflow.com/a/48815569
tagged with: python
score: 2
has comment: http://stackoverflow.com/comment/84634484
upvote count: 2
linked to: http://stackoverflow.com/q/1747817
has comment: http://stackoverflow.com/comment/84634135
has answer: http://stackoverflow.com/a/48815485
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84634083
has comment: http://stackoverflow.com/comment/84634308
has body: I'm having some issues trying to create a dictionary from 2 lists. I'm trying to get this as output. {1: {'name1', 'age1'}, 2: {'name2', 'age2'}, 3: {'name3', 'age3'}} My current code: (I'm new to coding so this is a mess and very efficient, and yes I do realize I'm running all code below 5 times) def Update(): for r in range(1,5): v1list.append(StringVar()) v2list.append(StringVar()) NameEntry = Entry(root, textvariable=v1list[r-1]).grid(row = r, column = 0, sticky=W) AgeEntry = Entry(root, textvariable=v2list[r-1]).grid(row = r, column = 4, sticky=W) for var1, var2 in ((a,b) for a in v1list for b in v2list): UserInput[r] = {var1.get(), var2.get()} print(UserInput) The output keeps pushing var1 and var2 forward resulting in this as output: {1: {''}, 2: {''}, 3: {''}, 4: {''}} I do actually see all inputs in there they just keep moving forward in the dictionary.
has title: Dictionary from 2 lists and a range?
has comment: http://stackoverflow.com/comment/84634335
type: Question
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48815485
favorite count: 0
has comment: http://stackoverflow.com/comment/84634540
possible better answer: http://stackoverflow.com/a/48815569

http://stackoverflow.com/a/48853756
downvote count: 0
score: 1
has body: CNNs are often confidently wrong. The filters you derived during training must have found similarities between features in roses and the dog image. If the CNN thinks a dog is a rose, then it thinks a dog is a rose. Simple as that. There wouldn't be an obvious test to check how certain it is that it is 80% certain. It can only tell you its 80% certain your dog is a rose. The model needs to be trained on more images to get better results. If you have a recurring/persistent confusion between two objects (i.e. dogs and roses) it can be a good idea to train the model with images of dogs as negative examples (either images with no features or by creating its own class). This way the model can learn what makes a rose distinctive from a dog.
has comment: http://stackoverflow.com/comment/84711032
upvote count: 1
has comment: http://stackoverflow.com/comment/84711192
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48853437
answers question: http://stackoverflow.com/q/48853437

http://stackoverflow.com/comment/84776292
has text: what is the response you're getting back?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48884829
type: Comment

http://stackoverflow.com/comment/84631961
type: Comment
comment on: http://stackoverflow.com/a/48807592
type: AnswerComment
score: 0
has text: This isn't really different from the code in the question, though, is it? The question already presented an implementation that uses `inlineCallbacks` to accomplish just what's being accomplished here with `addCallback`. So what's the difference?

http://stackoverflow.com/a/48849895
answers question: http://stackoverflow.com/q/48849731
type: Answer
has body: Since you are formatting the values into strings, you could do without the conversion from strings to integers: hour = alarm[0:2] minute = alarm[3:5] second = alarm[6:8] Also, instead of the % operator, I would use str.format() which is a more powerful string formatting method: print("\nsets to {}:{}:{}\n".format(hour, minute, second))
score: 0

http://stackoverflow.com/q/48952559
has title: Routing static pages with Flask or Bottle
type: UnansweredQuestion
score: 0
type: Question
has answer: http://stackoverflow.com/a/48952816
has body: When using: @route('/&lt;filename&gt;') def server_static(filename): return static_file(filename, root='.') it allows to serve the request www.example.com/helloworld with the static HTML file /myapp/helloworld. How to make www.example.com/anything be served by the static HTML file /myapp/html/anything.html, without having to hardcode each static filename anything in the Python code? Note: the tricky part is that the request is /anything (and not /anything.html), and the static file is /myapp/html/anything.html (there are 20 or more such files)
answer count: 1
tagged with: python
tagged with: bottle
has comment: http://stackoverflow.com/comment/84912096

http://stackoverflow.com/q/48885192
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48885282
has comment: http://stackoverflow.com/comment/129304668
upvote count: 1
has answer: http://stackoverflow.com/a/48885282
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48885277
has comment: http://stackoverflow.com/comment/84775076
linked to: http://stackoverflow.com/q/3389574
accepted answer: http://stackoverflow.com/a/48885440
has title: Python: Elegant solution to check if any substring is in list?
duplicate of: http://stackoverflow.com/q/3389574
score: 0
answer count: 3
has body: Before you close this, please try to understand the question - it's a bit different, but looks like a lot of downvoted questions. I'm looking for a simple way to check if any substrings of a string is in a list of strings. The input is like 2018_JAN_BGD, and I want to convert the month info in this to a (year-)quarter info. For example Q1 would be January, February and March. So I'm looking for a way to check if any of the substrings in 2018_JAN_BGD contains JAN, FEB or MAR. I could do this by writing 12 (for the whole year) if-else clauses with or's, but I feel like there's a more elegant solution in Python. I'm trying: def tellQuarter(month): Q1 = ('JAN','FEB','MAR') Q2 = ('APR','MAY','JUN') Q3 = ('JUL','AUG','SEP') Q4 = ('OCT','NOV','DEC') if any(for mon in Q1 in month): return ("Q1") if any(for mon in Q2 in month): return ("Q2") This is of course incorrect (invalid syntax), but I can't figure out how to put this correctly. Basically, I want to loop through Q1, and check if any of the strings is a substring of month. I mean I can do for mon in Q1: if mon in month: return "Q1" but isn't there a more elegant, single-line solution to this?
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/84774996
tagged with: python
has answer: http://stackoverflow.com/a/48885440

http://stackoverflow.com/comment/84804959
type: QuestionComment
comment on: http://stackoverflow.com/q/48899523
has text: Because `replace` is jimja's template filter and it is not available in django's default template engine. You can not use jinja's template filters from django's template engine you have to setup jinja as your template engine in your django app
score: 2
type: Comment

http://stackoverflow.com/comment/84675457
score: 0
type: Comment
has text: Does sendto() actually execute, or hang? What value does it return? It should be the number of bytes sent.
type: QuestionComment
comment on: http://stackoverflow.com/q/48835275

http://stackoverflow.com/comment/84810534
has text: Tbh, I do not understand the question? What are n, k and a? Why do you sort it? Because of your `A(i)` relation to `i+1`, I think you are at this the wrong way but you do not provide enough information.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48902114
type: QuestionComment

http://stackoverflow.com/a/48852083
answers question: http://stackoverflow.com/q/48851820
type: AcceptedAnswer
score: 4
type: Answer
has comment: http://stackoverflow.com/comment/84720788
downvote count: 0
upvote count: 4
has body: Simpliest is factorize with joined columns together: df['Invoice'] = pd.factorize(df['Date'].astype(str) + df['Assistant_name'])[0] + 1 print (df) product Date Assistant_name Invoice 0 product_1 2017-01-02 11:45:00 John 1 1 product_2 2017-01-02 11:45:00 John 1 2 product_3 2017-01-02 11:55:00 Mark 2 If performance is important use pd.lib.fast_zip: df['Invoice']=pd.factorize(pd.lib.fast_zip([df.Date.values, df.Assistant_name.values]))[0]+1 Timings: #[30000 rows x 3 columns] df = pd.concat([df] * 10000, ignore_index=True) In [178]: %%timeit ...: df['Invoice'] = list(zip(df['Date'], df['Assistant_name'])) ...: df['Invoice'] = df['Invoice'].astype('category').cat.codes + 1 ...: 9.16 ms ± 54.8 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [179]: %%timeit ...: df['Invoice'] = pd.factorize(df['Date'].astype(str) + df['Assistant_name'])[0] + 1 ...: 11.2 ms ± 395 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) In [180]: %%timeit ...: df['Invoice'] = pd.factorize(pd.lib.fast_zip([df.Date.values, df.Assistant_name.values]))[0] + 1 ...: 6.27 ms ± 93.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
accepted answer of: http://stackoverflow.com/q/48851820

http://stackoverflow.com/q/48853437
type: AnsweredQuestion
type: Question
has title: How do I check if Tensorflow-algorith is actually trained for image?
accepted answer: http://stackoverflow.com/a/48853756
tagged with: python
answer count: 1
score: 0
tagged with: tensorflow
has body: I used the "Tensorflow For Poets" example from https://codelabs.developers.google.com/codelabs/tensorflow-for-poets/#7. It worked as it should, but when it was given an image completely different (used a photo of a dog, when it was trained for flowers) it gave back a prediction for one of the values with more than 80% certainty, though it was completely wrong. My question is: how can it also check how certain it is that it is trained for a specific image? Here is the output: roses 0.8071102 tulips 0.20286822 daisy 2.0703827e-05 sunflowers 7.838418e-07 dandelion 3.357079e-08
has answer: http://stackoverflow.com/a/48853756

http://stackoverflow.com/a/48870443
has comment: http://stackoverflow.com/comment/84747447
accepted answer of: http://stackoverflow.com/q/48870171
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84746562
upvote count: 2
answers question: http://stackoverflow.com/q/48870171
has body: Your code looks mainly fine, but you can notice that you always encrypt, whatever mode you choose. This is caused by your if mode == 'encrypt' or 'e': line. Because or has a lower operator precedence than ==, this gets parsed as: if (mode == 'encrypt') or 'e': As mode is 'd', (mode == 'encrypt') is False. But as 'e' is a non-empty string, it evaluates to True in boolean context. So, (mode == 'encrypt') or 'e' is always True, whatever mode you choose. What you need is: if mode == 'encrypt' or mode =='e':
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84678885
has text: `scipy.interpolate.interp1d` - you have read its documentation right?
comment on: http://stackoverflow.com/q/48836873
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84751191
type: Comment
comment on: http://stackoverflow.com/q/48873638
score: 0
type: QuestionComment
has text: What is `id('afk')`?

http://stackoverflow.com/a/48942188
answers question: http://stackoverflow.com/q/48941964
score: 0
type: Answer
has body: It's basically saying that if, on the left hand side of your assignment statement, you have values that are repeated, in this case i, then the assigning of values will take place left-to-right, so you start with the left-most value (i), assign it, then assign the next one (x[i]), and so on. Edit: @iBug said it better.

http://stackoverflow.com/q/48885984
tagged with: python
has answer: http://stackoverflow.com/a/48932817
upvote count: 14
answer count: 3
has answer: http://stackoverflow.com/a/49883007
has body: My OSX install of Cassandra seems to have been broken by yesterday's release. Cassandra seems to start OK. Jeremys-MacBook-Pro: fractal jeremy$ cqlsh --version cqlsh 5.0.1 Jeremys-MacBook-Pro:fractal jeremy$ cqlsh localhost Traceback (most recent call last): File "/usr/local/Cellar/cassandra/3.11.2/libexec/bin/cqlsh.py", line 2443, in &lt;module&gt; main(*read_options(sys.argv[1:], os.environ)) File "/usr/local/Cellar/cassandra/3.11.2/libexec/bin/cqlsh.py", line 2421, in main encoding=options.encoding) File "/usr/local/Cellar/cassandra/3.11.2/libexec/bin/cqlsh.py", line 488, in __init__ **kwargs) File "cassandra/cluster.py", line 735, in cassandra.cluster.Cluster.__init__ (cassandra/cluster.c:10935) TypeError: __init__() got an unexpected keyword argument 'no_compact'
has title: Was cqlsh 5.0.1 broken in cassandra 3.11.2 release?
has answer: http://stackoverflow.com/a/48886832
downvote count: 0
tagged with: cqlsh
type: UnansweredQuestion
tagged with: cassandra
score: 14
has comment: http://stackoverflow.com/comment/84913148
has comment: http://stackoverflow.com/comment/84780196
has comment: http://stackoverflow.com/comment/85162428
has comment: http://stackoverflow.com/comment/85363582
favorite count: 0
type: Question

http://stackoverflow.com/comment/84641275
comment on: http://stackoverflow.com/a/48809143
type: AnswerComment
has text: @PrabakaranC: You can write a loop, create N "diff" columns, and then use `.any(axis=0)` to check them all at the end.
type: Comment
score: 0

http://stackoverflow.com/q/48833794
type: Question
tagged with: python
has answer: http://stackoverflow.com/a/48836385
duplicate of: http://stackoverflow.com/q/14824456
has body: I have a Dataframe with 14 rows and 7 columns where the columns represent groups and the rows represent months. I am trying to create a grouped bar plot such that at each month (on the x-axis) I will have the values for each of the groups as bars. The code is simply ax = df.plot.bar(width=1,color=['b','g','r','c','orange','purple','y']); ax.legend(loc='center left', bbox_to_anchor=(1.0, 0.5)) ax.set_xticklabels(months2,rotation=45) Which produces the following result: I would like to make the individual bars in each group wider but without them overlapping and I would also like to increase the distance between each group of bars so that there is enough space in the plot. It might be worth mentioning that the index of the dataframe is 0,...,13.
upvote count: 1
answer count: 1
tagged with: charts
tagged with: matplotlib
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/332289
tagged with: pandas
duplicate of: http://stackoverflow.com/q/332289
downvote count: 0
has title: Change distance between bar groups in grouped bar chart
score: 1
favorite count: 0

http://stackoverflow.com/q/48843193
upvote count: 4
type: AnsweredQuestion
tagged with: python-3.5
downvote count: 0
has answer: http://stackoverflow.com/a/72226713
duplicate of: http://stackoverflow.com/q/6633523
has comment: http://stackoverflow.com/comment/132555633
favorite count: 0
type: Question
accepted answer: http://stackoverflow.com/a/48843224
tagged with: python
score: 4
has answer: http://stackoverflow.com/a/48845430
possible better answer: http://stackoverflow.com/a/48845430
has comment: http://stackoverflow.com/comment/84691653
answer count: 3
has answer: http://stackoverflow.com/a/48843224
has title: Convert a number using atof
has comment: http://stackoverflow.com/comment/84691712
has body: In Python 3.5, I'd like to convert a German number string to a float using locale.atof with the following code: import locale from locale import atof locale.setlocale(locale.LC_ALL, 'de_DE') number = atof('17.907,08') However, this raises a ValueError: ValueError: could not convert string to float: '17.907.08' Why? Isn't this exactly what atof() was made for?
linked to: http://stackoverflow.com/q/6633523

http://stackoverflow.com/a/48933083
score: 1
upvote count: 1
has body: you are missing the path to your home directory in the urlpatterns urlpatterns = [ path('admin/', admin.site.urls), url(r'^aggregator/', include('aggregator.urls')), url(r'^bouncer/', include('bouncer.urls')), url(r'^$', views.yourhomeview), ]
downvote count: 0
answers question: http://stackoverflow.com/q/48932839
type: Answer

http://stackoverflow.com/comment/84789073
score: 0
type: AnswerComment
has text: Hmm, OK thank you for re-affirming that there isn't a better way. I ended up going with a variant of attempt 2.
type: Comment
comment on: http://stackoverflow.com/a/48874204

http://stackoverflow.com/comment/84903510
comment on: http://stackoverflow.com/q/48948662
has text: Read the docs: https://docs.python.org/3/library/stdtypes.html#str.join
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48863734
has comment: http://stackoverflow.com/comment/84749022
tagged with: jsonb
has comment: http://stackoverflow.com/comment/84749581
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/78300979
favorite count: 0
tagged with: postgresql
type: UnansweredQuestion
tagged with: python
has body: I have a jsonb column named "randomblocks" in my postgres database table "blocks" having data similar to the json: { "block": { "1": { "color": [ "black", "white" ] }, "2": { "color": [ "grey", "silver" ] } } } If I wanted to delete the "block" > "2", the query according to postgres documentation would be similar to: UPDATE blocks SET randomblocks = randomblocks #- '{block,2}' where blockid=1; At the moment I am stuck with raw query which is not an elegant way to achieve this: stmt = text("UPDATE blocks SET randomblocks = randomblocks #- '{block, :x}' where blockid= :y") stmt = stmt.bindparams(x=2, y=1) db.session.execute(stmt) How to write the same query using sqlalchemy without using the raw query and preferably the orm way if possible?
has comment: http://stackoverflow.com/comment/84747494
score: 2
upvote count: 2
tagged with: sqlalchemy
has title: How to use jsonb - and #- to delete in sqlalchemy
type: Question

http://stackoverflow.com/q/48846953
tagged with: python
has body: Is it possible to turn this program I have written into a single recursion function that ignores case differences, white spaces, and non-English letters? For example, the program must be able to return "True" to the following string, ignoring the uppercase "R" and the period."Rats live on no evil star.". No imports, only one function and the only the method that can be used is isalpha(). def main() : inputStr = input("Enter a string: ") if isPalindrome(inputStr) : print("That's a palindrome.") else: print("That isn't a palindrome.") def isPalindrome(string) : if len(string) &lt;= 1 : return True if string[0].lower() == string[len(string) - 1].lower() : return isPalindrome(string[1:len(string) - 1]) else : return False main()
has answer: http://stackoverflow.com/a/49098325
type: Question
tagged with: recursion
has title: A single palindrome recursive function
has answer: http://stackoverflow.com/a/48847028
has comment: http://stackoverflow.com/comment/84699320
has answer: http://stackoverflow.com/a/48849675
score: 0
answer count: 3
tagged with: palindrome
tagged with: isalpha
type: UnansweredQuestion

http://stackoverflow.com/comment/84900773
comment on: http://stackoverflow.com/q/48947026
type: Comment
type: QuestionComment
has text: Why would you need smth like that? "*2 variable number of argument*" makes no sense because the 2nd variable arument number would be automatically invalidated by the 1st. If you can't make it using `*args, **kwargs`, then either the design is poor, or *Python* is not the appropriate language for this task.
score: 1

http://stackoverflow.com/a/48847710
answers question: http://stackoverflow.com/q/48836493
has body: When the client requests the websocket connection via const socket = io(‘ws://localhost:5000’); it will have to wait until the connection is established first, before it can do anything with the message. The connection is established only when @socketio.on(‘connect’) def ... is finished. So it looks like the client waits until all the emit is done, and then start reacting to the messages. You probably need to make your for-loop asynchronous so that the server responds to the client about the connection first before it emits the data. For example, you can carve out the for-loop into a separate function and use flask’s background task: @socketio.on(‘connect’) def dataSent(): print(‘...’) socketio.start_background_task(target=emitloop) def emitloop(): for i in range(2,6): socketio.emit(‘data update’, i) time.sleep(1) (If flask is configured to use gevent for the background task, then you’ll need to install gevent or flask’s gevent plug-in.) You might also try to use function based setState (i.e. passing a function to setState rather than the state object), because setState is asynchronous and react can combine them together otherwise.
upvote count: 1
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/a/48826044
has comment: http://stackoverflow.com/comment/84657136
has comment: http://stackoverflow.com/comment/84658476
type: Answer
has comment: http://stackoverflow.com/comment/84656153
has comment: http://stackoverflow.com/comment/84656767
has comment: http://stackoverflow.com/comment/84657080
has comment: http://stackoverflow.com/comment/84655605
answers question: http://stackoverflow.com/q/48825587
score: 0
has comment: http://stackoverflow.com/comment/84656345
has body: Looking at this answer. This should work perfectly: feeds = html.findAll(type='application/rss+xml') + html.findAll(type='application/atom+xml') Trying that on the CNN RSS service works perfectly. Your main problem is that the edition.cnn.com does not have any traces of RSS in any way or fashion.

http://stackoverflow.com/comment/84804541
comment on: http://stackoverflow.com/q/48899523
has text: search for engine or template or render like keywords in the traceback
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84677412
type: Comment
comment on: http://stackoverflow.com/a/48836179
has text: Hello, thank you for the quick replay, but behaviour is still the same ;(
score: 0
type: AnswerComment

http://stackoverflow.com/q/48947106
has answer: http://stackoverflow.com/a/48948837
has title: How can I remove the outer area of ​a circle with opencv and python
downvote count: 0
score: 1
favorite count: 0
type: Question
has answer: http://stackoverflow.com/a/48950043
upvote count: 1
tagged with: python
tagged with: opencv
has body: I need to remove the outer area of ​​the circle. I need to use only the inner area of ​​the circle to avoid errors in image processing, currently I can only find the circle and mark it I do not know if I'm doing it right, using cv2.circle Please help me circles = cv2.HoughCircles(cinza, cv2.HOUGH_GRADIENT, 1, 20) if circles is not None: maior = 0 circles = np.uint16(np.around(circles)) for i in circles[0, :]: radius = i[2] if radius &gt; maior: maior = radius for i in circles[0, :]: center = (i[0], i[1]) radius = i[2] if radius == maior: cv2.circle(image, center, 1, (0, 100, 100), 3) cv2.circle(image, center, radius, (255, 0, 255), 3)
answer count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84904537

http://stackoverflow.com/comment/84860893
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48927271
has text: @GordonLinoff : it gives out an error that it is an undefined function

http://stackoverflow.com/comment/84820062
score: 0
has text: Sure Sven Festersen.. I'll try using subprocess module. Thanks :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48906886

http://stackoverflow.com/comment/84648372
has text: this was super helpful and easy to understand. Thanks so much , really helped!!
type: AnswerComment
comment on: http://stackoverflow.com/a/48821805
score: 0
type: Comment

http://stackoverflow.com/q/48954246
has comment: http://stackoverflow.com/comment/84934805
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48963987
tagged with: python
tagged with: computer-vision
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84915783
tagged with: image-processing
has title: Find sudoku grid using OpenCV and Python
has comment: http://stackoverflow.com/comment/84915417
has body: I'm trying to detect the grid in sudoku puzzles using OpenCV but I'm having troubles with the last steps (I guess). What I'm doing is: Downsaple the image Blur it Applying a highpass filter (bilateral) Thresholding the image, using adaptive threshold Some dilations and erosions All this gives me the following images: From now on, I need to detect the grid, and I found a few methods of how to do that but none of them gave me the confidence of being robust enough. The first one is to find lines using Hough transform but I find a lot of spurious lines. The other is using connected components, which gives me the best results. I tried to implement RANSAC as a way to get the right centroids, but I'm not having good results and also takes a while to get the answer ("a while" is less than 2 seconds, but later I want to use it in real time video). Any idea how this can be done? I mean, how can I discard the wrong centroids and start solving the sudoku?
has comment: http://stackoverflow.com/comment/108299761
has comment: http://stackoverflow.com/comment/84915251
type: Question
upvote count: 15
tagged with: opencv
has answer: http://stackoverflow.com/a/48963987
downvote count: 0
has comment: http://stackoverflow.com/comment/84915557
score: 15

http://stackoverflow.com/q/48960670
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48960768
downvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/84927660
has body: i am trying to write a program which takes strings and width as input and gives an input: ABCDEFGHIJKLIMNOQRSTUVWXYZ 4 and gives an output as(in newline): ABCD \n EFGH \n IJKL \n IMNO \n QRST \n UVWX \n YZ I wrote this code: def wrap(string, max_width): while 0 &lt; len(string) &lt; 1000 and 0 &lt; max_width &lt; len(string): print (textwrap.fill(string,max_width)) while True: try: string = input() max_width = int(input()) except EOFError: print("EOFError") break What can i do to solve this problem, I am still new to programming. The error message which i got was: Original exception was: Traceback (most recent call last): File "try2.py", line 8, in &lt;module&gt; max_width = int(input()) ValueError: invalid literal for int() with base 10: ''
score: -1
has comment: http://stackoverflow.com/comment/84927757
tagged with: python-3.6
upvote count: 1
answer count: 1
has title: max_width = int(input()) ValueError: invalid literal for int() with base 10: ''
favorite count: 0
accepted answer: http://stackoverflow.com/a/48960768

http://stackoverflow.com/q/48910863
has body: I am trying to create a simple Chatbot application UI using Kivy and Python but I'm stuck at the very first stage. How do I access the TextInput widget inside the BoxLayout to fetch it's contents? I read that the function on_text_validate() is called whenever you press 'Enter' on the TextInput. However this code down below doesn't seem to be functioning. from kivy.app import App from kivy.uix.boxlayout import BoxLayout from kivy.uix.label import Label from kivy.uix.textinput import TextInput from kivy.uix.screenmanager import Screen, ScreenManager, FadeTransition from kivy.uix.scrollview import ScrollView from kivy.properties import StringProperty from kivy.lang import Builder Builder.load_string(''' #:import AnchorLayout kivy.uix.anchorlayout #:import Layout kivy.uix.layout &lt;ChatBotScreen&gt;: BoxLayout: orientation: 'vertical' ScrollView: Label: size_hint_y: None height: self.texture_size[1] text_size: self.width, None botOutput: root.botOutput ScrollView: Label: size_hint_y: None height: self.texture_size[1] text_size: self.width, None userInput: root.userInput TextInput: id: ti_userinput multiline: False ''') class ChatBotScreen(Screen): userInput = StringProperty() botOutput = StringProperty() def on_text_validate(self): text_input_userInput = self.ids['ti_userinput'].text self.ids['ti_userinput'].text = '' print(text_input_userInput) def UserInput(self): pass def BotOutput(self): pass sm = ScreenManager(transition=FadeTransition()) sm.add_widget(ChatBotScreen(name='mainchat')) class MyApp(App): def build(self): return sm Please guide me.
tagged with: oop
has comment: http://stackoverflow.com/comment/84828631
has title: How do I define what happens when user enter's text in TextInput and presses enter in Kivy?
score: 1
has comment: http://stackoverflow.com/comment/84829184
has answer: http://stackoverflow.com/a/48911766
accepted answer: http://stackoverflow.com/a/48911766
upvote count: 1
has comment: http://stackoverflow.com/comment/84829455
tagged with: user-interface
answer count: 1
has comment: http://stackoverflow.com/comment/84829240
favorite count: 0
tagged with: python
tagged with: kivy
type: AnsweredQuestion
tagged with: kivy-language
downvote count: 0
type: Question

http://stackoverflow.com/comment/84783127
type: Comment
comment on: http://stackoverflow.com/a/48888264
has text: https://en.wikipedia.org/wiki/Nearest_neighbor_search#Exact_methods discusses using a KD-tree for this problem
score: 0
type: AnswerComment

http://stackoverflow.com/q/48814204
answer count: 2
upvote count: 0
possible better answer: http://stackoverflow.com/a/48821947
has title: From cooccurrence matrix to edges list data separation
accepted answer: http://stackoverflow.com/a/48822936
tagged with: python
favorite count: 0
tagged with: list
score: -3
has comment: http://stackoverflow.com/comment/84649671
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48822936
has body: i have a huge cooccurence matrix with indexes as skill_id and column names as skill_id, and the matrix is filled with the co-occurence of the same. please find the sample below I want the data in a 3 column dataframe: skillid1 skillid2 count Any help would be highly appreciated.
downvote count: 3
has comment: http://stackoverflow.com/comment/84632055
type: Question
has answer: http://stackoverflow.com/a/48821947

http://stackoverflow.com/a/49073208
upvote count: 4
score: 4
accepted answer of: http://stackoverflow.com/q/48954080
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48954080
downvote count: 0
has body: When using pandas.read_csv in threads it appears that the Python process leaks a little memory. I've reduced it to a problem with pandas.read_csv and a concurrent.futures.ThreadPoolExecutor. This is raised on the Pandas issue tracker here: https://github.com/pandas-dev/pandas/issues/19941 # imports import pandas as pd import numpy as np import time import psutil from concurrent.futures import ThreadPoolExecutor # prep process = psutil.Process() e = ThreadPoolExecutor(8) # prepare csv file, only need to run once pd.DataFrame(np.random.random((100000, 50))).to_csv('large_random.csv') # baseline computation making pandas dataframes with threasds. This works fine def f(_): return pd.DataFrame(np.random.random((1000000, 50))) print('before:', process.memory_info().rss // 1e6, 'MB') list(e.map(f, range(8))) time.sleep(1) # let things settle print('after:', process.memory_info().rss // 1e6, 'MB') # before: 57.0 MB # after: 56.0 MB # example with read_csv, this leaks memory print('before:', process.memory_info().rss // 1e6, 'MB') list(e.map(pd.read_csv, ['large_random.csv'] * 8)) time.sleep(1) # let things settle print('after:', process.memory_info().rss // 1e6, 'MB') # before: 58.0 MB # after: 323.0 MB
type: Answer

http://stackoverflow.com/comment/84674671
has text: In `get_user_info` you call `make_connection_to_user` without an argument. `make_connection_to_user` expects an argument to be provided.
comment on: http://stackoverflow.com/q/48834988
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/116703815
type: Comment
score: 1
comment on: http://stackoverflow.com/a/51973175
has text: the dictionary of bucket name and key is actually the recommended way of specifying CopySource. Ref: https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Object.copy_from
type: AnswerComment

http://stackoverflow.com/comment/84701393
type: Comment
type: QuestionComment
has text: by changing the arr = array(img, dtype="float32") to np. array(img, dtype="float32") work for me
comment on: http://stackoverflow.com/q/48815087
score: 0

http://stackoverflow.com/a/48935948
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48935831
has comment: http://stackoverflow.com/comment/84879888
downvote count: 0
has body: List comprehension is probably a great way to go. It works nicely because of your constraints. You probably want something like: [[i,j,k] for i in l[0] for j in l[1] if j&gt;i for k in l[2] if k&gt;j] &gt;&gt;&gt; [[1, 4, 5], [1, 4, 10], [1, 8, 10], [2, 4, 5], [2, 4, 10], [2, 8, 10], [3, 4, 5], [3, 4, 10], [3, 8, 10]] This makes a list of lists of the form [i,j,k] for all the i's in l[0] for all the j's in l[1] if j>i and for all the k's in l[2] if k>j (since we already know that j>i at this point) However, the code above only works for an input list of list of length 3. Took me a little bit, but this recursive approach should work for a input list of any length def list_of_lists(in_list): full_list=[] def recurse(so_far, l): if l==len(in_list): return so_far next_list = in_list[l] for i in next_list: if i&gt;so_far[-1]: new_list = recurse(so_far.copy()+[i], l+1) if new_list: full_list.append(new_list) for i in in_list[0]: recurse([i],1) return full_list
type: Answer

http://stackoverflow.com/a/48827172
has body: A list comprehension would help with a generator expression inside to prevent duplicate function calls: &gt;&gt;&gt; [int(i) for i in (math.sqrt(i) for i in terms) if i.is_integer()] [1, 2, 3, 4, 6] Or if you want a purely functional approach, since you suggest using filter() in your post: &gt;&gt;&gt; list(map(int, filter(float.is_integer, map(math.sqrt, terms)))) [1, 2, 3, 4, 6] Of course this can be written out with a regular for loop, which is less performant but totally acceptable, particularly given the OP seems new to Python: lst = [] for i in terms: s = math.sqrt(i) if s.is_integer(): lst.append(int(s))
type: Answer
has comment: http://stackoverflow.com/comment/84658482
upvote count: 6
has comment: http://stackoverflow.com/comment/84658760
has comment: http://stackoverflow.com/comment/84658252
score: 6
has comment: http://stackoverflow.com/comment/84658321
has comment: http://stackoverflow.com/comment/84671933
downvote count: 0
answers question: http://stackoverflow.com/q/48827130

http://stackoverflow.com/comment/84930978
comment on: http://stackoverflow.com/q/48962292
has text: Are you processing a Windows or Mac file with Python 2? If so `\n` is not necessarily the line terminator, and `split()` will not work as you expect. Try opening the file in universal new line mode: `open(path, 'ru')`
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48811312
score: 5
has answer: http://stackoverflow.com/a/79524282
upvote count: 5
has answer: http://stackoverflow.com/a/48812276
has comment: http://stackoverflow.com/comment/88559187
possible better answer: http://stackoverflow.com/a/52723647
downvote count: 0
has answer: http://stackoverflow.com/a/52723647
has body: I am trying to install ffmpeg in order to use it on OpenAI to record videos. I have installed it using brew install ffmpeg but somehow when I compile my code I get the same error, it is like the package is not recognized by my virtualenv where I am working. Error on Python console: raise error.DependencyNotInstalled("""Found neither the ffmpeg nor avconv executables. On OS X, you can install ffmpeg via `brew install ffmpeg`. On most Ubuntu variants, `sudo apt-get install ffmpeg` should do it. On Ubuntu 14.04, however, you'll need to install avconv with `sudo apt-get install libav-tools`.""") However, when I execute which ffmpeg I got the following path /usr/local/bin/ffmpeg. It seems like that Anaconda for example needs a specific command to install this package into its environment, it is the same for virtualenv? Thanks in advance.
tagged with: virtualenv
has answer: http://stackoverflow.com/a/78514189
favorite count: 0
answer count: 5
accepted answer: http://stackoverflow.com/a/48812276
tagged with: python
has title: Install ffmpeg in to virtual environment
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/65715908
tagged with: ffmpeg
has comment: http://stackoverflow.com/comment/88484733
linked to: http://stackoverflow.com/q/8481083
type: Question
linked to: http://stackoverflow.com/q/16748148

http://stackoverflow.com/comment/84834504
comment on: http://stackoverflow.com/q/48913801
type: QuestionComment
type: Comment
score: 2
has text: How do you create said series? Series are usually 1 dimensional.... what do you get when you do `df.values`

http://stackoverflow.com/a/48963393
score: 4
accepted answer of: http://stackoverflow.com/q/48963215
upvote count: 4
answers question: http://stackoverflow.com/q/48963215
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84932833
type: Answer
has body: What you're looking to do is replace each entry in your original array x by its index in the array of unique elements of x (in sorted order). For example, if x is np.array([7, 6, 2, 7, 7, 2]), the unique elements of x are [2, 6, 7], and we want to replace each number with its position in that array of unique elements: that is, replace each 2 with 0, each 6 with 1 and each 7 with 2. The numpy.unique function does both these jobs: it finds the (sorted) array of unique elements for you, and if you pass return_inverse=True, np.unique will also give you a second return value that contains exactly the indices you're after. So all you need to do is call np.unique with return_inverse=True, throw away the first return value, and keep the second. Examples: &gt;&gt;&gt; import numpy as np &gt;&gt;&gt; np.unique([5, 0, 5, 2, 5], return_inverse=True)[1] array([2, 0, 2, 1, 2]) &gt;&gt;&gt; x = np.array([4, 5, 3, 0, 4, 5, 3, 0, 2, 5, 2, 3, 2, 4, 4]) &gt;&gt;&gt; np.unique(x, return_inverse=True)[1] array([3, 4, 2, 0, 3, 4, 2, 0, 1, 4, 1, 2, 1, 3, 3])

http://stackoverflow.com/a/48893477
has comment: http://stackoverflow.com/comment/84794792
has comment: http://stackoverflow.com/comment/84792880
has body: Seems like you need df.groupby(df.Marker.eq(20).cumsum()).Marker.value_counts() Out[1013]: Marker Marker 0 21 1 1 20 1 21 1 2 2 1 20 1 22 1 23 1 Name: Marker, dtype: int64 Update df=df.assign(yourid=df.Marker.eq(20).cumsum()) df.loc[(df.yourid&lt;df.yourid.max())&amp;(df.yourid&gt;df.yourid.min())&amp;(df.Marker!=20),:].groupby('yourid').Marker.value_counts() Out[1021]: yourid Marker 1 21 1 Name: Marker, dtype: int64
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/48893307
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48893307

http://stackoverflow.com/a/48873795
has comment: http://stackoverflow.com/comment/84751848
has comment: http://stackoverflow.com/comment/84769088
upvote count: 1
type: Answer
has body: Opening websites: import webbrowser # pre-installed with python url = 'www.google.co.uk' webbrowser.open(url) Opening files (Windows): import os # pre installed os.startfile('file directory') # e.g "G:/Documents/School/image.png" For more details and methods regarding the webbrowser and os modules check out: https://docs.python.org/2/library/webbrowser.html https://docs.python.org/3/library/os.html Heres a mini UI that takes a barcode and either opens a file or webpage: import os from tkinter import * import webbrowser class Application(Frame): def __init__ (self, master): Frame.__init__(self,master) self.grid() b = StringVar() b.set("Enter barcode") self.barcode = Entry(self, textvariable = b) self.barcode.grid(row=0, column=1, sticky='n') self.submit = Button(self, text = "Submit", command = self.get_barcode) self.submit.grid(row=1, column=1, sticky='s') def get_barcode(self): barcode = int(self.barcode.get()) if barcode == 000: url = "www.google.co.uk" webbrowser.open(url) elif barcode == 111: os.startfile("C:\Program Files\Internet Explorer\iexplore.exe") else: print("invalid barcode or something") root= Tk() app = Application(root) root.mainloop() Obviously i haven't added any validation, but you can do this easily and perhaps even add some pop-up dialogues for the validation.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48862699

http://stackoverflow.com/comment/84917218
type: QuestionComment
comment on: http://stackoverflow.com/q/48951629
has text: It returns an invalid parameter error when I pass in `None`. It wants only nothing passed in, or `str` values, and even then, only particular strings. The library function is a boto3 call to boto3.client('cognito-idp').admin_create_user(), but I was trying to keep the question more general. https://boto3.readthedocs.io/en/latest/reference/services/cognito-idp.html#CognitoIdentityProvider.Client.admin_create_user
score: 0
type: Comment

http://stackoverflow.com/a/48897289
downvote count: 0
type: Answer
upvote count: 1
has body: You can append dataframes after they are created like so: candidatos1.append(candidatos2,ignore_index=True).append(candidatos3,ignore_index=True) You could concatenate the text files first and then load into Pandas but that's outside of Pandas.
score: 1
answers question: http://stackoverflow.com/q/48897215

http://stackoverflow.com/a/48937066
answers question: http://stackoverflow.com/q/48936649
has comment: http://stackoverflow.com/comment/84919254
score: 0
has comment: http://stackoverflow.com/comment/84935638
accepted answer of: http://stackoverflow.com/q/48936649
type: AcceptedAnswer
type: Answer
has body: There's no need for anything fancy. defaultdict is included in Python's standard library. It's an improved dictionary. I've used it here because it obviates the need to initialise entries in a dictionary. This means that I can write, for instance, result[id] = max(result[id], version). If no entry exists for id then defaultdict creates one and puts version in it (because it's obvious that this will be the maximum). I read through the lines in the input file, one at a time, discarding end-lines and blanks, splitting on the commas, and then use map to apply the int function to each string produced. I ignore the first line in the file simply be reading it and assigning its contents to a variable that I have arbitrarily called ignore. Finally, just to make the results more intelligible, I sort the keys in the dictionary, and present the contents of it in order. &gt;&gt;&gt; from collections import defaultdict &gt;&gt;&gt; result = defaultdict(int) &gt;&gt;&gt; with open('to_dict.txt') as input: ... ignore = input.readline() ... for line in input: ... id, version = map(int, line.strip().replace(' ', '').split(',')) ... result[id] = max(result[id], version) ... &gt;&gt;&gt; ids = list(result.keys()) &gt;&gt;&gt; ids.sort() &gt;&gt;&gt; for id in ids: ... id, result[id] ... (3, 1) (11, 3) (20, 2) (400, 2) EDIT: With that much data it becomes a different question, in my estimation, better processed with pandas. I've put the df.groupby(['ful_id']).version.idxmax() bit in to demonstrate what I've done. I group on ful_id, then ask for the maximum value of version and the index of the maximum value, all in one step using idxmax. Although pandas displays this as a two-column table the result is actually a list of integers that I can use to select rows from the dataframe. That's what I do with df.iloc[df.groupby(['ful_id']).version.idxmax(),:]. Here the df.groupby(['ful_id']).version.idxmax() part identifies the rows, and the : part identifies the columns, namely all of them. Tha…
has comment: http://stackoverflow.com/comment/84905573

http://stackoverflow.com/a/51727737
has body: Update: from the history of the file clustering_ops.py (master branch), it seems that the additional value (cluster_centers_vars) was removed in the following commit from 6.Oct, i.e. shortly after its introduction. That means that your initial code should be working perfectly with more recent versions of TF, i.e. (all_scores, cluster_idx, scores, cluster_centers_initialized, init_op, train_op) = kmeans.training_graph() should be now again ok. However, the consequence is that you cannot get the cluster centers through the kmeans.training_graph() function. If you want to get the cluster centers, there are two solutions. The first solution is simple, namely using the KMeansClustering Estimator, which is defined in the file kmeans.py. More specifically, you can use the method KMeansClustering.cluster_centers(). The second solution is rather a workaround. If you do not use the KMeansClustering Estimator, but only the KMeans graph constructor defined in the file clustering_ops.py, then you can still get the cluster centers by reading the global TF variable ´clusters:0´: tf_vble_cluster_centers = tf.global_variables('clusters:0')[0] # get the global TF variable 'clusters:0' cluster_centers = sess.run(tf_vble_cluster_centers) # evaluate its contents print(cluster_centers.shape) # nr. rows = nr. of clusters, nr. columns = nr. dimensions print(cluster_centers[0]) # print cluster centers for the first cluster
type: Answer
upvote count: 2
answers question: http://stackoverflow.com/q/48814591
score: 2
downvote count: 0

http://stackoverflow.com/comment/94063432
score: 0
type: Comment
has text: Thank you!!! I have found several other posts with similar solutions and no one was able to write a simple solution without paragraphs of gibberish. Thanks for keeping it simple! - This solved my problem immediately.
comment on: http://stackoverflow.com/a/48823691
type: AnswerComment

http://stackoverflow.com/q/48911463
has body: I am running the following code: import pygame pygame.init() img = pygame.image.load("Picture.jpg") white = (255, 255, 255) w = 900 h = 450 screen = pygame.display.set_mode((w, h)) screen.fill((white)) screen.fill((white)) screen.blit(img(0,0)) pygame.display.flip() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() When I run the code the pygame window opens, but it is blank(black) screen. I also get the following error message: Traceback (most recent call last): File "C:/Users/Draco/OneDrive/Documents/Programming/graphics.py", line 13, in screen.blit(img(0,0)) TypeError: 'pygame.Surface' object is not callable The image I am trying to open is saved as a JPG file. The image is saved under the name Picture. Many thanks in advance for any help.
score: 0
has title: Blank(black) screen in pygame window
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48912876
type: UnansweredQuestion
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/84829261
upvote count: 1
downvote count: 1
type: Question
tagged with: graphics

http://stackoverflow.com/comment/84773910
type: QuestionComment
has text: Yep, when converting val to str, fixed the problem. Thanks guys, couldn't find that question before.
score: 0
comment on: http://stackoverflow.com/q/48884320
type: Comment

http://stackoverflow.com/q/48857537
upvote count: 0
score: -1
has comment: http://stackoverflow.com/comment/84718635
has comment: http://stackoverflow.com/comment/84718674
type: Question
has comment: http://stackoverflow.com/comment/84718694
answer count: 1
has comment: http://stackoverflow.com/comment/84718765
has answer: http://stackoverflow.com/a/48857629
accepted answer: http://stackoverflow.com/a/48857629
has title: How are variables looked up in Python?
tagged with: python-internals
has comment: http://stackoverflow.com/comment/84718721
has body: I have been experimenting with Python and observed some behaviour that I don't understand. What I think happens when performing a look-up: Check local variables in current frame If variable is not found, try first outer frame Repeat 1 and 2 until there are no more outer frames and if the variable is not found, throw NameError This is consistent with the 1st call of print(x), as I have forced x into the first outer frame. However, the 2nd call of print(x) fails with a NameError, which confuses me as x exists in the local variables. Thanks! import inspect def test(): frame_inner = inspect.currentframe() print(locals()) # { 'frame_inner': A } frame_outer = inspect.getouterframes(frame_inner)[1].frame y = 'y' frame_outer.f_locals['x'] = 'x' print(locals()) # { 'frame_inner': A, 'frame_outer': B, 'y': 'y' } print(y) # y print(x) # x del frame_outer.f_locals['x'] frame_inner.f_locals['x'] = 'x' print(locals()) # { 'frame_inner': A, 'frame_outer': B, 'y': 'y', 'x': 'x' } print(y) # y print(x) # NameError: name 'x' is not defined test()
downvote count: 1
tagged with: python
favorite count: 0
tagged with: python-3.x
type: AnsweredQuestion

http://stackoverflow.com/q/48922079
has comment: http://stackoverflow.com/comment/84850827
score: 0
linked to: http://stackoverflow.com/q/48974662
has answer: http://stackoverflow.com/a/48984189
has body: I'm using Django REST Framework and have the folowing view class to view or create product. Now I'm trying to add a new record with POST method, but I get the error below. Can anyone tell me why and how can I fix this? updated . ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ TypeError at /store/view/ Got a `TypeError` when calling `Product.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Product.objects.create()`. You may need to make the field read-only, or override the ProductSerializer.create() method to handle this correctly. view class: class StoreApiView(mixins.CreateModelMixin, generics.ListAPIView): lookup_field = 'pk' serializer_class = ProductSerializer permission_classes = [IsAuthenticatedOrReadOnly] def get_queryset(self): qs = Product.objects.all() query = self.request.GET.get('q') if query is not None: qs = qs.filter( Q(title__icontains=query) | Q(description__icontains=query) ).distinct() return qs def perform_create(self, serializer): serializer.save(author=self.request.user, context={'request': self.request}) def post(self, request, *args, **kwargs): return self.create(request, *args, **kwargs) and the related serializer class: class ProductSerializer(ModelSerializer): product_ratings = ProductRatingSerializer(many=True, read_only=True) product_badges_set = ProductBadgesSerializer(many=True, read_only=True) author = serializers.SerializerMethodField() def get_author(self, obj): return obj.author.first_name + ' ' + obj.author.last_name def get_category(self, obj): return obj.category.title class Meta: model = Product fields = [ 'product_id', 'author', 'title', 'mini_description', 'you_learn', 'you_need', 'full_description', 'price', 'video_level', 'video_length', 'created_date', 'updated_date', 'product_ratings', 'product_badges_set', ] read_only_fields = …
accepted answer: http://stackoverflow.com/a/48984189
has comment: http://stackoverflow.com/comment/84969754
has comment: http://stackoverflow.com/comment/84972796
tagged with: python
has comment: http://stackoverflow.com/comment/84850704
has title: Creating a new record with POST gives error: Got a TypeError when calling Product.objects.create()
tagged with: django
has comment: http://stackoverflow.com/comment/84852354
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84852610
has comment: http://stackoverflow.com/comment/84972459
has comment: http://stackoverflow.com/comment/84856345
type: Question
has comment: http://stackoverflow.com/comment/84852174
answer count: 1
tagged with: django-rest-framework

http://stackoverflow.com/a/48959726
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48959646
type: Answer
upvote count: 1
has body: It seems you want to perform easy comparison without using for loop. Now you want all the ids to be True. you can do this, rather than defining id variables individually, use a list instead, where each value will correspond to one of your id. Like id1 id2 and id3 will be represented by ids[0],ids[1] and ids[1] respectively. Now after making list, if you want to see if all the values are true, just do this. boolean_val = all(ids) if boolean_val is True, it means all the values that is variables in the list are true, else one of them may be false. Hopefully this ans your doubt.

http://stackoverflow.com/a/48816762
upvote count: 2
type: Answer
answers question: http://stackoverflow.com/q/48816622
score: 2
has comment: http://stackoverflow.com/comment/84637423
has body: Take a look at the .str method which is available on any Pandas Series (which is what the columns of the data frame are). It supports regular expression syntax. I often search for what I don't want and then negate it with the ~. Like this: df = df[~df.RA.str.contains('126.1')]
accepted answer of: http://stackoverflow.com/q/48816622
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48908406
type: UnansweredQuestion
has title: Python: get name of actual run-time class from parent class method
tagged with: python
duplicate of: http://stackoverflow.com/q/3314627
tagged with: introspection
has comment: http://stackoverflow.com/comment/84823384
has comment: http://stackoverflow.com/comment/84822830
type: Question
has body: Edited, original question below. As pointed out by @MiH this question is nearly identical to Get subclass name? Is there a way to get the name of the actual/run-time class of an object rather than the name of the class where a method is defined? I call a base class method on derived class objects (such objects do not override the method), o.__class__.__name__ gives me the name of the class of the base class, not the name of the run-time class. Obviously I want to avoid defining a method in each derived class just to get its class name, the objective of the question is to know if there is a way to avoid that.
has comment: http://stackoverflow.com/comment/84822713
linked to: http://stackoverflow.com/q/3314627
tagged with: inheritance
tagged with: class
score: 0
has answer: http://stackoverflow.com/a/48908913
answer count: 1
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84822891

http://stackoverflow.com/comment/84809659
type: QuestionComment
has text: @NestorYanchuk: Why do you think that a delimter for [`split`](https://docs.python.org/3/library/stdtypes.html#str.split) would be needed?
score: 0
comment on: http://stackoverflow.com/q/48902085
type: Comment

http://stackoverflow.com/a/48914679
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48914493
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48914493
has body: The easiest way I can think of is by sending a file over SSH using SFTP. This doesn't require any additional setup on the Pi, except assuming you have SSH open on your Pi (there are plenty of tutorials online on this). A pure python solution to this could use the Paramiko library to connect to the Pi and copy the file. Here is a quick example: import paramiko ssh = paramiko.SSHClient() ssh.connect('192.168.1.30', username='pi', password='raspberry') # Default IP/login, this may be different for you sftp = ssh.open_sftp() # Localpath is a string containing the path of the local file, remotepath is where the file should be copied on the raspberry pi sftp.put(localpath, remotepath) sftp.close() ssh.close() There are many solutions to this problem (eg. setting up a fileserver), but I think this is the simplest. If using python is not vital then I just recommend using the linux scp
has comment: http://stackoverflow.com/comment/84862670
type: Answer

http://stackoverflow.com/comment/84886037
has text: Oops, I didn't properly read the part in yellow as I had assumed it was the same as what I read earlier. So it seems like I can just always use `is` and get nice behavior where `null` is considered equal to itself. Is this a sqlite specific thing? As I may end up using a different database if performance becomes an issue, and I read elsewhere that in SQL `is` can only be followed by `null` or `not null`.
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48928657

http://stackoverflow.com/comment/84916263
score: 0
type: AnswerComment
has text: @PapeK24 thanks for that, I adapted it to my code like so: ` for img_filename in os.listdir(DIRECTORY): a = re.search('^(.*)img(.*)\.png$', img_filename) if a is None: break else: x = a.group(1) y = a.group(2) print 'Camera is ', x print 'Image is ', y` however it only prints the x and y of one image in the directory (which contains 3 for testing)
type: Comment
comment on: http://stackoverflow.com/a/48953392

http://stackoverflow.com/a/49012298
downvote count: 0
score: 5
has comment: http://stackoverflow.com/comment/135710035
has body: TWS API doesn't have this functionality. You can't retreive order history, but you can get open orders using recOpenOrders request and capture executions in realtime by listening to execDetails event - just write them to a file and analyse aftewards.
accepted answer of: http://stackoverflow.com/q/48942917
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48942917
upvote count: 5
type: Answer

http://stackoverflow.com/q/48851337
favorite count: 0
answer count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48851541
has answer: http://stackoverflow.com/a/48851369
has title: Replace datetime characters in a string
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48852516
has comment: http://stackoverflow.com/comment/84706150
has comment: http://stackoverflow.com/comment/84706184
upvote count: 1
possible better answer: http://stackoverflow.com/a/48851409
type: Question
has answer: http://stackoverflow.com/a/48851715
has answer: http://stackoverflow.com/a/48851409
score: 1
accepted answer: http://stackoverflow.com/a/48851541
tagged with: date
tagged with: replace
has body: Consider the following example str of dates: '20180101,20180102,20180103,20180104,20180105,20180106,20180107,20180108,20180109,20180110,20180111,20180112,20180113,20180114,20180115,20180116,20180117,20180118,20180119,20180120,20180121,20180122,20180123,20180124,20180125,20180126,20180127,20180128,20180129,20180130,20180131,20180201,20180202,20180203,20180204,20180205,20180206,20180207,20180208'. Using .replace('2018','2018-'), or re.sub('2018', '2018-', foo_string) from the module re, a date changes to 2018-0101. However, I'd like to insert a hyphen for a range of dates. I have tried the following re.sub('{}'.format(range(2018,2019)), '2018-', foo_string) to no avail. The string is returned without any changes. For reference the years I'd like to range over for the hyphen are 1981 to 2018. Additionally, I'm unsure of a way to insert a hyphen between the month and dates in a clean way. Help along these directions would be greatly appreciated.
downvote count: 0
tagged with: string

http://stackoverflow.com/a/48874204
upvote count: 3
has body: I strongly doubt you'll find any way to do regular expressions in Python that's as natural as it is in Perl. Regex are part of Perl's design at a very low level, while they're not nearly as central to Python. So my first suggestion is to consider if you can avoid using regex all together. For your example problem that would be easy, just use line.lstrip(' ') and compare lengths to figure out how much indentation was removed. Maybe some other problems you'd consider will also have easy implementations using string methods, rather than regex. I really doubt there is any solution for general regex substitutions that is massively better than all of the options you've considered. I'd probably use something like your Attempt 2 myself, or maybe Attempt 1 where the indentation amount was saved by the inner function, rather than the match object itself.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84789073
type: Answer
accepted answer of: http://stackoverflow.com/q/48873936
answers question: http://stackoverflow.com/q/48873936
downvote count: 1
score: 2

http://stackoverflow.com/a/49986628
upvote count: 1
answers question: http://stackoverflow.com/q/48884253
has body: With pip upgrade, it worked for me 1. curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py 2. python get-pip.py
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/48845290
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84696327
tagged with: python
score: 8
has comment: http://stackoverflow.com/comment/84696037
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/90175688
upvote count: 8
type: Question
tagged with: struct
has title: Switching endianness in the middle of a struct.unpack format string
has answer: http://stackoverflow.com/a/62168627
has body: I have a bunch of binary data (the contents of a video game save-file, as it happens) where a part of the data contains both little-endian and big-endian integer values. Naively, without reading much of the docs, I tried to unpack it this way... struct.unpack( '3sB&lt;H&lt;H&lt;H&lt;H4s&lt;I&lt;I32s&gt;IbBbBbBbB12s20sBB4s', string_data ) ...and of course I got this cryptic error message: struct.error: bad char in struct format The problem is that struct.unpack format strings do not expect individual fields to be marked with endianness. The actually correct format-string here would be something like struct.unpack( '&lt;3sBHHHH4sII32sIbBbBbBbB12s20sBB4s', string_data ) except that this will flip the endianness of the third I field (parsing it as little-endian, when I really want to parse it as big-endian). Is there an easy and/or "Pythonic" solution to my problem? I have already thought of three possible solutions, but none of them is particularly elegant. In the absence of better ideas I'll probably go with number 3: I could extract a substring and parse it separately: (my.f1, my.f2, ...) = struct.unpack('&lt;3sBHHHH4sII32sIbBbBbBbB12s20sBB4s', string_data) my.f11 = struct.unpack('&gt;I', string_data[56:60]) I could flip the bits in the field after the fact: (my.f1, my.f2, ...) = struct.unpack('&lt;3sBHHHH4sII32sIbBbBbBbB12s20sBB4s', string_data) my.f11 = swap32(my.f11) I could just change my downstream code to expect this field to be represented differently — it's actually a bitmask, not an arithmetic integer, so it wouldn't be too hard to flip around all the bitmasks I'm using with it; but the big-endian versions of these bitmasks are more mnemonically relevant than the little-endian versions.
tagged with: endianness
linked to: http://stackoverflow.com/q/27506474

http://stackoverflow.com/a/48872150
type: Answer
accepted answer of: http://stackoverflow.com/q/48867997
has comment: http://stackoverflow.com/comment/84769618
score: 1
answers question: http://stackoverflow.com/q/48867997
upvote count: 1
has body: The most straight-forward way to accomplish this is to employ python's struct module to encode your array into a binary format that will be convenient to receive in C++. For example, to send an array of 32-bit integers, you might do something like this: import struct def encode_int_array(int_list): buf = struct.pack("!I" + "I" * len(int_list), len(int_list), *int_list) return buf Explanation: The ! character specifies the byte-ordering to be used in the encoding (here, big-endian / "network" order), the I character is used here for the array length, then again once for each integer to be encoded. The actual array length and each integer is then packed. So, if you called this function with the list [1, 2, 3], the format string given to pack will be "!IIII" and the the remaining arguments will be 3, 1, 2, 3 (the first '3' being the array length to encode). The end result is a bytes string containing the encoded 32-bit (4-byte) integers: |ArrayLen|Integer0|Integer1|Integer2|.... Use the above along with sendall to transmit the resulting buffer: sock.sendall(encode_int_array( [random.randint(1,255), random.randint(1,255), random.randint(1,255)])) On the C++ side, first read 4 bytes (to get the array length), convert the array length to native byte ordering, then read an additional 4 * array-length bytes to get all the integers; then convert each of those to native byte order. You should be careful never to assume that recv will receive all of the data you want. The SOCK_STREAM semantics do not guarantee that. So you need to ensure you receive exactly the number you expected. The C++ side might look something like this: #include &lt;cstdint&gt; // uint32_t et al definitions // Function to receive exactly "len" bytes. // Returns number of bytes received, or -1 on EOF or error int recv_all(int sock, char *buf, unsigned int len) { unsigned int n = 0; int status; while (n &lt; len) { status = recv(sock, buf + n, len - n); if (status == 0) { // Unexpected End of File return -…
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/48856002
answers question: http://stackoverflow.com/q/48855841
has body: While you should probably use zip like mentioned above, if you want to keep on using your way of doing things your problem is here when you for loop in python, it's a foreach, so when you do for linha in x: print linha linha will be the value of x[n] where n is the iteration of the loop anyways, to fix your code you'd do # no need for the for loop, pull everything back index = 0 while index&lt; min(len(x), len(y)): # make sure you check for both lengths in case they are not the same result = (int(x[index]) + int(y[index])) index += 1 print result # you want to print the result inside the loop so you don't lose it on the next iteration the proper way to do it though would be for n,p in zip(x,y): print int(n) + int(p)
type: Answer
upvote count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/84871683
type: AnswerComment
comment on: http://stackoverflow.com/a/48932462
type: Comment
score: 1
has text: Ah right, I knew there was some broadcasted way I could not think of. This is not just simpler but also better memory-wise.

http://stackoverflow.com/a/48917416
has body: I assume this is part of a larger project. You should run python &lt;script name&gt; from the parent directory of Folder A. Then you can do import A.C.c or from A.C import c
has comment: http://stackoverflow.com/comment/84841555
type: Answer
has comment: http://stackoverflow.com/comment/84841445
has comment: http://stackoverflow.com/comment/84841581
answers question: http://stackoverflow.com/q/48917393
has comment: http://stackoverflow.com/comment/84841385
has comment: http://stackoverflow.com/comment/84841542
score: 0

http://stackoverflow.com/a/48955093
score: 1
has comment: http://stackoverflow.com/comment/84917737
has comment: http://stackoverflow.com/comment/84917107
has comment: http://stackoverflow.com/comment/84918085
answers question: http://stackoverflow.com/q/48954408
has body: I get slightly different result from yours, but give it a try. If this is not what you want, I will delete my answer. idx = sorted(set([b.index(ai) for ai in a] + [len(b)])) c = [b[i:j] for i, j in zip(idx[:-1], idx[1:])]
has comment: http://stackoverflow.com/comment/84916988
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/84917515
downvote count: 0

http://stackoverflow.com/comment/84720509
type: Comment
type: QuestionComment
has text: I think this is wrong, you will also retain the last row correct?
comment on: http://stackoverflow.com/q/48858494
score: 2

http://stackoverflow.com/q/48961892
upvote count: 44
type: Question
tagged with: time-series
has body: I am new on pandas and for now i don't get how to arrange my time serie, take a look at it : date &amp; time of connection 19/06/2017 12:39 19/06/2017 12:40 19/06/2017 13:11 20/06/2017 12:02 20/06/2017 12:04 21/06/2017 09:32 21/06/2017 18:23 21/06/2017 18:51 21/06/2017 19:08 21/06/2017 19:50 22/06/2017 13:22 22/06/2017 13:41 22/06/2017 18:01 23/06/2017 16:18 23/06/2017 17:00 23/06/2017 19:25 23/06/2017 20:58 23/06/2017 21:03 23/06/2017 21:05 This is a sample of a dataset of 130 k raws,I tried : df.groupby('date &amp; time of connection')['date &amp; time of connection'].apply(list) Not enough i guess I think i should : Create a dictionnary with index from dd/mm/yyyy to dd/mm/yyyy Convert "date &amp; time of connection" type dateTime to Date Group and count Date of "date &amp; time of connection" Put the numbers i count inside the dictionary ? What do you think about my logic ? Do you know some tutos ? Thank you very much
has answer: http://stackoverflow.com/a/48961940
accepted answer: http://stackoverflow.com/a/48961940
answer count: 3
tagged with: pandas
downvote count: 0
possible better answer: http://stackoverflow.com/a/48961944
favorite count: 0
has answer: http://stackoverflow.com/a/58180807
tagged with: python-3.x
tagged with: python
has title: Python & Pandas - Group by day and count for each day
type: AnsweredQuestion
score: 44
has answer: http://stackoverflow.com/a/48961944

http://stackoverflow.com/comment/84828942
type: AnswerComment
comment on: http://stackoverflow.com/a/48874511
type: Comment
score: 1
has text: The code above works to certain extent. The problem is that fetches does not have a specific order in the execution and your computation graph does not specify an order as well. The easiest solution is to handle the order explicitly like what I did.

http://stackoverflow.com/comment/84797916
type: QuestionComment
has text: Are you looking for format in a Django template or to serialize to JSON for JavaScript?
type: Comment
comment on: http://stackoverflow.com/q/48895772
score: 0

http://stackoverflow.com/comment/84842494
type: QuestionComment
has text: @BryanOakley If you know of any could you please refer me to somewhere that could help me implement queues to fix my code? I haven't been able to find anything yet.
comment on: http://stackoverflow.com/q/48917403
score: 0
type: Comment

http://stackoverflow.com/a/61813557
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48948209
has body: For me the same version of joblib was used to dump and load but I was saving the file under python 3.7.4 and attempting to load with python 3.7.6 which raised the same KeyError.
score: 1
upvote count: 1

http://stackoverflow.com/a/48840345
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48839930
has comment: http://stackoverflow.com/comment/84692633
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84684755
has body: That's not so easy to answer without implementation details, but in general, python is known for it's much less cache friendliness, because you mostly haven't the option to low-level optimize cache behaviour in python. However, this isn't always correct. You propably can optimize the cache friendliness in python directly, or you use parts of c++ code for critical sections. But always consider, that you can just optimize your code better in C++. So if you have really critical code parts, where you want to achieve every percent of speed and effiency, you should use C++. That's the reason, that many programs use both, C++ for raw performance things and python for a nice interface and program structure.
answers question: http://stackoverflow.com/q/48839930
type: AcceptedAnswer

http://stackoverflow.com/q/48932676
answer count: 1
has body: My framework currently only has one conftest.py file in it, which contains a fixture called browser which returns the webdriver object to the test. We've recently tried to implement metafunc.parametrize in _generate_configuration_ in order to test cross browser and cross platform on browserstack, and have encountered a problem. When the browser fixture is called at the beginning of a ui test, it doesn't know what current browser/os/version the test is running in based on the metafunc.parametrize method. A nice example can be found here, but I like the idea of handling the webdriver object with a fixture because of how easy it is to handle the webdriver when it goes out of scope with the yield statement. It also DRYs up the code: https://qxf2.com/blog/selenium-cross-browser-cross-platform-pytest/
score: 0
has comment: http://stackoverflow.com/comment/84879393
tagged with: python
has title: Pytest webdriver fixture can't introspect some options
type: UnansweredQuestion
tagged with: selenium
tagged with: pytest
has answer: http://stackoverflow.com/a/48955861
type: Question

http://stackoverflow.com/q/48858878
has comment: http://stackoverflow.com/comment/84721162
has comment: http://stackoverflow.com/comment/84722702
tagged with: machine-learning
tagged with: floating-point
downvote count: 1
has answer: http://stackoverflow.com/a/48860163
type: Question
has comment: http://stackoverflow.com/comment/84721156
has comment: http://stackoverflow.com/comment/84721188
score: -1
has comment: http://stackoverflow.com/comment/84721213
has body: I have this Decision Tree algorithm: import sys from class_vis import prettyPicture from prep_terrain_data import makeTerrainData import numpy as np import pylab as pl features_train, labels_train, features_test, labels_test = makeTerrainData() from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import accuracy_score clf = DecisionTreeClassifier() clf = clf.fit(features_train, labels_train) prediction = clf.predict(features_test, labels_test) acc = accuracy_score(labels_test, prediction) def submitAccuracies(): return {"acc":round(acc,3)} When I run it, I get the following error: Traceback (most recent call last): File "vm_main.py", line 33, in &lt;module&gt; import main File "/tmp/vmuser_yafetikvhw/main.py", line 2, in &lt;module&gt; import studentMain File "/tmp/vmuser_yafetikvhw/studentMain.py", line 10, in &lt;module&gt; student_output = student_code.submitAccuracies() File "/tmp/vmuser_yafetikvhw/decisionTreeAccuracyQuiz.py", line 34, in submitAccuracies return float({"acc":round(acc,3)}) TypeError: a float is required I'm stuck here. I've tried turning my input into a float but still get same error. For example: acc = acc/1.0 or acc = float(acc) Thanks.
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84721123
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84721176
has title: Why is a float required, and how do I fix it?

http://stackoverflow.com/q/48812532
favorite count: 0
has title: Python Scrape ASPX page with Login
accepted answer: http://stackoverflow.com/a/48965682
tagged with: python
has comment: http://stackoverflow.com/comment/84658595
has comment: http://stackoverflow.com/comment/84630457
upvote count: 3
has comment: http://stackoverflow.com/comment/84646575
tagged with: web-scraping
downvote count: 1
type: Question
score: 2
type: AnsweredQuestion
has body: I am trying to do basic web scraping using Python 2.7 in this website (http://210.212.227.210/tkmce/index.aspx) which includes a login. The page is basically build on ASPX. I tried with the below and I was getting error with the login. This is the home page link (http://210.212.227.210) and this is the redirecting link I want to request after login(http://210.212.227.210/tkmce/Common/Home/Home.aspx) Please help me with this code. It doesn't login! These are the headers and POST data while tracking the login. FORMDATA: __LASTFOCUS: __EVENTTARGET: __EVENTARGUMENT: __VIEWSTATE:/wEPDwUKMTU4MDU0N... (its long) __VIEWSTATEGENERATOR:2611E4BA __EVENTVALIDATION:/wEdAAb+Owa/... txtUserName:(login username) txtPassword:(my login password) hdnstatus:0 btnLogin:Login hdnstatus0:0 REQUEST HEADERS: Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding:gzip, deflate Accept-Language:en-US,en;q=0.9 Cache-Control:max-age=0 Connection:keep-alive Content-Length:460 Content-Type:application/x-www-form-urlencoded Cookie:ASP.NET_SessionId=r3ubp0z1x5fhygqj2eqmnqig Host:210.212.227.210 Origin:http://210.212.227.210 Referer:http://210.212.227.210/tkmce/index.aspx Upgrade-Insecure-Requests:1 User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36 REQUEST HEADER AFTER LOGIN Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8 Accept-Encoding:gzip, deflate Accept-Language:en-US,en;q=0.9 Cache-Control:max-age=0 Connection:keep-alive Cookie:ASP.NET_SessionId=r3ubp0z1x5fhygqj2eqmnqig Host:210.212.227.210 Referer:http://210.212.227.210/tkmce/index.aspx Upgrade-Insecure-Requests:1 User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36 Python 2.7 Code using BeautifulSoup and Requests: import requests from bs4 import BeautifulSoup URL="http://210.212.227.21…
has answer: http://stackoverflow.com/a/48965682
answer count: 1
has comment: http://stackoverflow.com/comment/84656092
tagged with: asp.net

http://stackoverflow.com/q/48835481
has body: Say I have a string: teststring = "1.3 Hello how are you 1.4 I am fine, thanks 1.2 Hi There 1.5 Great!" That I would like as: testlist = ["1.3 Hello how are you", "1.4 I am fine, thanks 1.2 Hi There", "1.5 Great!"] Basically, splitting only on increasing digits where the difference is .1 (i.e. 1.2 to 1.3). Is there a way to split this with regex but only capturing increasing sequential numbers? I wrote code in python to sequentially iterate through using a custom re.compile() for each one and it is okay but extremely unwieldy. Something like this (where parts1_temp is a given list of the x.x. numbers in the string): parts1_temp = ['1.3','1.4','1.2','1.5'] parts_num = range(int(parts1_temp.split('.')[1]), int(parts1_temp.split('.')[1])+30) parts_search = ['.'.join([parts1_temp.split('.')[0], str(parts_num_el)]) for parts_num_el in parts_num] #parts_search should be ['1.3','1.4','1.5',...,'1.32'] for k in range(len(parts_search)-1): rxtemp = re.compile(r"(?:"+str(parts_search[k])+")([\s\S]*?)(?=(?:"+str(parts_search[k+1])+"))", re.MULTILINE) parts_fin = [match.group(0) for match in rxtemp.finditer(teststring)] But man is it ugly. Is there a way to do this more directly in regex? I imagine this is feature that someone would have wanted at some point with regex but I can't find any ideas on how to tackle this (and maybe it is not possible with pure regex).
possible better answer: http://stackoverflow.com/a/48835859
linked to: http://stackoverflow.com/q/48588490
downvote count: 0
score: 10
has comment: http://stackoverflow.com/comment/84686230
tagged with: sequential
has answer: http://stackoverflow.com/a/48835859
has answer: http://stackoverflow.com/a/48836214
answer count: 3
linked to: http://stackoverflow.com/q/39306590
tagged with: regex
tagged with: string
has title: Regex using increasing sequence of numbers Python
favorite count: 0
has comment: http://stackoverflow.com/comment/84676336
linked to: http://stackoverflow.com/q/45104747
tagged with: python
has comment: http://stackoverflow.com/comment/84677763
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84676041
has comment: http://stackoverflow.com/comment/84676821
has comment: http://stackoverflow.com/comment/84675879
has comment: http://stackoverflow.com/comment/84675738
has comment: http://stackoverflow.com/comment/84675928
has answer: http://stackoverflow.com/a/48835782
upvote count: 10
accepted answer: http://stackoverflow.com/a/48835782
type: Question

http://stackoverflow.com/a/48937215
answers question: http://stackoverflow.com/q/48895960
score: 0
type: Answer
has body: I've managed to fix it. So I needed to specify my encoding on my form so it became like that. &lt;form action="" method="POST" enctype="multipart/form-data"&gt; Then had to fix the forms.py class AddProblem(forms.ModelForm): lat = forms.FloatField() lng = forms.FloatField() images = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = problem fields = ('lat','lng','email','importance','description','images')

http://stackoverflow.com/comment/84638098
has text: They use different syntaxes. You are using the wrong syntax.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48816937

http://stackoverflow.com/comment/84715964
comment on: http://stackoverflow.com/a/48856143
type: Comment
score: 0
has text: @question1 You have to provide initial data to the form in view like `form = PostForm(initial={'name': 'name to be provided', 'url': 'any initial url'})`
type: AnswerComment

http://stackoverflow.com/comment/84918583
has text: Thanks! I got it working with no issue, it's just good practice to make sure the answer matches the question ;)
comment on: http://stackoverflow.com/a/48937870
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48805488
upvote count: 1
has answer: http://stackoverflow.com/a/48807149
type: Question
has title: How can I switch between multiple open powerpoint presentations using python?
linked to: http://stackoverflow.com/q/3301561
score: 1
answer count: 2
has answer: http://stackoverflow.com/a/48913746
downvote count: 0
linked to: http://stackoverflow.com/q/2090464
favorite count: 0
has body: Judging by other posts such as Python Window Activation this might not be as simple as I was hoping, but I'm compelled to ask anyway. In the snippet below, using win32com.client and Application.Presentations.Open(ppt1, ReadOnly=0) will open and activate a powerpoint presentation. Using Application.Presentations.Open(ppt2, ReadOnly=0) will open and activate another powerpoint presentation. As you will see, I can easily reference the former presentation and do SOME things with it, but it will NOT become the active window. How can this be accomplished? Here's what I've been working with: # The following requires two existing presentations # ppt1.pptx and ppt2.pptx in a directory named C:\\pptTest\\ import win32com.client Application = win32com.client.Dispatch("PowerPoint.Application") directory = 'C:\\pptTest\\' ppt_a = 'ppt_a.pptx' ppt_b = 'ppt_b.pptx' presentation_a = directory + ppt_a presentation_b = directory + ppt_b pres_a = Application.Presentations.Open(presentation_a, ReadOnly=0) pres_b = Application.Presentations.Open(presentation_b, ReadOnly=0) pres_a_slide1 = pres_a.Slides.Add(len(pres_a.Slides)+1, 12) shape_a_1 = pres_a_slide1.Shapes.AddTextbox(Orientation=0x1,Left=100,Top=50,Width=400,Height=100) shape_a_1.TextFrame.TextRange.Text='PRESENTATION A' ##%% pres_b_slide1 = pres_b.Slides.Add(len(pres_b.Slides)+1, 12) shape1 = pres_b_slide1.Shapes.AddTextbox(Orientation=0x1,Left=100,Top=50,Width=400,Height=100) shape1.TextFrame.TextRange.Text='PRESENTATION B' Result: As you can see by the example, I can still reference the first presentation after opening another, but I can't make it the active window. The reason why I'm so interested in this, is that some methods will not work properly unless the presentation I'm editing through Python is also the active window. I'll get into those details as well if that is interesting to anyone. Thank you for any suggestions!
tagged with: python
has comment: http://stackoverflow.com/comment/84613805
accepted answer: http://stackoverflow.com/a/48913746
type: AnsweredQuestion
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/48807149

http://stackoverflow.com/comment/84631420
has text: Do you have any abnormal formulas in your excel file? It looks like its trying to evaluate a range in a formula (which typically would look like `A1:B2`) but it is failing to find the `:` character.
comment on: http://stackoverflow.com/q/48813490
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48912686
answers question: http://stackoverflow.com/q/48912598
score: 3
downvote count: 0
has body: try something like this: start = a[a.data.notnull()].index[0] new_df = a.loc[start:] the first line finds the index of the first non-null value, the second cuts out all the entries before that from your dataframe.
type: Answer
upvote count: 3

http://stackoverflow.com/q/48870383
upvote count: 18
tagged with: python-asyncio
answer count: 1
tagged with: asynchronous
accepted answer: http://stackoverflow.com/a/48870542
favorite count: 0
tagged with: python-3.x
has body: I have been trying all kinds of things to be able to use an asyncio loop inside another asyncio loop. Most of the time my test just end in errors, such as: RuntimeError: This event loop is already running My example code below is just the base test I started with, so you can see the basics of what I am trying to do. I tried so many things after this test, it was just too confusing, so I figured I should keep it simple when asking for help. If anyone can point me in the right direction, that would be great. Thank you for your time! import asyncio async def fetch(data): message = 'Hey {}!'.format(data) other_data = ['image_a.com', 'image_b.com', 'image_c.com'] images = sub_run(other_data) return {'message' : message, 'images' : images} async def bound(sem, data): async with sem: r = await fetch(data) return r async def build(dataset): tasks = [] sem = asyncio.Semaphore(400) for data in dataset: task = asyncio.ensure_future(bound(sem, data)) tasks.append(task) r = await asyncio.gather(*tasks) return r def run(dataset): loop = asyncio.get_event_loop() future = asyncio.ensure_future(build(dataset)) responses = loop.run_until_complete(future) loop.close() return responses async def sub_fetch(data): image = 'https://{}'.format(data) return image async def sub_bound(sem, data): async with sem: r = await sub_fetch(data) return r async def sub_build(dataset): tasks = [] sem = asyncio.Semaphore(400) for data in dataset: task = asyncio.ensure_future(sub_bound(sem, data)) tasks.append(task) r = await asyncio.gather(*tasks) return r def sub_run(dataset): loop = asyncio.get_event_loop() future = asyncio.ensure_future(sub_build(dataset)) responses = loop.run_until_complete(future) loop.close() return responses if __name__ == '__main__': dataset = ['Joe', 'Bob', 'Zoe', 'Howard'] responses = run(dataset) print (responses)
tagged with: python
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48870542
has title: How to use an asyncio loop inside another asyncio loop
downvote count: 0
score: 18

http://stackoverflow.com/a/48846591
answers question: http://stackoverflow.com/q/48846417
type: Answer
has body: total_months = budget_one_months + budget_two_months You must add parenthesis when you define budget_one_months and budget_two_months. budget_one_months = df1["Date"].value_counts() and budget_two_months = df2["Date"].value_counts()
score: 0

http://stackoverflow.com/a/48875616
downvote count: 0
answers question: http://stackoverflow.com/q/48875473
has comment: http://stackoverflow.com/comment/84758282
type: Answer
score: 2
upvote count: 2
has body: Simpler way to achieve this will be to create a custom function to: Right justify the string based on n using str.format create a string of number in range using str.join Here's a sample function using generator expression: def print_triange(n): for i in range(n): print('{:&gt;{}}'.format(''.join(str(j) for j in range(n-i)), n)) # ^ To right justify the string This can also be achieved with map as: def print_triange(n): for i in range(n): print('{:&gt;{}}'.format(''.join(map(str, range(n-i))), n)) Sample Run: &gt;&gt;&gt; print_triange(10) 0123456789 012345678 01234567 0123456 012345 01234 0123 012 01 0

http://stackoverflow.com/comment/84800420
type: Comment
score: 1
has text: Thanks for the great explanation.
type: AnswerComment
comment on: http://stackoverflow.com/a/48897285

http://stackoverflow.com/comment/84797765
comment on: http://stackoverflow.com/q/48895468
has text: If you use `shell=True` and pass a list, then the first list item is the only thing treated as a shell script (subsequent elements of the list are arguments to that script -- ie. its `$0`, `$1`, `$2`, etc), which is why they're ignored when the script doesn't refer to them.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48804747
tagged with: python
has body: i built a minimal example for a code which I want to iterate over related objects, but it throws an error Python version: 3.6.4 - 64bit on all systems Seems to work on Win10 systems, but error occurs on Win7 systems Any ideas? minimal example of problem: class solution(GraphObject): __primarykey__ = "name" name=Property() includes = RelatedTo("solution") #graph got initialized as graph #code: var=list(solution.select(graph))#gets a list of all solutions for x in var:#iterates over solutions print(x.name) for y in x.includes: #not working print("---connected to: "+y.name) #not working error: in p2neo\packages\neo4j\v1\session.py line 124 session=self.session_pool.pop() IndexError: pop from an empty deque another error occurred: ConnectionRefusedError: [WinError 10061] Does this have to do with py2neo or my own setup of neo4j? Thanks in advance resc
has comment: http://stackoverflow.com/comment/84614946
score: 0
has comment: http://stackoverflow.com/comment/84620613
has title: iterating over relatedobjects
answer count: 0
type: UnansweredQuestion
type: Question
tagged with: neo4j
has comment: http://stackoverflow.com/comment/84615099
tagged with: py2neo
tagged with: python-3.x

http://stackoverflow.com/a/48908412
type: AcceptedAnswer
type: Answer
accepted answer of: http://stackoverflow.com/q/48908075
has comment: http://stackoverflow.com/comment/84822925
answers question: http://stackoverflow.com/q/48908075
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84826527
has body: Use basic numpy vectorized computation e.g. statevar = np.asarray(statevar_list) y = np.log(statevar[1:]) - np.log(statevar[:-1]) x = np.ones(len(y)) Aside: The rlm_results should have the robust estimate of the standard deviation that is used in the estimation as a scale attribute.
upvote count: 1

http://stackoverflow.com/comment/84799256
type: Comment
type: QuestionComment
has text: Because the second one only matches one of the ranges -- I want there to be at least one match for each range specified.
score: 0
comment on: http://stackoverflow.com/q/48896593

http://stackoverflow.com/q/48811189
possible better answer: http://stackoverflow.com/a/48811574
has comment: http://stackoverflow.com/comment/84626871
has comment: http://stackoverflow.com/comment/84626406
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has body: I have two dataframes: df: index some_variable identifier1 identifier2 1 x AB2 AB3 2 x BB2 BB3 3 x CB2 CB3 4 y DB2 DB3 5 y EB2 EB3 dfa: index some_variable identifier1 identifier2 identifier3 1 x AB5 AB3 AB3 2 x BB5 BB2 AB2 3 x CB5 CB2 AB5 4 y DB5 DB3 AB3 5 y EB5 EB3 AB3 if an element of df['identifier1'] is in dfa['identifier2'] replace for that index df['identifier2'] by dfa['identifier3'], if some_variable is equal to 'x'. So the condition is: [(df['identifier1'].isin(dfa['identifier2'])&amp;(df[some_variable]=='x')] and I want: index some_variable identifier1 identifier2 1 x AB2 AB3 2 x BB2 AB2 3 x CB2 AB5 4 y DB2 DB3 5 y EB2 EB3 I can set up the condition, but can't figure out how to get the output.
has answer: http://stackoverflow.com/a/48811715
type: Question
answer count: 2
downvote count: 0
accepted answer: http://stackoverflow.com/a/48811715
has comment: http://stackoverflow.com/comment/84626697
has comment: http://stackoverflow.com/comment/84626583
has comment: http://stackoverflow.com/comment/84626714
tagged with: pandas
has answer: http://stackoverflow.com/a/48811574
has title: Python - Verify if a value is in a column, replace by value in different column
favorite count: 0

http://stackoverflow.com/comment/84763992
has text: @delinco It looks like black magic at first, but it becomes simple once you've understood what the regex is doing and how `re.findall` works. :) The engine finds all strings that match the pattern given, but only returns the substrings specified in the capture groups as a list of tuples.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48879038
type: Comment

http://stackoverflow.com/comment/84665756
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48830848
type: AnswerComment
has text: `InfiniteFullSet` would need to be an *instance* of such a class for the OP's code to work. You also need to define `__rand__` in your class, or else it only works when the universe is the left operand of `&`.

http://stackoverflow.com/q/48832294
favorite count: 0
has body: Here, result is a Queryset. I am going through it and updating the value for it's price attribute to match what I get from the price_map.price value in my second query to Product.objects. This works and updates the prices accordingly. Until it goes into the .order_by method. Then, all of the values of price return to what they originally were. if sort_by in valid_sorts: for item in result: retrieved_item = Product.objects.get(name=item.name).get_pricing_info(self.request.session.get('visitors_country')) if retrieved_item['price_map'] is None: print 'we got a none here! ', item.name else: item.price = retrieved_item['price_map'].price if sort_by == 'highlow': result = result.order_by('-price') elif sort_by == 'lowhigh': result = result.order_by('price') elif sort_by == 'newest': result = result.order_by('-date','-price') elif sort_by == 'relevancy': pass If I add in some print statements for just before and just after the .order_by call, here is the output I get: Just before the order! 79.99 119.99 99.99 69.99 119.99 89.99 69.99 69.99 99.99 44.99 599.99 599.99 69.99 69.99 69.99 69.99 249.99 799.99 119.99 139.99 199.99 249.99 139.99 149.99 139.99 69.99 139.99 199.99 69.99 29.99 0.0 139.99 34.99 54.99 119.99 149.99 69.99 69.99 89.99 119.99 119.99 149.99 149.99 1699.99 69.99 249.99 39.99 39.99 39.99 599.99 999.99 199.99 49.99 119.99 119.99 249.99 99.99 99.99 199.99 69.99 99.99 39.99 169.99 this is the high low sort! 1499.99 599.99 599.99 399.99 349.99 299.99 249.99 209.99 199.99 199.99 179.99 159.99 159.99 129.99 129.99 119.99 119.99 119.99 119.99 119.99 99.99 99.99 89.99 89.99 89.99 69.99 69.99 69.99 69.99 59.99 59.99 49.99 49.99 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 Stack trace for the issue when I try to save the item after changing the price value in the for loop: Traceback (most recent call last): File "/home/user/.virtualenvs/rf/local/lib/python2.7/site-packages/django/core/handlers/…
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48833278
type: UnansweredQuestion
score: 1
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84670116
has title: Django: Queryset not saving changes to value?
tagged with: django-queryset
has comment: http://stackoverflow.com/comment/84672899
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/84797843
has text: @DawitAbate Thanks for your quick help but it still runs into the same error.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48895963

http://stackoverflow.com/q/48924292
answer count: 1
has comment: http://stackoverflow.com/comment/84855927
score: 0
has answer: http://stackoverflow.com/a/48924902
has comment: http://stackoverflow.com/comment/84854992
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84855858
accepted answer: http://stackoverflow.com/a/48924902
type: AnsweredQuestion
tagged with: pycharm
has title: Python/PyCharm: sys.path "lib" not the same capitalization as venv's "Lib"?
type: Question
has comment: http://stackoverflow.com/comment/84855202
has body: I cloned a Python 2 project and used PyCharm to create a Python 2.7.12 virtualenv. I am now getting an "ImportError" when I try to run the code. While debugging I noticed that if I start the virtualenv and run the version of Python it contains, and then check the Path that is checked for modules, the "lib" is not capitalized (see second red arrow below). However, in my venv folder, "Lib" is capitalized. Is this OK? Below is a screenshot of the traceback I'm getting. The first module imported is always not being found. If I start an interactive session using the venv I'm able to import all of the modules. Even more strangely, if I create a new file and try to run it with just an import in it (say, 'test.py'), the traceback shows an error in the original file (site.py). I pulled site.py into a new project and it seems that it is the actual name of the file as site that is causing the error: Doesn't work: Does work:
linked to: http://stackoverflow.com/q/41125919
tagged with: python

http://stackoverflow.com/q/48868855
has body: I have a number of zip files within them, there are hundreds of zip files: Parent_1.zip: [child1.zip, ..., childM.zip] Parent_..zip: [child1.zip, ..., childN.zip] Parent_P.zip: [child1.zip, ..., childL.zip] I unzipped them by loading the binaries into an rdd, then using flatmap to apply a function that extracts the csv file as a string foreach child.zip chunk. zips = sc.binaryFiles(data_files) files_data = zips.flatMap(zip_extract_stores) Once all the zip chunks are extracted, I get 748 chunks in total. print(files_data.count()) # =&gt; 748 chunks Now, I am trying to convert the csv strings, which are within the files_data rdd to a single dataframe. But I am facing few issues. Here's what I tried. Attemp 1: Applying collect() to extract a list in memory as follows: files_data = zips.flatMap(zip_extract_stores).collect() Then converting the chunks into a list of dataframes dataframes = [get_dataframe(data) for data in files_data] Then merging the dataframes into a single dataframe: merge_list_of_dataframes(dataframes) This works fine when run in local mode, but fails in cluster mode due to memory issues. Attemp 2: Giving that, files_data = zips.flatMap(zip_extract_stores) I tried iterating though the rdd files_data using toLocalIterator() for idx, data in enumerate(files_data.toLocalIterator()): if idx % 100 == 0: print("Loaded {} dataframes".format(idx)) dataframes.append(get_dataframe(data)) Then merge the dataframes into a single one with merge_list_of_dataframes(dataframes) This works fine in local mode, but in cluster mode the total count of the final dataframe is different from one run to another. For example, one run gives a total count of 1 million, whereas another run gives a total count of 5 millions, despite that the total expected count is 8 millions. Questions: How to stabelize files_data.toLocalIterator() so it consumes all the data? Otherwise, is there another way to achieve what I am trying to do, which is converting an rdd of CSV strings into a singl…
upvote count: 8
type: Question
downvote count: 0
tagged with: pyspark
tagged with: apache-spark
tagged with: rdd
favorite count: 0
score: 8
type: UnansweredQuestion
tagged with: python
has title: Pyspark rdd.toLocalIterator doesn't iterate through all data partitions
answer count: 0

http://stackoverflow.com/comment/84811780
type: Comment
has text: Please, show us code sample, it'll be easier to help you. In general regexps do not have tools for default values, you need to handle that in the programming language you use.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48903177

http://stackoverflow.com/comment/84647692
has text: What is the type of `line_score`? Is it perhaps a pandas dataframe? What is the type and the value of `game_sequence`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48822141

http://stackoverflow.com/a/49025264
has comment: http://stackoverflow.com/comment/85171863
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48862256
answers question: http://stackoverflow.com/q/48862256
has comment: http://stackoverflow.com/comment/85103221
type: AcceptedAnswer
upvote count: 1
type: Answer
has body: I agree with Eddie that you need to modify the permissions of the migrations folder. The migrations folder is located at: /opt/python/current/app/quotations/migrations/ You probably need to do something like: subprocess.call(['chmod', '-R', '+w', '/opt/python/current/app/quotations/migrations/']) You'll probably need this before and/or after the makemigrations call. Please comment if you have further issues.
has comment: http://stackoverflow.com/comment/85094893

http://stackoverflow.com/comment/84887918
comment on: http://stackoverflow.com/q/48940407
score: 0
type: Comment
has text: Have you tried calling `int` on all of the numerical inputs? Strings are sorted lexicographically so you'd need to convert them to integers for it to work properly.
type: QuestionComment

http://stackoverflow.com/comment/84643851
comment on: http://stackoverflow.com/a/48820096
score: 0
type: Comment
type: AnswerComment
has text: Wow thats super simple and worked like a charm. Thank you.

http://stackoverflow.com/comment/108758100
has text: Is there an equivalent to weigh samples when using `tape.gradient` in Tensorflow 2.0?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48883293
type: AnswerComment

http://stackoverflow.com/q/48921300
tagged with: python-3.x
has body: I am executing python scripts using cmd and have challenges in using other interfaces, so would be executing on CMD only. The python script has 113 lines of code. I want to run and test some selected subsetted line of codes before executing the complete script, without making new python scripts but from the parent script. From example below (has 28 lines): To run the parent script we say in cmd: C:\Users\X&gt; python myMasterDummyScript.py Can we run just between lines 1 - 16 Dummy Example: import numpy as np from six.moves import range from six.moves import cPickle as pickle pickle_file = "C:\\A.pickle" with open(pickle_file, 'rb') as f: data = pickle.load(f, encoding ='latin1') train_dataset = data['train_dataset'] test_dataset = data['test_dataset'] valid_dataset = data['valid_dataset'] train_labels = data['train_labels'] test_labels = data['test_labels'] valid_labels = data['valid_labels'] a = 28 b = 1 def reformat(dataset, labels): dataset = dataset.reshape(-1, a, a, b).astype(np.float32) labels = (np.arange(10)==labels[:,None]).astype(np.float32) return dataset, labels train_dataset, train_labels = reformat(train_dataset, train_labels) test_dataset, test_labels = reformat(test_dataset, test_labels) valid_dataset, valid_labels = reformat(valid_dataset, valid_labels)
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48921375
has answer: http://stackoverflow.com/a/48922107
has answer: http://stackoverflow.com/a/48922231
linked to: http://stackoverflow.com/q/23441657
linked to: http://stackoverflow.com/q/3987041
type: Question
linked to: http://stackoverflow.com/q/4527877
has comment: http://stackoverflow.com/comment/84848993
score: 0
has title: Run selected lines of a Python Script on CMD
has answer: http://stackoverflow.com/a/48921884
tagged with: python
has comment: http://stackoverflow.com/comment/84848901
tagged with: cmd
answer count: 4

http://stackoverflow.com/q/48957165
has comment: http://stackoverflow.com/comment/84921648
score: 2
type: AnsweredQuestion
tagged with: java
linked to: http://stackoverflow.com/q/9655181
type: Question
linked to: http://stackoverflow.com/q/2905556
linked to: http://stackoverflow.com/q/140131
accepted answer: http://stackoverflow.com/a/48957340
downvote count: 0
has title: Java equivalent of struct.unpack('d', s.decode('hex'))[0]
has body: I am reading a file which is stored binaries. In python I can decode the file easily &gt;&gt;&gt; s = '0000000000A0A240' &gt;&gt;&gt; s.decode('hex') '\x00\x00\x00\x00\x00\xa0\xa2@' &gt;&gt;&gt; import struct &gt;&gt;&gt; struct.unpack('d', s.decode('hex'))[0] 2384.0 Now I want to do the same decoding in Java, do we have anything similar?
has comment: http://stackoverflow.com/comment/84921364
tagged with: binaryfiles
answer count: 1
has comment: http://stackoverflow.com/comment/84921615
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/48957340
has comment: http://stackoverflow.com/comment/84921411
tagged with: python

http://stackoverflow.com/comment/84850659
type: Comment
comment on: http://stackoverflow.com/a/48921503
type: AnswerComment
has text: Yes Vivek I just did that but getting error : Found input variables with inconsistent numbers of samples: [1, 5]. Can you plesae help with this error.
score: 0

http://stackoverflow.com/q/48897786
favorite count: 0
has comment: http://stackoverflow.com/comment/125752144
has comment: http://stackoverflow.com/comment/84863579
tagged with: python
downvote count: 0
type: UnansweredQuestion
tagged with: openpyxl
has answer: http://stackoverflow.com/a/48898593
tagged with: excel
score: 1
has title: Issue adding Excel autofilter in openpyxl program
type: Question
has comment: http://stackoverflow.com/comment/125751875
has body: In python I am creating an Excel file using openpyxl, adding a filter and saving it as a new file. The file is created successfully, but throwing the error below when opening. My script: from openpyxl import load_workbook wb = load_workbook('Main.xlsx') ws = wb.active ws.auto_filter.ref= 'A1:A51' ws.auto_filter.add_filter_column(0, ['India', 'Japan'], blank=False) wb.save('results.xlsx') the error screenshot is given below:
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84807656

http://stackoverflow.com/comment/84866811
comment on: http://stackoverflow.com/q/48929377
has text: I see that when you trained your pipeline, you used `data.iloc[0:100000,1:5].astype(str).values` for your `xtr`, so why not do the same with `xtest = data.iloc[100001:101000,1:5].astype(str).values`?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84733649
has text: Share your URL for more details.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48865290

http://stackoverflow.com/comment/84669845
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48830918
has text: This is a good example of a gotcha with implied continuation. The linter I use doesn't warn about it either.
type: AnswerComment

http://stackoverflow.com/q/48914609
favorite count: 0
has title: Is it okay to use only one cursor to execute all operations with database?
has body: I have a program, which must work with database (and it can work in few threads). I wrote a special class, which starts from: class DataBase: def __init__(self): self.connection = sqlite3.connect("some_db.db", check_same_thread=False) self.cursor = self.connection.cursor() Is it okay to use such class? Or I should go another way and use few cursors? My program works fine now and I didn't notice any problems, but I'm not sure can it lead to big problems in future
has answer: http://stackoverflow.com/a/48998628
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84836374
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48998628
tagged with: database
tagged with: sqlite
downvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/22739590

http://stackoverflow.com/q/48874113
has answer: http://stackoverflow.com/a/72266527
upvote count: 15
type: AnsweredQuestion
downvote count: 0
has title: Concat multiple shapefiles via geopandas
has body: I'm trying to combine multiple shapefiles by implementing the follwing: import geopandas as gpd import pandas as pd for i in range(10,56): interesting_files = "/Users/m3105/Downloads/area/tl_2015_{}_arealm.shp".format(i) gdf_list = [] for filename in sorted(interesting_files): gdf_list.append(gpd.read_file((filename))) full_gdf = pd.concat(gdf_list) in which the directory /Users/m3105/Downloads/area has several shapefiles with such as tl_2015_01_arealm.shp, tl_2015_02_arealm.shp all the way up to tl_2015_56_arealm.shp. I'd like to combine all of these shapefiles and avoid repeating their headers. However, whenever I try concating the files using the code above, I get the following error: ValueError: Null layer: u'' Normally, I'd know how to concat csv files together but I'm note sure how to concat shapefiles. I'd greatly appreciate any help
type: Question
has comment: http://stackoverflow.com/comment/84753906
score: 15
accepted answer: http://stackoverflow.com/a/48879758
answer count: 3
tagged with: geopandas
favorite count: 0
has answer: http://stackoverflow.com/a/48879758
possible better answer: http://stackoverflow.com/a/57511945
has answer: http://stackoverflow.com/a/57511945
tagged with: python

http://stackoverflow.com/comment/84759101
has text: That's really neat. I'm browsing google to learn more about the operator +=. Thank you!
type: AnswerComment
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48877405

http://stackoverflow.com/comment/84731747
type: QuestionComment
has text: @smci Sorry but nope (been here, done that...) - first because there are _many_ not-that-cornerish corner cases where relying on `AttributeError` or such just won't work, then because the cost of an exception handler (when it's triggered) is quite high compared to a typecheck. There are indeed cases where EAFP is a better approach than LBYL (specially when dealing with non-atomic operations and concurrency issues), but this is not one. FWIW even the BDFL uses typecheck for this exact kind of problems, cf https://www.artima.com/weblogs/viewpost.jsp?thread=101605
comment on: http://stackoverflow.com/q/48861514
score: 0
type: Comment

http://stackoverflow.com/comment/90570968
comment on: http://stackoverflow.com/a/51233379
type: AnswerComment
has text: To install the current development version use: `pip install https://github.com/pyinstaller/pyinstaller/archive/develop.tar.gz`
type: Comment
score: 1

http://stackoverflow.com/comment/84768101
type: Comment
type: QuestionComment
has text: You shouldn't use pandas to read a csv of urls... even less to store the image back. Pandas is not a database. As you have it now, it's (in my opinion) impossible to do any multithreading as the `get_face` function loads everything into a dataframe.
comment on: http://stackoverflow.com/q/48881833
score: 0

http://stackoverflow.com/a/54569424
downvote count: 0
score: 16
upvote count: 16
has body: This is a known incompatibility between Django and Python 3.7. A fix has already been merged into Django 2.x branches and backported into 1.11 branch. To solve this issue, simply update Django to at least version 1.11.17 (or 2.x) or you can downgrade Python to version 3.6.
has comment: http://stackoverflow.com/comment/108096296
type: Answer
answers question: http://stackoverflow.com/q/48822571

http://stackoverflow.com/comment/84759001
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48877266
has text: `xrange` was deprecated in python 3.x. Replace `xrange` with `range` in your code.

http://stackoverflow.com/q/48827526
tagged with: mysql
has comment: http://stackoverflow.com/comment/84658794
type: Question
answer count: 1
has body: I am creating an app in Kivy. I am creating a login page that allows users to enter a password and user name in order to verify that they have previously used my application. I am storing usernames and passwords in a MySQL database called 'users', and the table is called 'login' that stores their username and password information in two columns. I am using the pymysql library to interact with my Python code and my MySQL database. In my Python code I am using the fetchall() method to get all of the username and password columns and rows from MySQL, and storing that data in a variable. When I print out that data I get a list of a dictionary that displays the following: [{'username': 'sample_username', 'password': 'sample_password'}, {'username': 'sample_username2', 'password': 'sample_password2'}] As you can see in MySQL I created a couple sample usernames and sample passwords that when using the fetchall() method are stored within a dictionary within a list. Next I created in Kivy a textinput box for username, and a textinput box for password. I stored the user input in variables for username and password like below: self.username = self.ids.textinput_username.text self.password = self.ids.textinput_username.text Then after I use the fetchall() method I check to see whether or not the username and password that the user entered match a username or password that is already in my code. if self.username in results: print("That username is stored") if self.password in results: print("That is a valid password") However, that code is not returning anything at all. It is as if Python cannot track the username that was entered by the user, and cannot check to see if it is in the results that I get after using the fetchall method. I even tried storing the results in a list, and then asking Python to check if the username and password string are anywhere in the list. login_list = [] for record in results: login_list.append(record) if self.username in login_list: print("That us…
score: 0
tagged with: kivy
has comment: http://stackoverflow.com/comment/84659648
has comment: http://stackoverflow.com/comment/84659342
tagged with: python
has title: Username Password retrieval
has answer: http://stackoverflow.com/a/48827899
accepted answer: http://stackoverflow.com/a/48827899
type: AnsweredQuestion

http://stackoverflow.com/q/48935072
has comment: http://stackoverflow.com/comment/84879856
score: 1
type: Question
has title: Printing output of pandas profiling object upon click of a button
downvote count: 0
favorite count: 0
tagged with: pandas-profiling
tagged with: python
has body: My question is very specific to pandas profiling package and tkinter package. I want that on click of a button, the profiling report should be displayed in the gui window. My code is: import pandas_profiling def data_profiling(): pandas_profiling.ProfileReport(data) import tkinter as tk root = tk.Tk() tk.Button(root, text='EDA/Data profiling', command=data_profiling).grid(row=9, column=0) Upon execution the button displays nothing. Documentation of pandas_profiling does not also help.
tagged with: tkinter
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84888983
upvote count: 1

http://stackoverflow.com/q/48954187
type: Question
has title: Sort a nested list in python having dictionaries
has comment: http://stackoverflow.com/comment/84915111
has answer: http://stackoverflow.com/a/48954315
has comment: http://stackoverflow.com/comment/84915017
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84914946
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84915010
linked to: http://stackoverflow.com/q/4233476
accepted answer: http://stackoverflow.com/a/48954315
has comment: http://stackoverflow.com/comment/84914990
tagged with: python
has body: I have a list in the below given format: {'DetectedText': 'RAZZAQ', 'Type': 'WORD', 'Id': 11, 'ParentId': 1, 'Confidence': 98.4175796508789, 'Geometry': {'BoundingBox': {'Width': 0.13082271814346313, 'Height': 0.07997149974107742, 'Left': 0.05101994425058365, 'Top': 0.03755004703998566}, 'Polygon': [{'X': 0.050936006009578705, 'Y': 0.03812778368592262}, {'X': 0.1816418319940567, 'Y': 0.038123928010463715}, {'X': 0.18164214491844177, 'Y': 0.11644938588142395}, {'X': 0.05093633010983467, 'Y': 0.11645323783159256}]}} {'DetectedText': '123456', 'Type': 'WORD', 'Id': 10, 'ParentId': 0, 'Confidence': 99.44573974609375, 'Geometry': {'BoundingBox': {'Width': 0.1333530694246292, 'Height': 0.0828823447227478, 'Left': 0.7199195027351379, 'Top': 0.028442291542887688}, 'Polygon': [{'X': 0.7201741337776184, 'Y': 0.028222769498825073}, {'X': 0.8533148169517517, 'Y': 0.03051863983273506}, {'X': 0.8531182408332825, 'Y': 0.11106494814157486}, {'X': 0.7199775576591492, 'Y': 0.10876907408237457}]}} {'DetectedText': 'ABDUL', 'Type': 'WORD', 'Id': 12, 'ParentId': 2, 'Confidence': 98.67652893066406, 'Geometry': {'BoundingBox': {'Width': 0.11256816983222961, 'Height': 0.074801966547966, 'Left': 0.04738632217049599, 'Top': 0.14951731264591217}, 'Polygon': [{'X': 0.04746600240468979, 'Y': 0.1498059332370758}, {'X': 0.1596333384513855, 'Y': 0.15002737939357758}, {'X': 0.15961268544197083, 'Y': 0.2239050269126892}, {'X': 0.04744535684585571, 'Y': 0.22368358075618744}]}} {'DetectedText': 'BED:', 'Type': 'WORD', 'Id': 13, 'ParentId': 2, 'Confidence': 98.10992431640625, 'Geometry': {'BoundingBox': {'Width': 0.08710028976202011, 'Height': 0.07596106827259064, 'Left': 0.6397669911384583, 'Top': 0.14786238968372345}, 'Polygon': [{'X': 0.6399385929107666, 'Y': 0.14720818400382996}, {'X': 0.7270201444625854, 'Y': 0.14760403335094452}, {'X': 0.7269713878631592, 'Y': 0.22334450483322144}, {'X': 0.6398898363113403, 'Y': 0.22294865548610687}]}} {'DetectedText': 'G3/26', 'Type': 'WORD', 'Id': 14, 'ParentId…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84915073
score: 1
upvote count: 1

http://stackoverflow.com/comment/84895591
has text: @harry04 - I add sample data to answer, problem is with filtering? Or something else?
comment on: http://stackoverflow.com/a/48943793
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48840557
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48841714
accepted answer: http://stackoverflow.com/a/48841714
tagged with: orm
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/84687228
has body: i have a models class FriendsWith(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) fusername =models.ForeignKey(User,on_delete=models.CASCADE,related_name='fusername') time = models.DateTimeField(auto_now_add=True) confirm_request = models.SmallIntegerField(default=1) blocked_status = models.IntegerField(default=0) i wanted to search all the friends of currently logged in user.So,i am doing like this obj1=FriendsWith.objects.filter(username=request.user).select_related('fusername') obj2=FriendsWith.objects.filter(fusername=request.user).values('username') obj=obj1 | obj2 friendslist=User.objects.filter(username__in=obj) Where User is a django User model I am trying to combine two queryset(obj1 and obj2) set here But it's not working.I can do the same thing in sql by using alias .But here i am not sure what to do. I am getting this error while performing the above code: TypeError: Merging 'QuerySet' classes must involve the same values in each case Please help in achieving this task
score: 0
answer count: 1
has title: join queryset in django

http://stackoverflow.com/comment/84734878
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48853214
has text: @match I mean you need to spend CPU time for csv parsing
type: Comment

http://stackoverflow.com/a/48888477
answers question: http://stackoverflow.com/q/48887515
has body: First of all, N and evalf are essentially the same thing; N(x, n) amounts to sympify(x).evalf(n). In your case, since x is a Python float, it's easier to use N because it sympifies the input. To get three digits after decimal dot, use N(x, 3 + log(x, 10) + 1). The adjustment log(x, 10) + 1 is 0 when x is between 0.1 and 1; in this case the number of significant digits is the same as the number of digits after the decimal dot. If x is larger, we get more significant digits. Example: for x in [0.0065, 1.0065, 10.0065, 100.0065]: print(N(x, 3 + log(x, 10) + 1)) prints 0.006 1.007 10.007 100.007 The transition from 6 to 7 is curious, but not entirely surprising. These numbers are not exactly represented in binary system, so the truncation to nearest double-precision float may be a factor here. I've made a few additional observation on this effect on my blog.
score: 0
type: Answer

http://stackoverflow.com/a/48907764
accepted answer of: http://stackoverflow.com/q/48906570
has comment: http://stackoverflow.com/comment/85353812
has comment: http://stackoverflow.com/comment/84823847
has comment: http://stackoverflow.com/comment/85320428
answers question: http://stackoverflow.com/q/48906570
has comment: http://stackoverflow.com/comment/84827690
type: Answer
has comment: http://stackoverflow.com/comment/85232322
has body: You can do it using gather_nd, with indices[i, j, k, l]= [i, j+ tensor_offset [i,j,k,l], k, l] (so indices would be of dimension 5). You can build it like that: import numpy as np import tensorflow as tf b, h, w ,c = 2, 11, 13, 7 final_shape = [b, h, w, c] offset = np.random.randint(low=0, high=h, size=final_shape) image = np.random.randint(low=0, high=1000, size=final_shape) input_tensor = tf.constant(image) m1 = tf.transpose(tf.reshape(tf.tile(tf.range(b), multiples=[h * w * c]), [h, w, c, b]), perm=[3, 0, 1, 2]) m2 = tf.transpose(tf.reshape(tf.tile(tf.range(h), multiples=[b * w * c]), [b, w, c, h]), perm=[0, 3, 1, 2]) + offset not_too_big = tf.less(m2, h) m2_safe = tf.mod(m2, h) # Makes sure we don't go too far in the original array m3 = tf.transpose(tf.reshape(tf.tile(tf.range(w), multiples=[b * h * c]), [b, h, c, w]), perm=[0, 1, 3, 2]) m4 = tf.reshape(tf.tile(tf.range(c), multiples=[b * h * w]), [b, h, w, c]) # No transposition needed here indices = tf.stack([m1, m2_safe, m3, m4], axis=-1) tmp = tf.gather_nd(input_tensor, indices) output = tf.multiply(tmp, tf.cast(not_too_big, tmp.dtype)) # Sets all the values corresponding to j+offset&gt;h to 0 EDIT: this works for me with the transposition.
has comment: http://stackoverflow.com/comment/85310647
score: 0
has comment: http://stackoverflow.com/comment/84825038
has comment: http://stackoverflow.com/comment/84828166
has comment: http://stackoverflow.com/comment/85320154
has comment: http://stackoverflow.com/comment/85301514
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85232572
has comment: http://stackoverflow.com/comment/85227098

http://stackoverflow.com/q/48836285
tagged with: python
type: AnsweredQuestion
type: Question
linked to: http://stackoverflow.com/q/32141623
upvote count: 6
downvote count: 0
has answer: http://stackoverflow.com/a/48839244
accepted answer: http://stackoverflow.com/a/48839244
tagged with: python-asyncio
answer count: 1
has title: python asyncio.Event.wait() not responding to event.set()
favorite count: 0
has body: The plan is to have several IO routines running "concurrently" (specifically on a Raspberry Pi, manipulating IO pins and running an SPI interface at the same time). I try to use asyncio to make this happen. However, my simple try-out refuses to run. This is a reduced version of the code, leaving out the IO pin details: """\ Reduced problem representation: this won't run because GPIO details have been left out """ import RPi.GPIO as gpio import asyncio GPIO_PB = 12 # Define pushbutton channel async def payload(): """ Provides some payload sequence using asyncio.sleep() """ #Payload action await asyncio.sleep(1) #Payload action await asyncio.sleep(1) class IOEvent(asyncio.locks.Event): """\ Create an Event for asyncio, fired by a callback from GPIO The callback must take a single parameter: a gpio channel number """ def __init__(self, ioChannel, loop): super().__init__(loop = loop) self.io = ioChannel def get_callback(self): "The callback is a closure that knows self when called" def callback( ch ): print("callback for channel {}".format(ch)) if ch == self.io and not self.is_set(): print(repr(self)) self.set() print(repr(self)) return callback async def Worker(loop, event): print("Entering Worker: {}".format(repr(loop))) while loop.is_running(): print("Worker waiting for {}".format(repr(event))) await event.wait() print("Worker has event") event.clear() await payload() print("payload ended") loop = asyncio.get_event_loop() # Create an event for the button pb_event = IOEvent( GPIO_PB, loop) # register the pushbutton's callback # Pushing the button calls this callback function gpio.add_event_callback( GPIO_PB, pb_event.get_callback() ) try: asyncio.ensure_future(Worker(loop, pb_event)) loop.run_forever() except KeyboardInterrupt: pass finally: print("Closing Loop") loop.stop() loop.close() The output I get is like this: Entering Worker: &lt;_UnixSelectorEventLoop running=True closed=False debug=False&gt; Worker waiting for &lt;__main__.IOEvent object at 0x76a2a950 [unse…
has comment: http://stackoverflow.com/comment/84678339
has comment: http://stackoverflow.com/comment/84677723
score: 6

optimization
tags question: http://stackoverflow.com/q/48950440
tags question: http://stackoverflow.com/q/48936045
tags question: http://stackoverflow.com/q/48845663
tags question: http://stackoverflow.com/q/48881428
tags question: http://stackoverflow.com/q/48886359
tags question: http://stackoverflow.com/q/48829551
tags question: http://stackoverflow.com/q/48887912
tags question: http://stackoverflow.com/q/48804698
tags question: http://stackoverflow.com/q/48835999
tags question: http://stackoverflow.com/q/48859767
tags question: http://stackoverflow.com/q/48950626
tags question: http://stackoverflow.com/q/48817141
tags question: http://stackoverflow.com/q/48847799
tags question: http://stackoverflow.com/q/48898879
tags question: http://stackoverflow.com/q/48892146
tags question: http://stackoverflow.com/q/48874745
tags question: http://stackoverflow.com/q/48890902
tags question: http://stackoverflow.com/q/48852561
tags question: http://stackoverflow.com/q/48895750
tag name: optimization
tags question: http://stackoverflow.com/q/48857635
tags question: http://stackoverflow.com/q/48896522
tags question: http://stackoverflow.com/q/48889787
tags question: http://stackoverflow.com/q/48861574
tags question: http://stackoverflow.com/q/48918896
tags question: http://stackoverflow.com/q/48914146
tags question: http://stackoverflow.com/q/48842326
type: Tag

http://stackoverflow.com/a/48863259
accepted answer of: http://stackoverflow.com/q/48863068
answers question: http://stackoverflow.com/q/48863068
type: Answer
score: 2
upvote count: 2
has body: You can use the numpy library for this: import numpy as np arr = np.random.randint(0, 2000, (1000, 8)) # array([[1026, 46, 1620, ..., 534, 1098, 1406], # [1081, 1235, 484, ..., 1124, 841, 4], # [1189, 1505, 1943, ..., 55, 1547, 1936], # ..., # [1242, 877, 1129, ..., 230, 1226, 1399], # [1134, 939, 969, ..., 1600, 288, 1479], # [ 492, 5, 545, ..., 1093, 1805, 1404]]) Then just slice the array for one selection, e.g. arr[0] will give you the first row as an array.
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48856701
downvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84717583
has comment: http://stackoverflow.com/comment/84722989
has body: I'm trying to import a function from a higher level directory. I believe converting my script to a python "package" is the best way to do this: package/ __init__.py # contains add function subpackage/ __init__.py my_script.py # where I want to import add function Let's say the function I want to import is simple: def add(x, y): return x + y I should be able to do something like this in my_script.py, per the python docs: from package import add print(add(5, 6)) But I'm getting a ModuleNotFoundError: No module named 'package' error. What am I doing wrong?
type: UnansweredQuestion
has title: python: importing functions from higher-level subpackage
linked to: http://stackoverflow.com/q/45448182
tagged with: python-import
has comment: http://stackoverflow.com/comment/84723001
tagged with: pythonpath
favorite count: 0
has comment: http://stackoverflow.com/comment/84717591
type: Question
tagged with: package
tagged with: python
has answer: http://stackoverflow.com/a/51807654
score: 0
upvote count: 1

http://stackoverflow.com/comment/84706184
score: 0
type: Comment
type: QuestionComment
has text: @heemayl Yes, all dates are in this format.
comment on: http://stackoverflow.com/q/48851337

http://stackoverflow.com/a/48892065
accepted answer of: http://stackoverflow.com/q/48890152
has body: First, some errors in your code: for i in range(l): Sh=(n[i]) i=i+1 #### Won't work. range() will override ##### Where do "a","b","o","e" come from ##### Shouldn't it be "G","B","Z","M" ("GA","BU","ZO","MEU")? if Sh =="a": Erc_finale.append(0) elif Sh =="b": Erc_finale.append(1) elif Sh =="o": Erc_finale.append(2) elif Sh =="e": Erc_finale.append(3) print(Erc_finale) F=str(Erc_finale) ### Not how you join an array into a string Here's a corrected way: def ShadockstoBase10(n): n = n.upper(); # Convert string to upper case l = len(n) Erc_finale = "" # Using a string instead of an array to avoid conversion later i = 0 while i &lt; l: # while loop so we can modify i in the loop Sh = n[i:i+2] # Get next 2 chars i += 2 # Skip 2nd char if Sh == "GA": Erc_finale += "0" elif Sh == "BU": Erc_finale += "1" elif Sh == "ZO": Erc_finale += "2" elif Sh =="ME" and "U" == n[i]: Erc_finale += "3" i += 1; # MEU is 3 chars else: break; # bad char return int(Erc_finale, 4) # Let Python do the heavy work Like everything in Python, there are other ways to do this. I just tried to keep my code similar to yours.
type: Answer
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48890152
score: 0

http://stackoverflow.com/q/48864696
accepted answer: http://stackoverflow.com/a/48866817
has answer: http://stackoverflow.com/a/48866923
has title: Algorithm to find # elements less than target in a sorted Matrix in O(n)?
tagged with: python
has comment: http://stackoverflow.com/comment/84736127
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48866923
tagged with: algorithm
type: Question
tagged with: sorting
has body: Design an algorithm that outputs the number of entries in A that are smaller than or equal to x. Your algorithm should run in O(n) time. For example in the array below if my target was '5' then I would return 2 b/c 1 and 3 are smaller. [1, 3, 5] [2, 6, 9] [3, 6, 10] I gave it a shot with the code below which is close to working and I think it's O(n) ... the problem I see is if I don't have the # in my array I am not sure if I am returning the right value? def findLessX(m,n,x): i = 0 j = n-1 while (i &lt; n and j &gt;= 0): if i == n or j == n: print("n not found") return (i+1)*(j+1)-1 if (m[i][j] == x): print(" n Found at ", i , " ", j) return (i+1)*(j+1)-1 elif (m[i][j] &gt; x): print(" Moving left one column") j = j - 1 elif (m[i][j] &lt; x): print(" Moving down one row") i = i + 1 print(" n Element not found so return max") return (i)*(j+1) # Driver code x = 5 n = 3 m = [ [1, 3, 5], [2, 6, 9], [3, 6, 9]] print("Count=", findLessX(m, n, x)) Inspect the Count and simple matrix above to see if soln works ~
has answer: http://stackoverflow.com/a/61171800
score: 0
answer count: 3
has answer: http://stackoverflow.com/a/48866817
has comment: http://stackoverflow.com/comment/84736041
tagged with: matrix

http://stackoverflow.com/a/48920198
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48907773
answers question: http://stackoverflow.com/q/48907773
has body: client_credentials won't issue refresh token. You need to use authorization_code flow to get the refresh token. https://docs.authlib.org/en/latest/client/oauth2.html#oauth2session-for-authorization-code
has comment: http://stackoverflow.com/comment/99758404
score: 1
has comment: http://stackoverflow.com/comment/89410418
upvote count: 1

http://stackoverflow.com/comment/85227114
type: AnswerComment
has text: By the way, for sets with a small enough number of possible elements, it looks like mapping the digits to characters can cut RAM usage by half. Of course, there's no improvement in execution time, as the number of possibilities stay the same.
type: Comment
comment on: http://stackoverflow.com/a/48862172
score: 0

http://stackoverflow.com/q/48889368
has answer: http://stackoverflow.com/a/48889774
score: 1
has comment: http://stackoverflow.com/comment/84784093
linked to: http://stackoverflow.com/q/10373247
favorite count: 0
type: Question
has body: I would like to write a simple dict to CSV for later reuse in a Pythonic manner. The approaches I have found online do not seem elegant and Pythonic to me, so I am looking for a better solution. For example: How do I write a Python dictionary to a csv file? How to export dictionary as CSV using Python? dic = {1:"a", 2:"b", 3:"c"} Output: 1,a 2,b 3,c
upvote count: 1
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84783950
has answer: http://stackoverflow.com/a/48889507
linked to: http://stackoverflow.com/q/45690380
has answer: http://stackoverflow.com/a/48889481
has comment: http://stackoverflow.com/comment/84783875
answer count: 4
has answer: http://stackoverflow.com/a/48889567
accepted answer: http://stackoverflow.com/a/48889507
has title: Writing a simple dict to a csv file in a simple and Pythonic manner?
has comment: http://stackoverflow.com/comment/84783990
tagged with: http://stackoverflow.com/tag/csv
possible better answer: http://stackoverflow.com/a/48889774
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/a/48937497
has comment: http://stackoverflow.com/comment/84882108
upvote count: 2
has comment: http://stackoverflow.com/comment/84883283
answers question: http://stackoverflow.com/q/48937399
has comment: http://stackoverflow.com/comment/84882250
type: Answer
score: 2
downvote count: 0
has body: Using list comprehensions (however generators as kindall has proposed is the most pythonic way): a=[{'prop':'ABC','cat':'ABC Dir'}, {'prop':'DEF','cat':'DEF Dir'}] bb = lambda prop: ' '.join([val['cat'] for val in a if val['prop'] == prop]) bb('ABC') Would give you a string with all the matches: 'ABC Dir' And here is another one that will join the matches with a blank space and if you want to pass an array too: f = lambda prop, d: ' '.join([val['cat'] for val in d if val['prop'] == prop]) f('ABC',a) Returns: 'ABC Dir'
has comment: http://stackoverflow.com/comment/84882024

http://stackoverflow.com/comment/84790009
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48892164
has text: When you give 20 and 10, and then no, as per your program, what is printed to the text file is-(20*2)/(10*5) = 0.8, which is correct.

http://stackoverflow.com/comment/84783905
type: QuestionComment
has text: In the general case what are you try to accomplish? i.e Multiply all values in the list, only multiple the last two elements in a list
comment on: http://stackoverflow.com/q/48889370
score: 0
type: Comment

http://stackoverflow.com/q/48962208
has comment: http://stackoverflow.com/comment/84930536
tagged with: python
has comment: http://stackoverflow.com/comment/84930825
type: AnsweredQuestion
tagged with: oop
has title: Is this pythonic? Class self variable
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84930815
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48962463
possible better answer: http://stackoverflow.com/a/48962392
has answer: http://stackoverflow.com/a/48962392
has body: Long story short, I need to write a data analysing tool using mainly OOP principles. I'm not quite a beginner at python but still not the best. I wrote a function which returned true or false value based on what the user inputted (below): def secondary_selection(): """This prints the options the user has to manipulate the data""" print("---------------------------") print("Column Statistics [C]") print("Graph Plotting [G]") d = input(str("Please select how you want the data to be processed:")).lower() # Returns as a true/false boolean as it's easier if d == "c": return True elif d == "g": return False else: print("Please enter a valid input") This function works the way I want it to, but I then tried to import it into different file for use with a class (below): class Newcastle: def __init__(self, data, key_typed): self.data = data[0] self.key_typed = key_typed def newcastle_selection(self): # If function returns True if self: column_manipulation() # If function returns False if not self: graph_plotting() The newcastle_selection(self) function takes the secondary_selection() function as a argument, but the only way I got it to work was the if self statement. As writing something like if true lead to both the column_manipulation and the graph_plotting functions being printed. I am wondering if there's any better way to write this as I am not quite a beginner at python but still relatively new to it. Disclaimer: This is for a first year course, and I asked this as a last result.
has comment: http://stackoverflow.com/comment/84930408
accepted answer: http://stackoverflow.com/a/48962463
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84930465
upvote count: 2
has comment: http://stackoverflow.com/comment/84930635

http://stackoverflow.com/q/48870710
downvote count: 0
linked to: http://stackoverflow.com/q/14542189
linked to: http://stackoverflow.com/q/19030727
linked to: http://stackoverflow.com/q/43111800
type: Question
has answer: http://stackoverflow.com/a/48876692
accepted answer: http://stackoverflow.com/a/48876692
answer count: 1
upvote count: 6
has title: Kivy ScrollView of Label won't scroll
linked to: http://stackoverflow.com/q/39489980
linked to: http://stackoverflow.com/q/32445341
linked to: http://stackoverflow.com/q/44610516
tagged with: kivy
favorite count: 0
tagged with: kivy-language
has body: I have a Label inside a ScrollView, hoping that that when the (multiline) text takes up too many lines, the user can scroll up & down, and when the lines are too long, the user can scroll left & right. And I can't get it to scroll. Here's the relevant part of my Builder string: ScrollView: id: scrollLayout size_hint_y: 0.9 Label: id: sortFilesDisplay size_hint_y: 0.9 text: 'Drag\\n in\\n files\\n to\\n be\\n sorted\\n yea\\n go\\n now\\n testing\\n please\\n work\\n now\\help' I've read the Kivy docs on ScrollView, that say I need to specify one of the size_hints to enable scrolling. I've readseveral SO posts about getting ScrollView to work: Kivy ScrollView - Not Scrolling kivy scrollview is not working kivy Scrollview can't Scroll ScrollView widget not scolling in kivy Kivy -- scroll view not working. And and how add chat users on side pane Kivy - My ScrollView doesn't scroll but they all involve embedding some kind of Layout (e.g. GridLayout), abut I'm not embedding a layout, just one Label. I've tried setting minimum_height to various things I saw in those posts, but still no effect. Those two size_hint_y's are in there just to try to do as directed; I don't need them. Also tried setting them to None. Any ideas? Also, that static string for text isn't what I ultimately want. I want the Label to remain scrollable when the string changes (when users drop in a new list of files), but I thought perhaps the 'dynamic' action was a problem, so for now I 'retreated' to trying a static string.
score: 6
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/48815881
answers question: http://stackoverflow.com/q/48811721
type: Answer
accepted answer of: http://stackoverflow.com/q/48811721
has comment: http://stackoverflow.com/comment/84640304
score: 0
has body: Can you try the below approach? I've created an utility with EnableCors class like below from bottle import request, response class EnableCors(object): def apply(self, fn, context): def _enable_cors(*args, **kwargs): # set CORS headers response.headers['Access-Control-Allow-Origin'] = '*' response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE' response.headers['Access-Control-Allow-Headers'] = 'Authorization, Origin, Accept, Content-Type, X-Requested-With' if request.method != 'OPTIONS': # actual request; reply with the actual response return fn(*args, **kwargs) return _enable_cors and to use it (lets take your class), from path.to.your_utility import EnableCors class MininetRest(Bottle): def __init__(self, net): super(MininetRest, self).__init__() self.route('/pingall', method='GET', callback=self.pingall) self.install(EnableCors()) Of course you need to look into the Access-Control-* options and chose what is needed for your requirements. Hope this helps
type: AcceptedAnswer

http://stackoverflow.com/comment/123304425
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48912748
has text: For me, it was the same but I needed to remove the `build` folder.
score: 0

http://stackoverflow.com/a/48871836
answers question: http://stackoverflow.com/q/48870792
has body: You may use this regex: ^(?:\d+/){1,3}(?:\d+|XXX)$ RegEx Demo Details: ^: Start (?:\d+/){1,3}: Match a number followed by / 1 to 3 times (?:\d+|XXX): follo $: End
type: Answer
score: 1
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/84854374
comment on: http://stackoverflow.com/a/48908748
score: 0
type: AnswerComment
has text: @Eric I updated the sample code in relation to your question.
type: Comment

http://stackoverflow.com/comment/84759948
type: QuestionComment
comment on: http://stackoverflow.com/q/48877868
type: Comment
has text: `name 'sendCmdWaitResponse' is not defined`
score: 0

http://stackoverflow.com/comment/84683344
type: QuestionComment
has text: What do you mean by *remove*? Do you want to extract it, or delete it?
type: Comment
comment on: http://stackoverflow.com/q/48835298
score: 0

http://stackoverflow.com/q/48854574
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84713254
downvote count: 3
has answer: http://stackoverflow.com/a/48855005
type: Question
has title: Upper limit of points pyplot
has comment: http://stackoverflow.com/comment/84712776
tagged with: matplotlib
has body: Just being a curious George here. But I'm handling 279 million data points (x,y) and am wondering if pyplot can scatter such a number? Thanks.
upvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48855005
favorite count: 0
score: -3
tagged with: python

http://stackoverflow.com/q/48813621
tagged with: temperature
has body: I'm trying to make code for my temperature sensor. Been stuck on a NameError when I try to execute the code. My question is, does anyone have a clue what I am doing wrong? Code: import datetime from sense_hat import SenseHat def hotwater(): sense = SenseHat() sense.clear() celcius = round(sense.get_temperature(), 1) result = 'temp. C' + str(celcius) print(result) result_list = [(datetime.datetime.now(), celcius)] while __name__ == '__main__': Hotwater() Error: Traceback (most recent call last): file "/home/pi/Web_test.py", line 9 in &lt;module&gt; results= 'temp. C' + str(celcius) NameError: name 'celcius' is not defined
answer count: 2
has answer: http://stackoverflow.com/a/48813761
tagged with: sensors
has comment: http://stackoverflow.com/comment/84630808
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 2
score: 1
has answer: http://stackoverflow.com/a/48813697
downvote count: 1
has title: Programming a temperature sensor in python
type: Question

http://stackoverflow.com/q/48861378
score: 2
tagged with: selenium-chromedriver
has body: I have tried selenium webdriver in Python and it works fine. But when I try to open default chrome profile it doesn't open the websites. The code is chromeOptions = webdriver.ChromeOptions() chromeOptions.add_argument("user-data- dir=/Users/prajwal/Library/Application Support/Google/Chrome") capability = DesiredCapabilities.CHROME capability["pageLoadStrategy"] = "normal" driver = webdriver.Chrome(desired_capabilities=capability, chrome_options=chromeOptions) driver.get("https://www.google.com") The window opens in this case. But it doesnt open the website. However, it works fine if I remove chromeOptions.add_argument("user-data- dir=/Users/prajwal/Library/Application Support/Google/Chrome") Where am I going wrong ?
answer count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84814168
type: Question
has title: Selenium webdriver not opening websites in default chrome profile
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84727780
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84847183
tagged with: python
has comment: http://stackoverflow.com/comment/84729665
tagged with: selenium-webdriver

http://stackoverflow.com/comment/84759458
comment on: http://stackoverflow.com/a/48875869
has text: @Adela good point. I've updated to code to keep drugas in the same order as tokens.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84629904
comment on: http://stackoverflow.com/q/48813083
score: 0
type: Comment
type: QuestionComment
has text: Yes, the Python package contains it. Look for the version you need.

http://stackoverflow.com/a/48963987
has comment: http://stackoverflow.com/comment/84934932
type: AcceptedAnswer
downvote count: 0
has body: Hough transform is definitely the way to go. In fact grid detection is one of the most popular example when introducing this tehcnique (see here and here). I suggest the following steps: downsample blur apply Canny (you should have a good guess what the min/max possible length of a grid line from the used perspective) dilate the edge image (canny finds both border of a separator in the grid as different edges, dilation will make these merge again) erode (now we have too thick borders, hough would find too many lines) apply HoughLines merge the similar lines At the last step you have many possible ways to go and it strongly depends on what you want to do with the results afterwards. For example you could create a new edge image with the found images and apply erosion and hough again, you could use something Fourier-based, or you could just simply filter the lines by some arbitrary threshold values (just to mention a few). I implemented the last one (since conceptually that is the easiest one to do), here is what i did (although i am not at all sure whether this is the best approach or not): defined an arbitrary threshold for the rho and theta values checked how many times an edge is in these thresholds of another one starting from the most similar one I started dropping out lines that are similar to it (this way we will keep the line that is in some sense the 'middle' one among a similar group) the remaining lines are the final candidates See code, have fun: import cv2 import numpy as np filter = False file_path = '' img = cv2.imread(file_path) gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray,90,150,apertureSize = 3) kernel = np.ones((3,3),np.uint8) edges = cv2.dilate(edges,kernel,iterations = 1) kernel = np.ones((5,5),np.uint8) edges = cv2.erode(edges,kernel,iterations = 1) cv2.imwrite('canny.jpg',edges) lines = cv2.HoughLines(edges,1,np.pi/180,150) if not lines.any(): print('No lines were found') exit() if filter: rho_threshold = 15 theta_threshol…
accepted answer of: http://stackoverflow.com/q/48954246
type: Answer
score: 25
upvote count: 25
answers question: http://stackoverflow.com/q/48954246
has comment: http://stackoverflow.com/comment/84935485

http://stackoverflow.com/comment/84758485
type: QuestionComment
comment on: http://stackoverflow.com/q/48838029
type: Comment
score: 0
has text: @NathanVērzemnieks a class would suffice but, I prefer a function by a slight degree. I feel like Functions are more user-friendly **in general** and this is meant to be a module used by others. I am aiming to make this module able to be used by beginners in Python. Some users may only know HTML/CSS(maybe Javascript) and this could be their first time using Python let alone any dynamic programming language at all.

http://stackoverflow.com/comment/84700770
type: QuestionComment
has text: Please give a try to pdfminer library in Python and let me know
score: 0
comment on: http://stackoverflow.com/q/48848408
type: Comment

http://stackoverflow.com/q/48811883
has comment: http://stackoverflow.com/comment/84628345
has comment: http://stackoverflow.com/comment/84627608
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84627712
tagged with: python
answer count: 4
score: 2
upvote count: 3
has answer: http://stackoverflow.com/a/48812340
downvote count: 1
has answer: http://stackoverflow.com/a/48813196
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84627634
has comment: http://stackoverflow.com/comment/84627718
has comment: http://stackoverflow.com/comment/84627428
has answer: http://stackoverflow.com/a/48812166
has answer: http://stackoverflow.com/a/48811927
has title: Adding a value to all indices except for one in a 2D array
has comment: http://stackoverflow.com/comment/84627509
has body: How can I add a value to all indices in numpy array a except one, without having to make a mask? Please note that I do not want to reverse the operation of the a[0,0] index, because in my use case, the operation on the right of the += cannot be performed at 0,0 index. import numpy as np a = np.random.rand(10, 10) # The 0,0 index is incremented with 1. a[0,0] += 1. # I would like to increment all others with three += 3.
favorite count: 0

http://stackoverflow.com/a/53759796
downvote count: 2
upvote count: 27
has body: Try this: import warnings warnings.filterwarnings('ignore') warnings.simplefilter('ignore')
type: Answer
score: 25
answers question: http://stackoverflow.com/q/48828824

http://stackoverflow.com/a/48853009
has comment: http://stackoverflow.com/comment/84891034
upvote count: 14
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48852930
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48852930
has body: Use factorize: a = pd.factorize(z)[0].tolist() print (a) [0, 0, 0, 0, 1, 1, 1, 2, 2, 2] Or numpy.unique: a = np.unique(z, return_inverse=True)[1].tolist() print (a) [0, 0, 0, 0, 1, 1, 1, 2, 2, 2]
type: Answer
score: 14

http://stackoverflow.com/a/48938293
has comment: http://stackoverflow.com/comment/84883789
has body: If you're using BeautifulSoup4 for link in soup.find_all('link', href=True): print "Found the URL:", link['href'] If your using version 3 for link in soup.findAll('link', href=True): print "Found the URL:", link['href']
type: Answer
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48938108
downvote count: 0

http://stackoverflow.com/q/48889462
score: 0
has comment: http://stackoverflow.com/comment/84785333
tagged with: iterator
has comment: http://stackoverflow.com/comment/84810248
has answer: http://stackoverflow.com/a/48889671
has title: Custom generator object for lazily flattening large datasource
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84785811
linked to: http://stackoverflow.com/q/42983569
tagged with: lazy-loading
has comment: http://stackoverflow.com/comment/84784929
accepted answer: http://stackoverflow.com/a/48889671
has body: I'm looking for the object oriented equivalent of this function: def lazy_gen_func(path): for line in open(path): for token in line.split(): yield token Related answers suggest the following approach: class eager_gen_obj(object): def __init__(self, path): f = open(path) self.text = [token for line in f for token in line.split()] self.index = 0 def __iter__(self): return self def __next__(self): try: result = self.text[self.index] except IndexError: raise StopIteration self.index += 1 return result With the downside that the full source file has to be loaded in memory when __init__ is called. How do I create a custom generator object to lazily flatten nested source data?
tagged with: python
answer count: 1
tagged with: generator

php
tags question: http://stackoverflow.com/q/48885476
tags question: http://stackoverflow.com/q/48811905
tags question: http://stackoverflow.com/q/48932861
tags question: http://stackoverflow.com/q/48914431
tag name: php
tags question: http://stackoverflow.com/q/48960598
tags question: http://stackoverflow.com/q/48826796
tags question: http://stackoverflow.com/q/48917381
tags question: http://stackoverflow.com/q/48881546
tags question: http://stackoverflow.com/q/48831733
tags question: http://stackoverflow.com/q/48825064
tags question: http://stackoverflow.com/q/48897369
tags question: http://stackoverflow.com/q/48870959
tags question: http://stackoverflow.com/q/48910713
type: Tag

http://stackoverflow.com/comment/84877747
score: 0
type: Comment
type: QuestionComment
has text: @PRMoureu thanks for the comment. I realised that my manage.py file was located in the wrong place. It wasn't in the root folder, but a subfolder of the root. Now I've moved it it works using both methods.
comment on: http://stackoverflow.com/q/48934578

http://stackoverflow.com/q/48841215
type: AnsweredQuestion
tagged with: tkinter
downvote count: 2
has body: Suppose I have Python code like this # &lt;Pure Python statement A&gt; root = tk.Tk() mainframe = tk.Frame(root) # &lt;Pure Python statement B&gt; # &lt;other tkinter code&gt; root.mainloop() Which statements are then ending up on tkinter's mainloop? Is it just the 3 tkinter statements? EDIT There must be more things going on, because some code between the tkinter code is affected: When I run the following code (taken from another question) import tkinter as tk import tkinter.filedialog filename = "" def op(): global filename filename =tk.filedialog.askopenfilename() root = tk.Tk() mainframe = tk.Frame(root) mainframe.grid(column=0, row=0) tk.Button(mainframe, text="Open file", command=op).grid(column=0, row=1) root.mainloop() print(filename) after closing the program the selected filename is displayed. But when running import tkinter as tk import tkinter.filedialog filename = "this_is_a_test" def op(): global filename filename =tk.filedialog.askopenfilename() root = tk.Tk() mainframe = tk.Frame(root) mainframe.grid(column=0, row=0) tk.Button(mainframe, text="Open file", command=op).grid(column=0, row=1) print(filename) root.mainloop() after closing the program, nothing is displayed. So somehow the pure Python statements before mainloop seem to get absorbed.
type: Question
has comment: http://stackoverflow.com/comment/84686716
score: -2
has comment: http://stackoverflow.com/comment/84691252
answer count: 2
has answer: http://stackoverflow.com/a/48842706
upvote count: 0
has comment: http://stackoverflow.com/comment/84687589
possible better answer: http://stackoverflow.com/a/48841340
has comment: http://stackoverflow.com/comment/84688069
has comment: http://stackoverflow.com/comment/84691407
has answer: http://stackoverflow.com/a/48841340
favorite count: 0
has comment: http://stackoverflow.com/comment/84687523
has comment: http://stackoverflow.com/comment/84693124
has title: What kind of code does tkinter's mainloop collect?
has comment: http://stackoverflow.com/comment/84687610
has comment: http://stackoverflow.com/comment/84687561
tagged with: python
accepted answer: http://stackoverflow.com/a/48842706

http://stackoverflow.com/comment/84889826
type: AnswerComment
has text: Interesting! Maybe I used the wrong terminology with "select" - I meant "locate"; I don't want to click the element, just ensure that it's there. I did manage to get the wait condition to return without exception by scrolling to the element first - but this defeats the purpose of the wait condition! I want to ensure that the element is present before I continue; if I first scroll into view, then I get a transient error. I guess it was incorrect to say that I can reliably get the element with find_element_by_xpath(). Is there a way to wait until an element is present at all on the page?
type: Comment
comment on: http://stackoverflow.com/a/48941209
score: 1

http://stackoverflow.com/comment/84654678
comment on: http://stackoverflow.com/a/48813868
score: 0
type: AnswerComment
has text: @Sebastian I am able to get all 10 headlines with the above updated code , have a look at it once.
type: Comment

http://stackoverflow.com/a/48948639
answers question: http://stackoverflow.com/q/48947557
score: 0
type: Answer
has body: For the first part about finding the keywords that match in your Series() I'd suggest the following : mySeries.apply(lambda l: " ".join(e for e in keywords if all(keyword in l for keyword in e.split()))) Sorry for the phrasing which should (must) be improved. But the idea is just check if all elements in your input strings (split by default " ") are found in the Series row. If they do, then return them. You may use that with simple_keywords or double_keywords (instead of the keywords in my line, I guess it works. With simple_keywords : 0 case 1 case 2 adapter 3 case With double_keywords : 0 battery case 1 charging case 2 3

http://stackoverflow.com/a/48901073
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48899022
accepted answer of: http://stackoverflow.com/q/48899022
has body: Yeah,I`ve alread solved the problem from Sublime2 and SublimeREPL Just try to edit the path again as below: you'll need to modify {"PATH":"{PATH};c:\Python32"} to {"PATH":"{PATH};c:\Python32;c:\path\to\R"}
score: 0

http://stackoverflow.com/comment/88706324
comment on: http://stackoverflow.com/a/48971851
type: AnswerComment
score: 0
has text: Thanks @ixaxaar :) Updated the answer.
type: Comment

http://stackoverflow.com/comment/84935230
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48886872
has text: That is because i have not converted it to JSON because already know how to do that and i used pprint to display the output. Anyway i have updated the snippet.

http://stackoverflow.com/q/48960159
has title: how to convert a text file into csv using python
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84926759
tagged with: python
type: UnansweredQuestion
downvote count: 2
has answer: http://stackoverflow.com/a/48960336
tagged with: text
has body: I have a requirement where in I need to convert my text files into csv and am using python for doing it. My text file looks like this , 1. Which of the following structure are made of several layer's of cells :- (A) Ciliated epithelium (B) Stratified epithelium (C) Cuboidal epithelium (D) Columnar epithelium 2. Which simple epithelium tissue cells are square in vertical sections and Polygonal in horizontal section (A) Columnar epithelium (B) Squamous epithelium (C) Cuboidal epithelium (D) Ciliated epithelium I want a CSV as follows: 1, "Which of the following structure are made of several layer's of cells :-", "Ciliated epithelium", "Stratified epithelium", "Cuboidal epithelium", "Columnar epithelium" 2, "Which simple epithelium tissue cells are square in vertical sections and Polygonal in horizontal section", "Columnar epithelium", "Squamous epithelium", "Cuboidal epithelium", "Ciliated epithelium" I have tried multiple ways but unable to get it. Any thoughts to solve this problem? Thanks in advance.
has answer: http://stackoverflow.com/a/48960393
type: Question
answer count: 2
upvote count: 0
score: -2

http://stackoverflow.com/a/48843468
has comment: http://stackoverflow.com/comment/84691378
score: 2
accepted answer of: http://stackoverflow.com/q/48843322
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48843322
upvote count: 2
type: Answer
has body: I believe this is a misunderstanding of what usecols does. The documentation doesn't suggest that the columns come back in the same order presented in the argument. usecols : array-like or callable, default None Return a subset of the columns. If array-like, all elements must either be positional (i.e. integer indices into the document columns) or strings that correspond to column names provided either by the user in names or inferred from the document header row(s). For example, a valid array-like usecols parameter would be [0, 1, 2] or [‘foo’, ‘bar’, ‘baz’]. If callable, the callable function will be evaluated against the column names, returning names where the callable function evaluates to True. An example of a valid callable argument would be lambda x: x.upper() in ['AAA', 'BBB', 'DDD']. Using this parameter results in much faster parsing time and lower memory usage. In fact the columns came back in the same order that they are present in the file. cols = ['Author', 'Title', 'Abstract Note', 'Url'] with open('test.csv') as fh: print('\n'.join(filter(lambda x: x in cols, fh.readline().split(',')))) Author Title Url Abstract Note And when we read the file: df = pd.read_csv( "test.csv", usecols=('Author', 'Title', 'Abstract Note', 'Url')) df.columns Index(['Author', 'Title', 'Url', 'Abstract Note'], dtype='object') We see the same column order. Instead, slice the resulting dataframe with columns in the order you want. cols = ['Author', 'Title', 'Abstract Note', 'Url'] df = pd.read_csv('test.csv', usecols=cols)[cols] df.columns Index(['Author', 'Title', 'Abstract Note', 'Url'], dtype='object')

http://stackoverflow.com/comment/84617265
type: QuestionComment
has text: What does your question has to do with RobotFramework and Python?
score: 0
comment on: http://stackoverflow.com/q/48806894
type: Comment

http://stackoverflow.com/q/48925541
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48927536
has body: I have collected outputs from several clustering algorithms on the same data set, based on which I would like to generate an adjacency matrix indicating in how many different runs any two samples were clustered together. I.e. for each I = 10 clusterings, I have a one-hot representation N x C_i indicating whether or not the sample n belongs to cluster c (for the i'th run), with the possibility of different (amount of) clusters for each run. The goal is then to build an adjacency matrix N x N on which I can threshold and select only consistent clusters for further analysis. It is quite easy to build an algorithm that does this: n_samples = runs[0].shape[0] i = [] j = [] for iter_no, ca in enumerate(runs): print("Processing adjacency", iter_no) for col in range(ca.shape[1]): comb = itertools.combinations(np.where(ca[:, col])[0], 2) for c in comb: i.append(c[0]) j.append(c[1]) i = np.array(i) j = np.array(j) adj_mat = scipy.sparse.coo_matrix((np.ones(len(i)), (i, j)), shape=[n_samples, n_samples]) This scales very poorly with cluster size, and I typically have N = 15000 with cluster sizes occasionally reaching 12k. Hence, I'm looking for the networkx library to possibly speed this up? Is there any obvious way to do this? UPDATE: Solution found (see answer).
favorite count: 0
has title: Creating adjacency matrix from multiple clustering results of various sizes
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: networkx
score: 1
type: Question

http://stackoverflow.com/comment/84753215
score: 0
type: AnswerComment
has text: Do you know it performs speed wise?
comment on: http://stackoverflow.com/a/48874305
type: Comment

http://stackoverflow.com/comment/86745135
has text: Is there any way that I could test this theory to validate this is the issue? Or configure things in a way that it doesn't need that much space?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/49786501
type: Comment

file
type: Tag
tags question: http://stackoverflow.com/q/48826322
tags question: http://stackoverflow.com/q/48937769
tags question: http://stackoverflow.com/q/48923170
tags question: http://stackoverflow.com/q/48949022
tags question: http://stackoverflow.com/q/48879633
tags question: http://stackoverflow.com/q/48926384
tags question: http://stackoverflow.com/q/48862093
tag name: file
tags question: http://stackoverflow.com/q/48898109
tags question: http://stackoverflow.com/q/48845287
tags question: http://stackoverflow.com/q/48882582
tags question: http://stackoverflow.com/q/48881167
tags question: http://stackoverflow.com/q/48822567
tags question: http://stackoverflow.com/q/48914493
tags question: http://stackoverflow.com/q/48859333
tags question: http://stackoverflow.com/q/48891613
tags question: http://stackoverflow.com/q/48862654
tags question: http://stackoverflow.com/q/48918277
tags question: http://stackoverflow.com/q/48908224
tags question: http://stackoverflow.com/q/48939318
tags question: http://stackoverflow.com/q/48866806
tags question: http://stackoverflow.com/q/48807141
tags question: http://stackoverflow.com/q/48810557
tags question: http://stackoverflow.com/q/48924029
tags question: http://stackoverflow.com/q/48914221
tags question: http://stackoverflow.com/q/48899091

http://stackoverflow.com/comment/84882990
type: Comment
comment on: http://stackoverflow.com/q/48935328
has text: @PedroUrbina threads share memory, processes don't.
type: QuestionComment
score: 0

annotate
tag name: annotate
type: Tag
tags question: http://stackoverflow.com/q/48922328

http://stackoverflow.com/comment/84729725
has text: I actually don't know much about `encoding` just few names and definition, it would be a great help if you could share a link so that the answer can be optimized or it becomes better.
comment on: http://stackoverflow.com/a/48863075
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84924200
type: QuestionComment
comment on: http://stackoverflow.com/q/48958509
type: Comment
has text: So what do you suggest should I import all images again without adding "astype('float32')/255" ? and then try numpy reshape?
score: 0

http://stackoverflow.com/a/48914770
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48914556
has comment: http://stackoverflow.com/comment/84838022
has comment: http://stackoverflow.com/comment/84837488
accepted answer of: http://stackoverflow.com/q/48914556
has comment: http://stackoverflow.com/comment/84837361
type: Answer
has comment: http://stackoverflow.com/comment/84838504
has comment: http://stackoverflow.com/comment/84836524
has comment: http://stackoverflow.com/comment/84836366
score: 1
upvote count: 1
has body: You have to add the methods in your decorator @app.route("/", methods=['GET', 'POST']) def index(): {...} Also you'll have to add your arguments name and id to submit(): @app.route('/submit') def submit(name, id): {...} Finally, import make_response from flask import Flask, request, redirect, url_for, make_response
has comment: http://stackoverflow.com/comment/84836770
has comment: http://stackoverflow.com/comment/84837716
has comment: http://stackoverflow.com/comment/84837522

http://stackoverflow.com/q/48880466
has answer: http://stackoverflow.com/a/48881515
tagged with: django-rest-framework
favorite count: 0
has comment: http://stackoverflow.com/comment/84765363
type: UnansweredQuestion
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84765144
has comment: http://stackoverflow.com/comment/84765249
has title: Django REST API : Create object from python file
has comment: http://stackoverflow.com/comment/84765183
has comment: http://stackoverflow.com/comment/84765321
type: Question
linked to: http://stackoverflow.com/q/22567306
has comment: http://stackoverflow.com/comment/84765074
has answer: http://stackoverflow.com/a/48880810
has body: I'm looking for developping Django REST API from my web application and I would like to try creating object through the API. Mainly if my process is well-implemented. I'm using a python file in order to make that. This is my file : import requests url = 'http://localhost:8000/Api/identification/create/' data = { "Etat": "Vivant", "Civilite": "Monsieur", "Nom": "creation", "Prenom": "via-api", "Sexe": "Masculin", "Statut": "Célibataire", "DateNaissance": "1991-11-23", "VilleNaissance": "STRASBOURG", "PaysNaissance": "FR", "Nationalite1": "FRANCAISE", "Nationalite2": "", "Profession": "Journaliste", "Adresse": "12, rue des fleurs", "Ville": "STRASBOURG", "Zip": 67000, "Pays": "FR", "Mail": "", "Telephone": "", "Image": "http://localhost:8000/media/pictures/HH_Hh_19212-00001-979812-2_ShUDIk8.jpg", "CarteIdentite": "http://localhost:8000/media/Carte_Identite/carte_ID_lzpOI41_WOnC9WH.gif" } response = requests.post(url, data=data) print (response.text) I'm confusing if I have to use post or put, but anyway, I don't overcome to create my object. If I make the process directly through the API, it works, but not with a pythonic file. Any idea ? EDIT : For example, it works with these files : #API_list.py import requests url = 'http://localhost:8000/Api/Identification/' response = requests.get(url) print (response.text) and #API_details.py import requests url = 'http://localhost:8000/Api/Identification/26/' response = requests.get(url) print (response.text) and #API_edit.py import requests url = 'http://localhost:8000/api/Identity/26/edit/' data = { "Ville": "STRASBOURG", "Zip": 67000, "Pays": "FR", "Adresse": "12, rue de la mésange", "Telephone": "0388603938", "Mail": "ceciestuntest@datasystems.fr", } response = requests.put(url, data=data) print (response.text)
has comment: http://stackoverflow.com/comment/84765480
score: 0
answer count: 2
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/84629796
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48812506
has text: @GrantWilliams Given that this seems invalid even as a string literal (weird `''`) and the format is vaguely specified at best I am skeptical how far this can be answered, but suit yourself. :)

http://stackoverflow.com/q/48888272
has answer: http://stackoverflow.com/a/48888299
downvote count: 0
accepted answer: http://stackoverflow.com/a/48888299
tagged with: pandas
answer count: 1
favorite count: 0
has title: Adding elements to a dataframe while iterating over it
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: dataframe
has body: I have this dataframe called SBPV_DBPV which looks something like this: STUDY_ID SBPV DBPV 0 1 12.927571 19.054308 1 3 12.635492 10.603099 2 5 25.825786 7.663226 3 6 16.931817 12.369440 And I was trying to implement KMeans algorithm manually. So I have 3 centroids and I am trying to calculate distance of each row to these centroids and append the minimum centroid to the row in the dataframe: for i, row in SBPV_DBPV.iterrows(): #distance of each row to the 3 centroids dist1 = ((row['SBPV'] - (k1.values.reshape(-1,1)[0]))**2 + (row['DBPV'] - k1.values.reshape(-1,1)[1])**2)**0.5 dist2 = (row['SBPV'] - (k2.values.reshape(-1,1)[0])**2 + (row['DBPV'] - k2.values.reshape(-1,1)[1])**2)**0.5 dist3 = (row['SBPV'] - (k3.values.reshape(-1,1)[0])**2 + (row['DBPV'] - k3.values.reshape(-1,1)[1])**2)**0.5 row['cluster'] = min(dist1,dist2,dist3) However after I run the loop, the dataframe does not get modified. I had read that I have to use .applyin order to modify the dataframe but I dont know how I can implement that while iterating over the rows. Thanks
type: Question

http://stackoverflow.com/comment/84837224
type: Comment
type: QuestionComment
score: 0
has text: It looks like you've made a mess with installing different interpreters and packages linked to incorrect interpreters. `def append(self, value: object) -> object` should never work in Python 2.
comment on: http://stackoverflow.com/q/48915333

cx-freeze
tags question: http://stackoverflow.com/q/48858406
tag name: cx-freeze
tags question: http://stackoverflow.com/q/48848853
type: Tag
tags question: http://stackoverflow.com/q/48837417
tags question: http://stackoverflow.com/q/48904257
tags question: http://stackoverflow.com/q/48957469
tags question: http://stackoverflow.com/q/48846219

http://stackoverflow.com/a/64338795
upvote count: 1
has body: Destruction is the best way to delete something. self.listNode.destroy() and then add Your data again to your ListBox.
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48833763

http://stackoverflow.com/comment/84670733
comment on: http://stackoverflow.com/q/48833111
has text: How did you try to see the content? `req = requests.get(url='url', verify=False)` and then `print(req.json())` what do you see?
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/91261716
type: Comment
comment on: http://stackoverflow.com/a/48860100
has text: Awesome! I have read so many posts about different ways to import JavascriptExecutor, none of which worked as the OP said. And all along it wasn't even necessary... Probably why it can't be loaded anymore, it is built in.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84647133
has text: It is giving me the output but when the 3days ATR is calculated, it is also taking the 1st day TR(i.e, of date 16'Jan) into the calculation which I don't want. Basically, I want the 3 days ATR as of 15'Feb, 14'Feb, and 13'Feb.
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48821392
score: 0

http://stackoverflow.com/comment/84802909
score: 0
type: AnswerComment
has text: Got it .But is there any ways i can get the cookie without sending any request to the url ?
type: Comment
comment on: http://stackoverflow.com/a/48858169

http://stackoverflow.com/comment/84803290
has text: For paralellism you use the https://docs.python.org/3.6/library/multiprocessing.html
type: AnswerComment
comment on: http://stackoverflow.com/a/48898885
score: 0
type: Comment

http://stackoverflow.com/comment/84641244
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48818376
has text: ydata takes values of the selected field. But if after the call of the function I insert: print(radio.ydata) Nothing appears. Assume I want to make an other plot with the selected field but in a different figure...

http://stackoverflow.com/comment/84880443
has text: I think this answer fits OP's needs better!
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48936775

http://stackoverflow.com/comment/86332932
comment on: http://stackoverflow.com/q/48959376
score: 0
has text: Solved! I'm not sure how to mark it as such.
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48896884
score: 0
type: Answer
has body: I believe the simplest thing would be the following: b=[list(a),list(a),list(a)] The problem in your example is that by doing [a,a,a] you do not create new object.
answers question: http://stackoverflow.com/q/48896856
has comment: http://stackoverflow.com/comment/84800222
has comment: http://stackoverflow.com/comment/84800241

http://stackoverflow.com/q/48926141
accepted answer: http://stackoverflow.com/a/48926182
upvote count: 2
tagged with: python
has body: let's say I have a datetimeindex. (In this example I set the date range manually, but actually, there are lot's of date index, and I can't specify the beginning day manually.) date_idx = pd.DatetimeIndex(pd.date_range("2000-1-1",periods=3)) DatetimeIndex(['2000-01-01', '2000-01-02', '2000-01-03'], dtype='datetime64[ns]', freq='D') I want to extend the index to 3 days before like below. DatetimeIndex(['1999-12-29', '1999-12-30', '1999-12-31', '2000-01-01', '2000-01-02', '2000-01-03'], dtype='datetime64[ns]', freq=None) I toke a detour and got what I want. Is there any easier way to do that? later = date_idx.tolist() begin_day = later[0] former = pd.date_range(begin_day, periods=3 ).shift(-3).tolist() result = pd.DatetimeIndex(former + later)
score: 2
type: AnsweredQuestion
type: Question
has answer: http://stackoverflow.com/a/48926182
downvote count: 0
answer count: 1
tagged with: pandas
has title: Extend data time index backward directly in pandas
favorite count: 0

http://stackoverflow.com/q/48903681
has title: How to send file according to file ID on Telegram
tagged with: telegram-bot
score: 2
type: AnsweredQuestion
has body: How can I send (not forward) file existing on Telegram to user according to file ID? I know all files uploaded on Telegram have unique ID. How can I extract that ID and what's the function or method to send that file by extracted ID? (I use Python Telepot library) import telepot from telepot.loop import MessageLoop def on_chat_message(msg): content_type, chat_type, chat_id = telepot.glance(msg,'chat') if content_type == 'text': user_msg_text = msg['text'] if user_msg_text == '/start': bot.sendDocument(chat_id=chat_id, ) TOKEN = "479761462:AAE8yqX2RGCbynHJgShIdJzCZWYF9SSBUkU" bot = telepot.Bot(TOKEN) MessageLoop(bot, {'chat': on_chat_message, 'callback_query': on_callback_query}).run_as_thread() print('Listening ...') what I should enter on second argument of sendDocument() method?
favorite count: 0
tagged with: python-telegram-bot
tagged with: telegram
type: Question
upvote count: 2
accepted answer: http://stackoverflow.com/a/49187868
tagged with: python
answer count: 1
tagged with: telepot
downvote count: 0
has answer: http://stackoverflow.com/a/49187868

http://stackoverflow.com/q/48806156
tagged with: service
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48807076
score: 0
has answer: http://stackoverflow.com/a/48807076
has answer: http://stackoverflow.com/a/48806387
type: Question
answer count: 2
has body: i have read a lot of posts on this site on how to implement a python script as a service. After fiddling around i am at the point that the service is started via systemctl (and running) but the script is doing nothing... My config file in /etc/systemd/system/: [Unit] Description=tg Bot [Service] Type=simple User=user WorkingDirectory=/home/user/tg_onduty/ ExecStart=/usr/bin/python3 /home/user/tg_onduty/on_duty.py Restart=always [Install] WantedBy=multi-user.target Output: user@server:~$ sudo service tg_onduty status ● tg_onduty.service - Telegram OnDuty Bot Loaded: loaded (/etc/systemd/system/tg_onduty.service; enabled; vendor preset Active: active (running) since Thu 2018-02-15 11:28:20 CET; 2min 17s ago Main PID: 1538 (python3) Tasks: 9 Memory: 17.7M CPU: 351ms CGroup: /system.slice/tg_onduty.service └─1538 /usr/bin/python3 /home/user/tg_onduty/on_duty.py I have read https://unix.stackexchange.com/questions/339638/difference-between-systemd-and-terminal-starting-program/339645#339645 and understand that running the script via systemctl is different than running via CLI (via CLI /usr/bin/python3 /home/user/tg_onduty/on_duty.py is working). My question is now: How can i trace or see whats going wrong or why the script seems to do nothing? Via Journalctl i only see: Feb 15 11:56:17 server systemd[1]: Started tg Bot. Any help is appreciated. Thanks, David
accepted answer: http://stackoverflow.com/a/48806387
has title: Ubuntu Server 16.04 systemctl service with python script is running but not working
tagged with: python
tagged with: systemctl

http://stackoverflow.com/comment/84641038
type: Comment
type: QuestionComment
has text: I want to use the selected field, after making the click. I don't know where that option, variable is stored, so I can use after the click. The code plots the selected field. yes, but assume that I want to perform further calculations with that field.
score: 0
comment on: http://stackoverflow.com/q/48818376

http://stackoverflow.com/comment/84698238
has text: Thank you so much guys i did not know that map passes one value i got it Thanks again :)
comment on: http://stackoverflow.com/q/48847018
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48812925
accepted answer of: http://stackoverflow.com/q/48812500
upvote count: 7
answers question: http://stackoverflow.com/q/48812500
score: 7
has comment: http://stackoverflow.com/comment/84630084
has comment: http://stackoverflow.com/comment/84649729
has body: In pandas, this would work: df_test['column_name'] = df_test['column_name'].astype('int64') as geopandas is built on top of pandas, this should work as well. As for how it compares to to_numeric, they are both vectorized, and comparable as far as speed goes: Testing the speed of astype method vs the to_numeric method for a modest sized Series, I got an average of 0.00007522797584533691 seconds for astype and 0.0003248021602630615 seconds for to_numeric.
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84775570
type: Comment
has text: Please give me some time. I'm working something else. I will put type of a[1] by end of day
comment on: http://stackoverflow.com/a/48871110
type: AnswerComment
score: 0

http://stackoverflow.com/q/48831851
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
type: Question
has body: I'm trying to use GridSearchCV from SKlearn to tune hyperparameters for my estimator. In the first step, the estimator is used to for is SequentialFeatureSelection, which is a custom library that performs wrapper based feature selection. This means iteratively adding new features and identifying the ones where the estimator performs best with. Hence, the SequentialFeatureSelection method requires my estimator. This library is programmed so that it is perfectly fine to use with SKlearn, so I integrate it in the first step of the GridSearchCV pipeline to transform the features to the ones selected. In the second step, I would like to use exactly the same classifier with exactly the same parameters to be fitted and predict the outcome. However with the parameter grid, I can only either set the parameters to the classifier that I pass to SequentialFeatureSelector OR the ones in 'clf' and I cannot assure that they are always the same. Finally, with the selected features and selected parameters I want to predict on a previously held out test-set. On the bottom of the page of the SFS library, they show how to use SFS with GridSearchCV, but there the KNN algorithm used to select features and the one used to predict are also using different parameters. And when I check for myself after traininf SFS and GridSearchCV, the parameters are never the same, even when I use the clf.clone() as proposed. Here is my code: import sklearn.pipeline import sklearn.tree import sklearn.model_selection import mlxtend.feature_selection def sfs(x, y): x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.2, random_state=0) clf = sklearn.tree.DecisionTreeClassifier() param_grid = { "sfs__estimator__max_depth": [5] } sfs = mlxtend.feature_selection.SequentialFeatureSelector(clone_estimator=True, # Clone like in Tutorial estimator=clf, k_features=10, forward=True, floating=False, scoring='accuracy', cv=3, n_jobs=1) pipe = sklearn.pipeline.Pipeline([('sfs', s…
score: 5
answer count: 1
tagged with: grid-search
tagged with: scikit-learn
favorite count: 0
has title: How to pass two estimator objects to sklearn's GridSearchCV so that they have the same parameters in each step?
has answer: http://stackoverflow.com/a/48842359
accepted answer: http://stackoverflow.com/a/48842359
upvote count: 5
downvote count: 0

http://stackoverflow.com/q/48828086
downvote count: 0
has title: MQTT Client keeps on diconnecting
type: Question
has answer: http://stackoverflow.com/a/48828287
accepted answer: http://stackoverflow.com/a/48828287
has comment: http://stackoverflow.com/comment/84659912
has body: I have multiple python files. One files has all the code related to MQTT and has some functions while the other imports the MQTT file and calls functions as an event occurs. The MQTT file only publishes messages some QoS 0 and some QoS 1 and is connected to mosquitto broker installed in the local machine. MQTT Code is as follows import paho.mqtt.client as mqtt from threading import current_thread import datetime import cv2 as cv2 import time # Define Variables MQTT_HOST = "127.0.0.1" MQTT_PORT = 1883 MQTT_KEEPALIVE_INTERVAL = 60 def send_something(): try: mqttc.publish("topic", "hello", 1, False) # QoS =1 Retain = False except Exception as e: print(str(e)) def send_something_else(): mqttc.publish("anothertopic", CombinedByteArr, 0, False) def on_connect(mqttc, userdata, flags, rc): print("[INFO] : MQTT : Connection returned result: " + mqtt.connack_string(rc)) if(rc == 0): print("[INFO] : MQTT : Connection Successful") else: print(rc) def on_disconnect(mqttc, userdata, rc): if rc != 0: print(" Unexpected disconnection") while(True): try: print("Trying to Reconnect") mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL) break except: print("Error in Retrying to Connect with Broker") continue # Initiate MQTT Client ThreadID = str(current_thread().ident) mqttc = mqtt.Client(client_id= ThreadID, clean_session=False) mqttc.on_publish = on_publish mqttc.on_connect = on_connect mqttc.on_message = on_message mqttc.on_disconnect = on_disconnect while(True): try: mqttc.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL) print("[INFO] : MQTT : MQTT Connect Complete") break except: print("ERROR Occurred") mqttc.loop_start() # Start A Thread The I run multiple python files that means multiple copies of MQTT are run. In mosquitto logs it always shows Client keep on disconnecting and then reconnecting. I get these continously after some time in mosquitto logs: - 1518788230: New client connected from 127.0.0.1 as MQTT2225 (c0, k60). 1518788230: Sending CONNACK to MQTT2225…
tagged with: paho
upvote count: 2
tagged with: mosquitto
answer count: 1
has comment: http://stackoverflow.com/comment/84660655
favorite count: 0
tagged with: mqtt
tagged with: disconnection
has comment: http://stackoverflow.com/comment/84659835
tagged with: python
has comment: http://stackoverflow.com/comment/84659889
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/48954080
tagged with: python
has comment: http://stackoverflow.com/comment/84917214
type: AnsweredQuestion
has title: Why is dask read_csv from s3 keeping so much memory?
downvote count: 0
tagged with: amazon-s3
has comment: http://stackoverflow.com/comment/84997868
type: Question
has comment: http://stackoverflow.com/comment/85107818
accepted answer: http://stackoverflow.com/a/49073208
answer count: 1
has comment: http://stackoverflow.com/comment/84960664
has comment: http://stackoverflow.com/comment/84960785
score: 15
has answer: http://stackoverflow.com/a/49073208
has body: I'm reading in some gzipped data from s3, using dask (a replacement for a SQL query). However, it looks like there is some caching of the data file, or unzipped file somewhere that keeps in system memory. NB this should be runnable, the test data here is used from the pandas test suite in a public s3 bucket. import dask.dataframe as dd import pandas as pd import psutil as ps import os #for easier vis mb = 1048576 def mytestfunc(file): process = ps.Process(os.getpid()) print('initial memory: {0}'.format(process.memory_info().rss/mb)) data = dd.read_csv(file, compression = 'gzip', blocksize = None, storage_options = {'anon':True}) print('dask plan memory: {0}'.format(process.memory_info().rss/mb)) data = data.compute() print('data in memory: {0}'.format(process.memory_info().rss/mb)) print('data frame usage: {0}'.format(data.memory_usage(deep=True).sum()/mb)) return data process = ps.Process(os.getpid()) print('before function call: {0}'.format(process.memory_info().rss/mb)) out = mytestfunc('s3://pandas-test/large_random.csv.gz') print('After function call: {0}'.format(process.memory_info().rss/mb)) # out = mytestfunc('s3://pandas-test/tips.csv.gz') # print('After smaller function call: {0}'.format(process.memory_info().rss/mb)) Which gives me: before function call: 76.984375 initial memory: 76.984375 dask plan memory: 92.9921875 data in memory: 224.71484375 data frame usage: 38.14704895019531 After function call: 224.7265625 Naively, I would expect the 'after function call' to be the 'before function call' plus the dataframe and a bit of overhead. Here, the gzip is 43mb, and results in an overhead of about 90mb, in my real example, this extra part is about 50gb of extra memory for a 10gb dataframe. You can see that the memory is freed up if you rerun on another, smaller file - uncomment the rerun on the smaller file to see it. This also shows that the increase is due to the file size - you can switch the order and run 'tips' first and the memory stays at ~90mb. I am…
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84960360
has comment: http://stackoverflow.com/comment/85079862
upvote count: 15
has comment: http://stackoverflow.com/comment/84964647
favorite count: 0
tagged with: dask

http://stackoverflow.com/comment/84713086
score: 0
comment on: http://stackoverflow.com/a/48854803
type: AnswerComment
has text: @Jean-FrançoisFabre, you're right, the input data is at fault. This is just one sample out of 99000. Since I'm going ahead with the assumption that the comma is a separator, your solution was spot on! Thank you so much!
type: Comment

http://stackoverflow.com/comment/84921363
type: AnswerComment
has text: The concat doesn't work when the plane value is not unique. Do you have solution?
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48954135

http://stackoverflow.com/comment/120817157
has text: Above link is broken. This works: https://pip.pypa.io/en/stable/cli/pip_install/#requirement-specifiers
comment on: http://stackoverflow.com/a/48941150
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84915524
type: Comment
has text: Are you looking for an answer like this one?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48954462

http://stackoverflow.com/a/48914914
type: Answer
accepted answer of: http://stackoverflow.com/q/48914851
has comment: http://stackoverflow.com/comment/84836222
upvote count: 3
answers question: http://stackoverflow.com/q/48914851
has comment: http://stackoverflow.com/comment/84836264
has body: Your current regex is greedy (.*), so it's matching as much as possible (everything after gene= and up to the last occurrence of ;). You can make your .* lazy by adding the lazy quantifier ? as such: .*?. There exists, however, better options (reducing the number of steps until a match is found) since lazy quantifiers backtrack. Option 1 See regex in use here (?&lt;=gene=)[^;]+ (?&lt;=gene=) Positive lookbehind ensuring what precedes matches gene= literally [^;]+ Match any character except ; one or more times Result: LOC444342 Option 2 Including gene= and ; in the match, you can use the following as seen in use here gene=[^;]*; Result: gene=LOC444342;
type: AcceptedAnswer
downvote count: 0
score: 3

http://stackoverflow.com/q/48932290
has body: The error comes from the line 16 ('gender = db.Column(db.Enum(Gender), nullable=False)') of the following code. from flask_sqlalchemy import SQLAlchemy from .views import app import enum db = SQLAlchemy(app) class Gender(enum.Enum): female = 0 male = 1 other = 2 class Content(db.Model): id = db.Column(db.Integer, primary_key=True) description = db.Column(db.String(200), nullable=False) gender = db.Column(db.Enum(Gender), nullable=False) def __init__(self, description, gender): self.description = description self.gender = gender def init_db(): db.drop_all() db.create_all() db.session.add(Content("THIS IS SPARTAAAAAAA!!!", Gender['male'])) db.session.add(Content("What's your favorite scary movie?", Gender['female'])) db.session.commit() lg.warning('Database initialized!') And I get this error stack trace Traceback (most recent call last): File "run.py", line 3, in &lt;module&gt; from fbapp import app File "__init__.py", line 5, in &lt;module&gt; from . import models File "models.py", line 13, in &lt;module&gt; class Content(db.Model): File "models.py", line 16, in Content gender = db.Column(db.Enum(Gender), nullable=False) File "sqltypes.py", line 1296, in __init__ self._enum_init(enums, kw) File "sqltypes.py", line 1332, in _enum_init length = max(len(x) for x in self.enums) File "sqltypes.py", line 1332, in &lt;genexpr&gt; length = max(len(x) for x in self.enums) TypeError: object of type 'type' has no len() Could someone tell me where is my mistake ? thanks.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84875267
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84872178
tagged with: enums
score: 1
tagged with: sqlalchemy
type: Question
has answer: http://stackoverflow.com/a/75338899
has comment: http://stackoverflow.com/comment/84871918
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84871665
has comment: http://stackoverflow.com/comment/84897182
has title: creating table with python/sqlalchemy with enum type column
favorite count: 0

http://stackoverflow.com/comment/84894082
type: Comment
comment on: http://stackoverflow.com/a/48943773
type: AnswerComment
has text: Yes, I have __init__.py in my views directory
score: 0

http://stackoverflow.com/comment/84840219
has text: Thank you very much for your input. Eventually, the solution was much simpler and did not involve a TCP/IP connection: what I did was creating a block that synchs with the simulation time and pauses the simulation whenever (currentTime-previousTime)=timeStep. Then, I created an if statement in python such that 'if paused, then update parameters and resume simulation', using the get_param('modelName', 'SimulationStatus') and set_param('modelName', 'SimulationCommand', 'continue') from the matlab api imported in Python. This works fine for me.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48867145
score: 1

http://stackoverflow.com/comment/84826325
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48908693
score: 0
has text: @brunodesthuilliers It does not! But it does encapsulate the local constants together, right? Add a docstring defining the purpose of class. Name the class as LocalConstants. It is just a way of documenting. One could also define a dictionary with name LOCAL_CONSTANTS. The purpose is not to document constants only here, right? but also to give a message that these are meant to be local constants not to be used in other modules. True, You could just add a comment above the constants. But if you want to give a more serious message, You can choose latter.

http://stackoverflow.com/q/48831553
has answer: http://stackoverflow.com/a/48833620
has title: Producing a pip-installable module without using distutils or setuptools
tagged with: pip
type: AnsweredQuestion
has body: In the Python documentation (https://docs.python.org/2.7/distutils/setupscript.html) it is described a way for making a module installable via "pip install". Suppose that, for unknown reasons, you cannot rely on distutils or setuptools (a potential situation is described in my other question Distutils appharently fails with a (working) SWIG extension). Is there an alternative way for obtaining a pip-installable package? Ps: my module is written via SWIG (C wrapping). It works when compiled as usual, but it seems not to work if I compile it by using distutils/setuptools. This is the key point of the related linked question.
type: Question
answer count: 1
linked to: http://stackoverflow.com/q/48829372
accepted answer: http://stackoverflow.com/a/48833620
score: 0
tagged with: python

data-transform
type: Tag
tag name: data-transform
tags question: http://stackoverflow.com/q/48806737

http://stackoverflow.com/q/48909410
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48909534
tagged with: equation
has answer: http://stackoverflow.com/a/48909587
tagged with: definition
type: Question
upvote count: 2
possible better answer: http://stackoverflow.com/a/48909458
has comment: http://stackoverflow.com/comment/84824972
has answer: http://stackoverflow.com/a/48909528
score: 0
has title: Python (repeated values with append)
favorite count: 0
accepted answer: http://stackoverflow.com/a/48909561
has body: I have the following formula Q = Square root of [(2 * C * D)/H] And I would like to input 100,150,180 so the output i want is 18,22,24 so my code is import math c=50 h=30 value=[] def equation(a1,b1,c1): for i in (a1,b1,c1): value.append(int(math.sqrt(2*c*a1/h))) value.append(int(math.sqrt(2*c*b1/h))) value.append(int(math.sqrt(2*c*c1/h))) print (value) when I input equation(100,150,180), why is the output following? [18, 12, 24] [18, 12, 24, 18, 12, 24] [18, 12, 24, 18, 12, 24, 18, 12, 24] How do i change the code so i get only [18, 12, 24]
answer count: 5
downvote count: 2
tagged with: python
tagged with: append
has answer: http://stackoverflow.com/a/48909458
has answer: http://stackoverflow.com/a/48909561

http://stackoverflow.com/q/48831979
has comment: http://stackoverflow.com/comment/84668655
has answer: http://stackoverflow.com/a/48832666
answer count: 1
has comment: http://stackoverflow.com/comment/84668162
tagged with: regex
favorite count: 0
has title: How to concentrate lists from a loop into a single lost in python
tagged with: python-3.x
tagged with: extract
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: list
score: 1
type: Question
downvote count: 0
has body: I need to concentrate some list from a loop. I am using regex to make some extraction, then am using findall in regex which get out all your result on individual list. but i need to get all this list in one. So here is my code.. import re boy = open('mbko.txt') girl = open ('xxx.txt','w') for line in boy: line = line.rstrip() z= re.findall('[a-zA-Z0-9]\S*@\S*[a-zA-Z]',line) if len(z)&gt;0: leng= len(z) girl.write("the total length is :{}\n". format(leng)) girl.write(str(z)) print z After this i have the result ['stephen.marquard@uct.ac.za'] ['postmaster@collab.sakaiproject.org'] ['source@collab.sakaiproject.org'] ['apache@localhost'] ['stephen.marquard@uct.ac.za'] lol don't mind the naming. but i need to get the list result in one single list like ['stephen.marquard@uct.ac.za', 'postmaster@collab.sakaiproject.org', 'source@collab.sakaiproject.org', 'apache@localhost', 'stephen.marquard@uct.ac.za'] i actually added this part after the if statement to get each line join together, final = [] for i in z: #for j in i: final+=i but still can't get a good result.

http://stackoverflow.com/comment/84811829
type: QuestionComment
comment on: http://stackoverflow.com/q/48895772
score: 0
type: Comment
has text: indeed, the idea is that I pass data for JavaScript to create chart, in this particular case with morris.js.

http://stackoverflow.com/q/48838029
has answer: http://stackoverflow.com/a/48849303
upvote count: 3
accepted answer: http://stackoverflow.com/a/48848685
type: Question
possible better answer: http://stackoverflow.com/a/48849303
has comment: http://stackoverflow.com/comment/84758485
tagged with: scope
has comment: http://stackoverflow.com/comment/84692759
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84699546
has comment: http://stackoverflow.com/comment/84700920
tagged with: global
favorite count: 0
linked to: http://stackoverflow.com/q/35988
has comment: http://stackoverflow.com/comment/84699479
has comment: http://stackoverflow.com/comment/84680831
tagged with: python
has comment: http://stackoverflow.com/comment/84693761
tagged with: dictionary
has body: So, the title pretty much says it all. for instance let's look at the below example code: ## How can I obtain a dict/list (like locals()) of all the variables in second and/or third layer scopes via a command # coming from the first layer? ## Or another example would be how could I obtain the variables "locals() style" from the thirdlayer via a # command from the second layer? # essentially can a parent function/class access a list/dict of a child function # or class?? def firstLayer(): a = 4.7 q = locals() print(q) # local vars of 1st layer def secondlayer(): b = 7 r = locals() print(r) # local vars of 2nd layer def thirdlayer(): c = False s = locals() i = globals() print('c:\n', c, "\nglobals from 3rd layer:\n\t", i) # local vars of 3rd layer thirdlayer() secondlayer() firstLayer() sample_var = globals() print(sample_var) # returns the list of global variables to reiterate what I said in the comments in the code, essentially is their any way I can get a list of all the variables local to a 'child' scope? I know functions are shut off, but if their is no way to do this is their any more complicated code that could achieve this and I could integrate it into a function or class if necessary. EDIT: To elaborate further; here's the situation i'm in. def varsfunc(): font1 = "Harlow Solid" grey = '#454545' font2 = 'Mistral' font3 = 'Italic 35px Times New Roman' pnk = 'pink' grn = 'green' return locals() Essentially, I am creating a module and the user must create some type of function that they list all of they variables they would like to declare to be used to modify a css file. Essentially, I would like to allow the user to not have to type "return locals()". I want to achieve it by having the end-users wrap the above example function in a decorator that will do the equivalent of returning locals() of the exact scope I want. The decorator does not work for me because it is in an outer scope. TO BE EVEN MORE CLEAR: I need a decorator/function that wraps another function…
has title: Python - How to obtain a dictionary(or even a list) of variables in a specific scope; more specific than locals/globals()
has answer: http://stackoverflow.com/a/48848685
tagged with: locals
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/48828475
upvote count: 0
answer count: 1
favorite count: 0
tagged with: tuples
type: UnansweredQuestion
has title: Difference bwtween [1] and [1:2] in array
tagged with: python
has body: a=([1,2], [3,4], [5,6]) b=[[1,2], [3,4], [5,6]] print(a[1]) print(a[1:2]) print(b[1]) print(b[1:2]) Why the a[1] returns a list [3,4], but a[2:3] returns a tuple ([3,4])? I always thought list[1] is the same as list[1:2]. But I was wrong. Why the length of b[1] (returns a list [3,4]) is two, but the length for b[1:2] returns a list of list [[3,4]] with length 1?
tagged with: list
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48828574
score: -1

http://stackoverflow.com/comment/84783684
comment on: http://stackoverflow.com/a/48888399
score: 5
type: AnswerComment
has text: please add some information to your answer. just providing links will render your answer useless once the links are dead.
type: Comment

http://stackoverflow.com/q/48917140
has comment: http://stackoverflow.com/comment/84841101
answer count: 0
score: 1
tagged with: import
type: Question
tagged with: python-import
has title: Does a python dynamic import of module generates .pyc?
has comment: http://stackoverflow.com/comment/84841269
downvote count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84841172
tagged with: python-importlib
has comment: http://stackoverflow.com/comment/84841109
favorite count: 0
has body: I would like to have dotted name strings that I can evaluate. Those dotted names could point to functions from new files the project do not know about (to quickly add a new functionality to the project without being part of the development team). Right now, I resolve and compile the dotted names using a library (pyramid) then I save the compiled function object somewhere to be able to use it later. I've seen that importlib let us import a module and it works perfectly fine, like so: importlib.import_module('my_library') Still, normally when you import a module, a .pyc will be generated so other calls won't take as much time to execute (as they won't have to be compiled again). Do imports using importlib create .pyc files? If not, would adding it to locals() change anything? (Adding it to globals() did not seem to work for me) Like so: locals()['my_library'] = importlib.import_module('my_library')
type: UnansweredQuestion
upvote count: 1
tagged with: python

http://stackoverflow.com/q/48942079
answer count: 1
has comment: http://stackoverflow.com/comment/84891069
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84891010
has body: for image_path in TEST_IMAGE_PATHS: image = Image.open(image_path) # the array based representation of the image will be used later in order to prepare the # result image with boxes and labels on it. image_np = load_image_into_numpy_array(image) # Expand dimensions since the model expects images to have shape: [1, None, None, 3] image_np_expanded = np.expand_dims(image_np, axis=0) # Actual detection. output_dict = run_inference_for_single_image(image_np, detection_graph) # Visualization of the results of a detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, instance_masks=output_dict.get('detection_masks'), use_normalized_coordinates=True, line_thickness=8) plt.figure(figsize=IMAGE_SIZE) plt.imshow(image_np) In one of the codes for tensorflow object detection API, there is the vis_util.visualize_boxes_and_labels_on_image_array method which draws bounding boxes on the image and returns the new image_np which is fed into plt.imshow(image_np) to display. However, vis_util.visualize_boxes_and_labels_on_image_array method is not assigned to image_np variable as shown in the code. How does plt.imshow(image_np) get the latest(The image which has the drawn bounding box) image?
has title: visualize boxes in tensorflow object detection
tagged with: tensorflow
type: Question
has comment: http://stackoverflow.com/comment/84891038
has answer: http://stackoverflow.com/a/48942205
score: 0

http://stackoverflow.com/comment/84827250
type: Comment
type: QuestionComment
has text: @desertnaut kindly check now, I updated the images. When I said "right away" I meant update images.
comment on: http://stackoverflow.com/q/48909418
score: 0

http://stackoverflow.com/comment/84632535
has text: @danihp Because strictly matching a space beforehand, not sure if its necessary here, OP can confirm. Note that, in your `[a|p]`, `|` is taken literally inside `[]`.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48814334

http://stackoverflow.com/comment/84614310
comment on: http://stackoverflow.com/a/48805233
type: AnswerComment
has text: Not really. It just the way you sampled your function which was not dense enough. To understand try plotting with points marker '.'.
score: 0
type: Comment

http://stackoverflow.com/comment/84699479
score: 0
type: Comment
has text: A dict of values was my old idea but, I was trying to improve it from that.. I guess I might just have to make the end user do more work but, nobody likes using a confusing module.
type: QuestionComment
comment on: http://stackoverflow.com/q/48838029

http://stackoverflow.com/comment/84831758
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48912500
has text: what python version u have selected "36" is it valid??

http://stackoverflow.com/comment/84655016
type: QuestionComment
comment on: http://stackoverflow.com/q/48825468
score: 0
has text: @CongMa The `list` is necessary in Python3 (and harmless in Python2). Well, converting something using summing and multiplying where in theory only a reinterpretation should be necessary, doesn't seem "nice" even though it works.
type: Comment

http://stackoverflow.com/comment/84839280
comment on: http://stackoverflow.com/q/48916226
score: 0
has text: @C8H10N4O2 I want the output of above to be abc and memo... which are like the "first" instances in each numbered list.. I was thinking like regex to match `{` on left and '} (' on right to do this.. as this will capture abc and memo.. but unable to come up with regex
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84912043
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48906241
has text: Is there also an efficient way to exclude - say the first entry(/column value) from each of the arrays, since they actually represent ids.. and concatenate these identifiers from the different arrays. ? a = [[ 0, -0.02], [1, -0.15]] b = [[0, 0.03]] so result = array([[ '0_0_0' , 0.03], # ['0_0_1' , 0.16], # [ '1_0_0' , -0.1 ], # [ '1_0_1' , 0.03]]) I understand that storing them as strings may not be totally efficient, so am looking for a better way.

http://stackoverflow.com/a/48869231
answers question: http://stackoverflow.com/q/48869168
score: 1
has body: You cannot use advanced indexing with lists, but your code should work if you do yel = ye[0] which is actually equivalent to the current line for arrays that implement advanced indexing.
downvote count: 0
has comment: http://stackoverflow.com/comment/84742424
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84917133
has text: @Andersson It is working! Thanks so much for both of you. Save my time!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48953127

http://stackoverflow.com/a/48838518
has body: use eval temp = eval("Sample("+my_str+")")
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48838289
score: 1

http://stackoverflow.com/a/48965274
upvote count: 1
has body: You get this error because you run the cell defining the model twice. As the code uses internally tf.get_variable it complains that the variable has already be defined in the graph. If you want to create a new model (e.g. run the model cell a second time), you might need to reset the default graph using tf.reset_default_graph
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48959947

http://stackoverflow.com/comment/84671204
type: QuestionComment
has text: i will suggest you to update your question with both the models, views and serializers you are using, that will help to come up with more accurate answer.
comment on: http://stackoverflow.com/q/48804687
score: 0
type: Comment

http://stackoverflow.com/q/48836596
tagged with: function
has answer: http://stackoverflow.com/a/48836654
accepted answer: http://stackoverflow.com/a/48836654
downvote count: 0
has comment: http://stackoverflow.com/comment/84678003
favorite count: 0
tagged with: python
duplicate of: http://stackoverflow.com/q/9884764
upvote count: 3
has title: How does using '?' for object information work?
has comment: http://stackoverflow.com/comment/84678049
possible better answer: http://stackoverflow.com/a/48836652
has comment: http://stackoverflow.com/comment/84678070
type: Question
type: AnsweredQuestion
score: 3
has answer: http://stackoverflow.com/a/48836652
linked to: http://stackoverflow.com/q/9884764
has body: I stumbled upon the following syntax in Python decorator to keep signature and user defined attribute: &gt; def func(): ... return "Hello World!" ... &gt; func? Signature: func() Docstring: &lt;no docstring&gt; File: ~/&lt;ipython-input-8-934f46134434&gt; Type: function Attempting the same in my Python Shell, whether 2 or 3, simply raises a SyntaxError. So what is this exactly, is it specific to some shells?
tagged with: ipython
duplicate of: http://stackoverflow.com/q/34393217
linked to: http://stackoverflow.com/q/48746567
answer count: 2

http://stackoverflow.com/a/48829267
upvote count: 7
has body: See below an example using FormData. But please note it may not work on old IE browsers (I think 8, 9 won't work). &lt;input type="file" id="upload_file" data-import-url="{% url 'upload_file' %}" data-csrf-token="{{ csrf_token }}" multiple&gt; Then the jQuery: $("#upload_file").change(function () { var url = $(this).attr("data-import-url") var data = new FormData(); $.each($("#upload_file")[0].files, function(i, file) { data.append("file", file); }); data.append("csrfmiddlewaretoken", $(this).attr("data-csrf-token")); $.ajax({ url: url, data: data, cache: false, contentType: false, processData: false, type: 'post', beforeSend: function () { // before send, display loading, etc... }, success: function (data) { // success handling... }, error: function () { // error handling... } }); }); In your view you could get it like this: uploaded_files = request.FILES.getlist('file') If you need to support older browsers, the jQuery File Upload is a really good library. I've written a tutorial about multiple files upload using Django + Ajax (using this particular library).
has comment: http://stackoverflow.com/comment/84663287
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48829089
score: 7
accepted answer of: http://stackoverflow.com/q/48829089
type: Answer

multiprocessing
tags question: http://stackoverflow.com/q/48927506
tags question: http://stackoverflow.com/q/48953878
tags question: http://stackoverflow.com/q/48814788
tags question: http://stackoverflow.com/q/48904556
tags question: http://stackoverflow.com/q/48808472
tags question: http://stackoverflow.com/q/48838346
tags question: http://stackoverflow.com/q/48932757
tags question: http://stackoverflow.com/q/48846085
tags question: http://stackoverflow.com/q/48939847
tags question: http://stackoverflow.com/q/48860553
tags question: http://stackoverflow.com/q/48807196
tags question: http://stackoverflow.com/q/48947290
tags question: http://stackoverflow.com/q/48867620
tags question: http://stackoverflow.com/q/48900923
tags question: http://stackoverflow.com/q/48914833
tags question: http://stackoverflow.com/q/48822463
tags question: http://stackoverflow.com/q/48870758
tags question: http://stackoverflow.com/q/48902620
tags question: http://stackoverflow.com/q/48857362
tags question: http://stackoverflow.com/q/48835700
tags question: http://stackoverflow.com/q/48950516
tags question: http://stackoverflow.com/q/48811375
tags question: http://stackoverflow.com/q/48879277
tags question: http://stackoverflow.com/q/48870608
type: Tag
tag name: multiprocessing

http://stackoverflow.com/q/48857500
has answer: http://stackoverflow.com/a/48857801
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48857516
has title: Modifying Python 3.6.4 list elements
has body: So I have 2 lists: L1 = ['a', 'b', 'c', 'd'] L2 = ['1', '2', '3', '4'] I need my result to look like this: ['a1', 'b2', 'c3', 'd4'] I used a for loop, but I can't seem to get it right. This is what I did: L3 = [] L1 = ['a', 'b', 'c', 'd'] L2 = ['1', '2', '3', '4'] for i in range(len(L1)): L3 += L1[i] + L2[i] print(L3) My results end up looking like: ['a', '1', 'b', '2', 'c', '3', 'd', '4'] And that's all I have. Any help would be greatly appreciated!
tagged with: python
score: 2
tagged with: python-3.x
tagged with: list
upvote count: 2
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48857547
has answer: http://stackoverflow.com/a/48857557
has answer: http://stackoverflow.com/a/48857538
type: Question

http://stackoverflow.com/comment/84644192
type: QuestionComment
comment on: http://stackoverflow.com/q/48820022
has text: why is it that your file `tfidf_vectorizer` has no extension. Shouldn't it be something like `tfidf_vectorizer.json` or something like that @KlausD.
score: 0
type: Comment

http://stackoverflow.com/comment/84677632
score: 0
type: Comment
type: QuestionComment
has text: Possible duplicate of [Python: Call method by instance object: "missing 1 required positional argument: 'self'"](https://stackoverflow.com/questions/20023986/python-call-method-by-instance-object-missing-1-required-positional-argument)
comment on: http://stackoverflow.com/q/48832690

http://stackoverflow.com/a/48813862
has body: Without re, which is probably more efficient, and with some assumptions: the string always start with '{ and ends with }' top level elements are separated by ,'' and no other ,'' in the data sublevel elements are separated by , and no other , in the data then this can be done like this: ms = "'{output:{OUTPUT_PATH:hdfs://x.x.x.x:X/tmp/x/x,OUTPUT_TYPE:hdfs},''input:{INPUT_TEMPTABLE:sample,INPUT_TYPE:hdfs,INPUT_PATH:hdfs://x.x.x.x:X/sparkStream/sample1/},''process:{query.param:${http.query.param.name},PROCESS_SQL:1,PROCESS_TYPE:sql},''attributes:{path:./,restlistener.remote.source.host:127.0.0.1,filename:1211999192960535,restlistener.remote.user.dn:none,uuid:2b025f49-7d53-49db-8063-24ddda29fc4a}}'" result = {} # get rid of '{ and '} # split on ,'' for e in ms[2:-2].split(",''"): # e is top level # split on { # e[0] is toplevel key # e[1] is sublevel e = e.split('{',1) # p is sublevel # if multiple sublevels split on , p = e[1].split(',') if ',' in e[1] else [e[1]] i_dict = {} for v in p: # for each value in p get rid of trailing } v = v.rstrip('}') # split the value # i[0] is sublevel key # i[1] is sublevel value i = v.split(':',1) #add to sublevel dict i_dict[i[0]] = i[1] #add sublevel dict as value for toplevel result[e[0][:-1]] = i_dict print(result) output is a dictionary: {'output': {'OUTPUT_PATH': 'hdfs://x.x.x.x:X/tmp/x/x', 'OUTPUT_TYPE': 'hdfs'}, 'input': {'INPUT_TEMPTABLE': 'sample', 'INPUT_TYPE': 'hdfs', 'INPUT_PATH': 'hdfs://x.x.x.x:X/sparkStream/sample1/'}, 'process': {'query.param': '${http.query.param.name', 'PROCESS_SQL': '1', 'PROCESS_TYPE': 'sql'}, 'attributes': {'path': './', 'restlistener.remote.source.host': '127.0.0.1', 'filename': '1211999192960535', 'restlistener.remote.user.dn': 'none', 'uuid': '2b025f49-7d53-49db-8063-24ddda29fc4a'}} with the absence of other input strings, this code is not further tested, YMMV.
type: Answer
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48812506
accepted answer of: http://stackoverflow.com/q/48812506
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84896421
has text: Kindly excuse me. Not able to get. Your full recode please
score: 0
comment on: http://stackoverflow.com/q/48944802
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84674587
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48834765
has text: Ok, so i have instantiated the class... But using the get() method to access the attribute of init_alarm_gui class says there is no attribute. Do i need to inherit the properties of init_alarm_gui to Alarm_clock?
type: AnswerComment

http://stackoverflow.com/q/48893231
has title: what makes the time limit?
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48894267
possible better answer: http://stackoverflow.com/a/48894273
has body: N = int(input()) matrix = [[0 for x in range(N)] for y in range(N)] def Print(matrix): for row in matrix: for elem in row: print(elem, end=' ') print() def is_attacked(matrix,j,i,N): for a in range(N): for b in range(N): if matrix[a][b]: if j == a or i-j == b-a or b == i or i+j == b+a: return(True) return(False) def alg(matrix,N,number_of_queens): if number_of_queens == 0: return(True) for a in range(N): for b in range(N): if is_attacked(matrix,a,b,N): continue matrix[a][b] = 1 if alg(matrix,N,number_of_queens-1): return(True) else: matrix[a][b] = 0 return(False) if alg(matrix,N,N): print("YES") Print(matrix) else: print("NO") This is the solution to the Eight queen chess problem on Hackerearth the problem is that i get time exceeded on my last input but i implemented the algorithm correctly and i revised the code maybe it is because python is slower from other languages.what takes time in my code?.Hackerearth link:https://www.hackerearth.com/practice/basic-programming/recursion/recursion-and-backtracking/tutorial/
tagged with: python
tagged with: backtracking
tagged with: recursion
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48894273
type: Question
accepted answer: http://stackoverflow.com/a/48894267

http://stackoverflow.com/a/48935095
type: Answer
has comment: http://stackoverflow.com/comment/111541119
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/111541206
has comment: http://stackoverflow.com/comment/111543178
has comment: http://stackoverflow.com/comment/84901354
has comment: http://stackoverflow.com/comment/111541034
has comment: http://stackoverflow.com/comment/84904086
has body: You can access the gateway id via the config.slaveinput attribute. Example: def test_spam(pytestconfig): assert hasattr(pytestconfig, 'slaveinput') assert pytestconfig.slaveinput['slaveid'] == 'gw0' The test will only pass when xdist is actually invoked, e.g. via pytest -n1 test_spam.py, otherwise the slaveinput attribute won't be set.
upvote count: 2
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48934551
accepted answer of: http://stackoverflow.com/q/48934551

http://stackoverflow.com/q/48827311
has answer: http://stackoverflow.com/a/77494692
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48828549
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48833703
tagged with: web-scraping
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/48828549
has comment: http://stackoverflow.com/comment/84659991
has body: I am trying to web scrape my facebook page to get the birthdays of all my friends. Since facebook uses ajax calls to load the friends names in the "birthday events" page, i looked in the network activity in chrome dev tools to figure out where and how its doing the xhr calls and how the response data is . The response from these calls , don't mean anything to me . They're looking like they're obfuscated or something... How to extract the data that I see on the site using the response data I get when the xhr calls are made ? here is the response data : for (;;); { "__ar": 1, "payload": null, "domops": [ ["replace", "#birthdays_pager", false, { "__html": "\u003Cdiv class=\"_4-u2 _tzh _fbBirthdays__monthCard _4-u8\"&gt;\u003Cdiv class=\"_4-u3 _5dwa _5dw9\" id=\"birthdays_monthly_card_1522566000\"&gt;\u003Cspan class=\"_38my\"&gt;April\u003Cspan class=\"_c1c\"&gt;\u003C\/span&gt;\u003C\/span&gt;\u003Cspan class=\"_5dw8\"&gt;\u003Cdiv class=\"_tzj\"&gt;\u003Ca href=\"https:\/\/www.facebook.com\/kajal.chaudhary.5492\"&gt;Kajal Chaudhary\u003C\/a&gt;, \u003Ca href=\"https:\/\/www.facebook.com\/shreesha.bhat.963\"&gt;Shreesha Bhat Galimane\u003C\/a&gt; and 19 others\u003C\/div&gt;\u003C\/span&gt;\u003Cdiv class=\"_3s3-\"&gt;\u003C\/div&gt;\u003C\/div&gt;\u003Cdiv class=\"_4-u3\"&gt;\u003Cdiv class=\"_43qm _tzu _43q9\"&gt;\u003Cul class=\"uiList _4cg3 _509- _4ki\"&gt;\u003Cli class=\"_43q7\"&gt;\u003Ca href=\"https:\/\/www.facebook.com\/satish.ven.58\" class=\"link\" data-jsid=\"anchor\" data-hover=\"tooltip\" data-tooltip-content=\"Satish Ven (4\/2)\"&gt;\u003Cimg class=\"_s0 _ry img\" src=\"https:\/\/scontent.fblr6-1.fna.fbcdn.net\/v\/t1.0-1\/p57x57\/27540391_2084438825122967_6451048031944951645_n.jpg?oh=77383450a07722e1a44bf39c6d2c12f7&amp;amp;oe=5B19517E\" alt=\"Satish Ven\" data-jsid=\"img\" \/&gt;\u003C\/a&gt;\u003C\/li&gt;\u003Cli class=\"_43q7\"&gt;\u003Ca href=\"https:\/\/www.facebook.com\/sheshufirefox\" class=\"link\" data-jsid=\"anchor\" data-hover=\"tooltip\" da…
has title: how to get useful data from xhr responses in facebook page?
has comment: http://stackoverflow.com/comment/84661698
has comment: http://stackoverflow.com/comment/84660101
answer count: 3
upvote count: 1
tagged with: facebook-graph-api
favorite count: 0
tagged with: facebook
possible better answer: http://stackoverflow.com/a/48833703
tagged with: python

http://stackoverflow.com/comment/84839219
type: AnswerComment
comment on: http://stackoverflow.com/a/48883293
score: 0
type: Comment
has text: Great. Somehow I missed this.

http://stackoverflow.com/a/48935666
upvote count: 3
has body: In what format is the path to your local files? You could simply check if your input string is a URL: if url.startswith('http'): link = urlopen(url).read() else: link = open(url) Otherwise just convert your local files' path to a file URI scheme and you should be able to open them like a regular URL
downvote count: 0
answers question: http://stackoverflow.com/q/48935514
type: Answer
score: 3

http://stackoverflow.com/q/48850446
has title: How to print a binary tree in as a structure of nodes in Python
score: 4
answer count: 3
has answer: http://stackoverflow.com/a/49844237
tagged with: tree-traversal
type: UnansweredQuestion
upvote count: 4
downvote count: 0
has body: I have a python code to convert a string mathematical expression into a binary tree and order the nodes of the tree so the left child will be always smaller than the right child. I want to print the binary tree in the following order. For example consider the mathematical expression ((2 * 75) / 4). buildParseTree() converts the string expression into a tree and printNodeInLevels() rearranges the nodes so left child is smaller than the right right child at each level. Operands &lt; operators and operators are orders as '+' &lt; '-' &lt; '*' &lt; '/'. If the structure of the tree is like this + /\ 4 * /\ 2 75 I want to print it as follows. How should I go about this? Because the length of the mathematical expressions vary all the time e.g (24 * 2), ((5 - 1) * (2 / 3)), (20 - (5 + 4)) etc Node("+") #root .addkid(Node("*") #right child at level 1 .addkid(Node("75")) #right child at level 2 .addkid(Node("2")) #left child at level 2 ) .addkid(Node("4")) #left child at level 1 I have worked out the method to print nodes by their levels as in an in-order traversal pattern.If I call the method as follows it will print the following: pt = buildParseTree("( ( 2 * 74 ) / 4 )") printNodesInLevels(pt) output: / 4 * 2 74
favorite count: 0
tagged with: binary-tree
has answer: http://stackoverflow.com/a/48850663
type: Question
has answer: http://stackoverflow.com/a/58104529
tagged with: python

http://stackoverflow.com/comment/84781506
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48887664
type: Comment
has text: The First new error isE1101:Module 'pygame' has no 'init' member, and 13 errors on the list. I feel lost because I did not write the code, I just copied down it as it is a sample on the book.

http://stackoverflow.com/comment/84910300
score: 0
has text: Thank you, this worked! I noticed whole values were simply displayed as "3.". Would there be any way to pad the zeros for "3.00" for consitency?
comment on: http://stackoverflow.com/q/48951639
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48815919
has comment: http://stackoverflow.com/comment/84639553
type: Question
tagged with: transform
score: 0
has comment: http://stackoverflow.com/comment/84639572
has comment: http://stackoverflow.com/comment/84639848
tagged with: python
tagged with: data-fitting
has comment: http://stackoverflow.com/comment/84639491
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84640074
has title: Predicting the class of an article
has comment: http://stackoverflow.com/comment/84639609
has body: I have successfully trained an SVM on 7 different classes. I train the clf in another method that I then pass into test. What test does is accept a website, extracts the main article from the website and then classifies that article using the clf from train. I then proceed to clean the entire article, and once its cleaned, I try to fit transform and classify it, but its not working out as well as expected I keep getting different errors, which I have been trying to fix, but the latest error got me thinking I might be approaching this in fundamentally the wrong way. def test(text_clf_svm): print "Analysing Webpage" #Gets the URL from the extension url = "https://www.theguardian.com/commentisfree/2018/feb/15/corbyn-mcdonnell-tax-radical-labour" #Goose loaded g = Goose() #Extract the text and feed it to the classifier article = g.extract(url=url) article = article.cleaned_text article = clean(article) article =str(article) print "Vectorising Text" print "Predicting Political Bias" vect = CountVectorizer(min_df=0., max_df=1.0) predicted_svm = text_clf_svm.predict(vect.fit_transform([article])) print predicted_svm This is the latest error I get: (fyp) Lucass-MacBook-Pro:fyp lucasbenitez$ python final_fyp.py Training Analysing Webpage Cleaning Article Vectorising Text Predicting Political Bias Traceback (most recent call last): File "final_fyp.py", line 114, in train() File "final_fyp.py", line 66, in train test(text_clf_svm) File "final_fyp.py", line 38, in test predicted_svm = text_clf_svm.predict(vect.fit_transform([article])) File "//anaconda/envs/fyp/lib/python2.7/site-packages/sklearn/utils/metaestimators.py", line 54, in out = lambda *args, **kwargs: self.fn(obj, *args, **kwargs) File "//anaconda/envs/fyp/lib/python2.7/site-packages/sklearn/pipeline.py", line 326, in predict Xt = transform.transform(Xt) File "//anaconda/envs/fyp/lib/python2.7/site-packages/sklearn/feature_extraction/text.py", line 893, in transform _, X = self._count_vocab(raw_documents, fixed_voca…
tagged with: svm

http://stackoverflow.com/comment/84652883
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48807108
has text: Please, give us more details about your use case. Where is the user getting access and why are you using oauth 2 and not the [Google Sign-In](https://cloud.google.com/appengine/docs/flexible/python/authenticating-users)?

http://stackoverflow.com/a/48943101
downvote count: 0
has body: It figured out to be quite simple: in this function def listen_for_result(self): """ Check if there is something in the queue. """ try: self.res = self.thread_queue.get(0) self._print(self.res) except queue.Empty: self.root.after(100, self.listen_for_result) should be added one more call to itself - even after successfull printing. After this - I can send text to queue from anywhere and it will be printed without calling this function right after sending text to queue. def listen_for_result(self): """ Check if there is something in the queue. """ try: self.res = self.thread_queue.get(0) self._print(self.res) self.root.after(100, self.listen_for_result) except queue.Empty: self.root.after(100, self.listen_for_result) So now self.thread_queue.put('Getting files\n') can be used in any thread. Instead of self.thread_queue.put('Getting files\n') self.root.after(100, self.listen_for_result) double lines like before.
answers question: http://stackoverflow.com/q/48862213
accepted answer of: http://stackoverflow.com/q/48862213
type: Answer
upvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/93635820
type: AcceptedAnswer

http://stackoverflow.com/comment/84844361
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48918530
type: QuestionComment
has text: Your description is exactly how I'd go about it, even though I've never had to do this before. Which part is giving you trouble?

http://stackoverflow.com/q/48877944
has answer: http://stackoverflow.com/a/48906523
type: Question
has comment: http://stackoverflow.com/comment/84761454
tagged with: javascript
has title: how do I call specific function in views.py through ajax call in javascript file?
tagged with: ajax
score: 0
answer count: 3
has comment: http://stackoverflow.com/comment/84760388
has answer: http://stackoverflow.com/a/48878906
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48878991
tagged with: django
tagged with: python
has body: In Django we map URLs to functions in views.py. If we do an ajax call then we need to mention url in ajax call but that will call the function mapped to that url. I want to call specific function from views.py via ajax call? What should I do so that I can call any function in views.py via AJAX call without changing url? views.py def index(request): codes=Code.objects.all()[:10] context={ 'name': 'KD', 'codes': codes } return render(request,'coding/index.html',context) def details(request): code=Code.objects.get(1) context={ 'code': code } return render(request, 'coding/details.html', context) urls.py from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.index, name="index" ), path('details',views.details, name="details" ), ]; javascript

http://stackoverflow.com/q/48957190
tagged with: django
type: AnsweredQuestion
has body: Django Version: 1.8 Python Version: 3.5.2 Getting this Error when i'm running this app on production, from Windows to Linux PC Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'dasboard') Traceback: File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response 119. resolver_match = resolver.resolve(request.path_info) File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/django/core/urlresolvers.py" in resolve 366. for pattern in self.url_patterns: File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/django/core/urlresolvers.py" in url_patterns 402. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/django/core/urlresolvers.py" in urlconf_module 396. self._urlconf_module = import_module(self.urlconf_name) File "/home/ubuntu/var/www/django_env/lib/python3.5/importlib/__init__.py" in import_module 126. return _bootstrap._gcd_import(name[level:], package, level) File "/home/ubuntu/var/www/mydashboard/mydashboard/urls.py" in &lt;module&gt; 3. from dasboard import views File "/home/ubuntu/var/www/mydashboard/dasboard/views.py" in &lt;module&gt; 6. from rest_framework.response import Response File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/rest_framework/response.py" in &lt;module&gt; 13. from rest_framework.serializers import Serializer File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/rest_framework/serializers.py" in &lt;module&gt; 30. from rest_framework.compat import postgres_fields, unicode_to_repr File "/home/ubuntu/var/www/django_env/lib/python3.5/site-packages/rest_framework/compat.py" in &lt;module&gt; 26. from django.urls import ( **# noqa** Exception Type: ImportError at / Exception Value: No module named 'djang…
accepted answer: http://stackoverflow.com/a/48957559
possible better answer: http://stackoverflow.com/a/48957307
type: Question
upvote count: 2
answer count: 2
has answer: http://stackoverflow.com/a/48957559
has title: Trying to deploy an app in Production getting this No module named 'django.urls' error
favorite count: 0
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48957307
tagged with: python
score: 2
downvote count: 0

convolution
tags question: http://stackoverflow.com/q/48875980
tags question: http://stackoverflow.com/q/48921574
tag name: convolution
tags question: http://stackoverflow.com/q/48860388
tags question: http://stackoverflow.com/q/48889769
type: Tag

http://stackoverflow.com/a/48881371
type: Answer
accepted answer of: http://stackoverflow.com/q/48875601
score: 2
has comment: http://stackoverflow.com/comment/84791961
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/103926914
has body: There are 2 main causes of issues in your code The use of the python's built-in sum function. this is a function that takes an iterable of number and return their sum. e.g. if you try to sum a slice of the dataframe df, you will get the same error traceback sum(df.loc[1]) TypeError Traceback (most recent call last) &lt;ipython-input-60-6dea0ab0880f&gt; in &lt;module&gt;() ----&gt; 1 sum(df.loc[1]) TypeError: unsupported operand type(s) for +: 'int' and 'str' To fix this, you'll need to use pandas sum function as shown below df.loc[1].sum() #output A 2 B 4 C 6 dtype: int64 As you can see, this will produce the expected result. i.e. sums the columns in the data-slice The second issue is the "reduce" stage. each process will return a single dataframe, the lines result = sorted(result, key=lambda x: x[0]) return pd.concat([i[1] for i in result]) The first line will produce an error as whenever none of the result has a column called 0. similar issue with the second line. this can be resolved as follows return pd.concat(result,axis=1) Now the code will run without issue given the data being used. The overall code: import multiprocessing as mp import pandas as pd import numpy as np def _apply_df(args): df, func = args return df.groupby(level=0).apply(func) def mp_apply(df, func): workers = 4 pool = mp.Pool(processes=workers) split_dfs = np.array_split(df, workers, axis=1) result = pool.map(_apply_df, [(d, func) for d in split_dfs]) pool.close() #result = sorted(result, key=lambda x: x[0]) return pd.concat(result,axis=1) def my_func(x): return x.sum() if __name__ == '__main__': df = pd.DataFrame([[1, 2, 3, 1], [1, 2, 3, 1], [4, 5, 6, 2], [7, 8, 9, 2]], columns=['A', 'B', 'C', 'cluster_id']) df = df.set_index('cluster_id') out = mp_apply(df, my_func) print(out) Output: A B C cluster_id 1 2 4 6 2 11 13 15
has comment: http://stackoverflow.com/comment/98824994
downvote count: 0
has comment: http://stackoverflow.com/comment/84801239
answers question: http://stackoverflow.com/q/48875601
upvote count: 2

http://stackoverflow.com/q/48820336
tagged with: python
has comment: http://stackoverflow.com/comment/84657516
score: 2
linked to: http://stackoverflow.com/q/4581727
answer count: 0
type: Question
has body: I have developed a simple flask app locally where I was using SQLite database to perform the login. Now I have deployed it to Heroku and realized that Heroku doesn't support SQLite, that's why now I need to change it to another database. Here's what I have done with SQLite: Here's how i have created table: from sqlalchemy import create_engine from sqlalchemy import Column, Date, Integer, String from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///tutorial.db', echo=True) Base = declarative_base() # Create USER model class User(Base): __tablename__ = "users" id = Column(Integer, primary_key=True) username = Column(String) password = Column(String) def __init__(self, username, password): self.username = username self.password = password Base.metadata.create_all(engine) Here's how i'm using SQlite for login: from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///tutorial.db', echo=True) @app.route('/login', methods=['GET', 'POST']) def lodadata(): POST_USERNAME = str(request.form['uid']) POST_PASSWORD = str(request.form['upass']) session = sessionmaker(bind=engine) s = session() query = s.query(User).filter(User.username.in_([POST_USERNAME]), User.password.in_([POST_PASSWORD])) result = query.first() if result: session['logged_in'] = True else: flash('Something wrong about Login Detail') How can I change my database to another DB which supported by Heroku? Help me, please! Thanks in advance!
tagged with: flask
tagged with: sqlite
downvote count: 0
tagged with: flask-sqlalchemy
favorite count: 0
tagged with: postgresql
upvote count: 2
type: UnansweredQuestion
has title: Transform flask with sqlite to Flask with postgres
has comment: http://stackoverflow.com/comment/84648589

http://stackoverflow.com/a/48946429
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48946323
type: Answer
answers question: http://stackoverflow.com/q/48946323
has body: You can create the required command by first iterating over the list(obs_dir) and forming the string. Ex: import os obs_dir = ['18185','18186','18187','19926','19987','19994','19995','20045','20046','20081'] xid = ['src21'] s = "pset combine_spectra src_arfs=" for i in obs_dir: s += "/{0}/{1}_{0}_spectrum.arf, ".format(i, xid[0]) s = s.strip().rstrip(',') print s #os.system(s)
upvote count: 3
score: 3

http://stackoverflow.com/a/48957568
type: Answer
score: 2
has body: Django ImageField by default verifies that the uploaded file contains a valid image, in fact it hands over image data to PIL to process. One could subclass ImageField and override its to_python method so that the resize filters are applied on the first step of validation, however it's more convenient to implement custom clean_* method, here's an example: class MyModel(models.Model): image = models.ImageField(upload_to='images/%Y/%m/%d/', blank=True, null=True) class MyModelForm(ModelForm): def clean_image(self): img = self.cleaned_data.get('image') if not img: return img maxdim = 1024 if any(dim &gt; maxdim for dim in img.image.size): # Resize too large image up to the max_size from PIL import Image i = Image.open(img.file) fmt = i.format.lower() i.thumbnail((maxdim, maxdim)) # We must reset io.BytesIO object, otherwise resized image bytes # will get appended to the original image img.file = type(img.file)() i.save(img.file, fmt) return img class Meta: model = models.MyModel Things to note: Original image bytes are stored in the img.file attribute img.file is an instance of the io.BytesIO PIL.Image instance of the orig. image is stored in the img.image attribute
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48934147
answers question: http://stackoverflow.com/q/48934147
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/124819033
has comment: http://stackoverflow.com/comment/110950373

http://stackoverflow.com/a/48928576
answers question: http://stackoverflow.com/q/48928108
downvote count: 0
type: Answer
upvote count: 1
has body: The expression property getter has to be called explicitly. obj_val = instance.obj.expr() print(obj_val)
score: 1

http://stackoverflow.com/a/48866923
has body: As mentioned in my comment your problem is not solveable in O(n) for most matrices. Some other thoughts: Why count j downwards? i and j can never become n Here is a solution in O(n) that perhaps fullfills your needs. Here is the adapted code: def findLessX(m,n,x): i = 0 j = 0 while True: if i+1&lt;n and m[i+1][j]&lt;x: i=i+1 elif j+1&lt;n and m[i][j+1]&lt;x: j=j+1 else: print("n found at ", i+1 , " ", j+1, "or element not found so return max") return (i+1)*(j+1)
has comment: http://stackoverflow.com/comment/84737884
type: Answer
answers question: http://stackoverflow.com/q/48864696
has comment: http://stackoverflow.com/comment/84737284
score: 0

mixed-integer-programming
tags question: http://stackoverflow.com/q/48834817
tag name: mixed-integer-programming
type: Tag

http://stackoverflow.com/comment/84614189
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48805703
has text: Try removing the inner parentheses.
score: 0

http://stackoverflow.com/comment/84716177
score: 0
type: Comment
type: QuestionComment
has text: what is in test_number? what is Q? Assisting you will be much easier, if you can edit your question to produce a complete question with sample data and all the details provided. = )
comment on: http://stackoverflow.com/q/48855998

http://stackoverflow.com/comment/84664621
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48830324
score: 0
has text: `df = df.groupby(['foo','bar']).mean()`, it is dupe :(

http://stackoverflow.com/a/48926671
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48926212
answers question: http://stackoverflow.com/q/48926212
has body: Once you've made a meshgrid R is no longer a single value but an array. Furthermore, scipy.integrate.quad returns a tuple of the value and the estimated error. It's maybe a question of personal taste but I like to use lambda only for anonymous functions. Otherwise, I just get confused. My solution is probably not the fastest but it's good enough given the current parameters I think. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy.integrate import quad from scipy.special import jn def integrand(x, r): return np.exp(-x**2) * jn(0, r*x) * x def intensity(r): output = np.zeros_like(r) for i, ri in enumerate(r.flat): output.flat[i] = quad(lambda x: integrand(x, ri), 0, 5)[0] return output rho = np.linspace(0, 1.25, 50) p = np.linspace(0, 2*np.pi, 50) R, P = np.meshgrid(rho, p) Z = intensity(R) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') X, Y = R*np.cos(P), R*np.sin(P) surf = ax.plot_surface(X, Y, Z, cmap=plt.cm.YlGnBu_r)
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/comment/84926355
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48959284
type: Comment
has text: Thank you! This is the most primitive way i can find, but I do not know if it is as efficient as using `np`. @Ron Norris

http://stackoverflow.com/comment/84691627
score: 0
comment on: http://stackoverflow.com/q/48841927
type: Comment
type: QuestionComment
has text: in terminal type python

http://stackoverflow.com/q/48863493
downvote count: 3
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84730128
score: -3
tagged with: python
has title: How do I replace one of the JSON object value with another value in python?
type: AnsweredQuestion
upvote count: 0
has body: JSON String message = '{ "messageId": "Sending Sensor Data", "deviceId": "", "eventTemplateId": "", "Latitude": 12.874, "Longtide": 56.257, "Registration": "", "Battery": 100, "Idle": 0, "Occupied": "1" }' Random no generator occupied = random.randrange(1, 101, 2) I need to replace the "Occupied": "1" into "Occupied": with occupied string. Solutions Tried: message = '{ "messageId": "Sending Sensor Data", "deviceId": "", "eventTemplateId": "", "Latitude": 12.874, "Longtide": 56.257, "Registration": "", "Battery": 100, "Idle": 0, "Occupied": "%s" }'.format(occupied) Am I missing something here? I am clueless to identify. Sorry being stupid and I am new to python lang Thanks, Ram
type: Question
has comment: http://stackoverflow.com/comment/84730161
has comment: http://stackoverflow.com/comment/84730197
has answer: http://stackoverflow.com/a/48863583
accepted answer: http://stackoverflow.com/a/48863583

http://stackoverflow.com/comment/84911183
comment on: http://stackoverflow.com/q/48952175
score: 0
type: Comment
type: QuestionComment
has text: the Class command uses subprocess, a process of running a command and getting the output and return code

http://stackoverflow.com/comment/84672646
has text: Yes, feather (also look at parquet) are good choices, less certain about the metadata situation with them
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48832824

http://stackoverflow.com/a/48912901
has comment: http://stackoverflow.com/comment/84874542
has body: You cannot access the docstring as an attribute of the class (because the class object doesn't exist yet), but you can grab it directly, like a local variable: class Foo: 'This is a class.' a = __doc__ This sets the value of a as one would expect: &gt;&gt;&gt; Foo.a 'This is a class.' However, I haven't been able to find any information about this behavior in the official documentation. It's unclear if being able to access __doc__ like this is an official feature or a mere implementation detail. If you want to make absolutely sure that your code doesn't rely on what's possibly an implementation detail, you can manually assign to __doc__ like so: class Foo: a = __doc__ = 'This is a class.' It's a little ugly, but it's guaranteed to work.
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48910337
has comment: http://stackoverflow.com/comment/84874461
score: 1
accepted answer of: http://stackoverflow.com/q/48910337
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84932670
has text: One of the error was that I closed the BAM before I went through the iterator, but still not working after that. Edited the code anew.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48956490
type: QuestionComment

http://stackoverflow.com/q/48833610
has comment: http://stackoverflow.com/comment/84679163
tagged with: curl
answer count: 0
type: UnansweredQuestion
tagged with: facebook
tagged with: python
has body: I'm a complete beginner in both of Python and APIs things, I was trying to create a chatbot using Python using simple text response,the problem is I'm trying to use the FB documentation but it uses cURL and PHP "I think" so how can I use the documenation code for example : https://developers.facebook.com/docs/messenger-platform/reference/template/button the code in this link to fit in my code in Python here is an example of my simple response which already works if data['object'] == 'page': for entry in data['entry']: for messaging_event in entry['messaging']: # IDs sender_id = messaging_event['sender']['id'] recipient_id = messaging_event['recipient']['id'] if messaging_event.get('message'): # Extracting text message if 'text' in messaging_event['message']: messaging_text = messaging_event['message']['text'] else: messaging_text = 'no text' # Echo response = None entity, value = wit_reponse(messaging_text) if entity == 'schedule': response = "Ok I will send you {} news".format(str(value)) elif entity == "location": response = "Ok so you live in {0}. I will send you top headlines from {0}".format(str(value)) if response == None: response = "You know that I'm a bot at the end,I didn't understand :(" bot.send_text_message(sender_id, response)
has title: Using fb Messenger API in Python
has comment: http://stackoverflow.com/comment/84671752
type: Question
score: 0
tagged with: chatbot

http://stackoverflow.com/a/48810684
has body: Let's assume the filename for your original script is testfile.py Make another file in the same directory as the first one with this code: import time,os while 1: time.sleep(1800) os.system("start python testfile.py") Running this script will run your other file every 30 minutes regardless of how long the script takes to run!
has comment: http://stackoverflow.com/comment/84625136
answers question: http://stackoverflow.com/q/48810440
has comment: http://stackoverflow.com/comment/123872649
score: 0
has comment: http://stackoverflow.com/comment/84624985
has comment: http://stackoverflow.com/comment/84625304
type: Answer

http://stackoverflow.com/comment/84908549
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48950800
score: 0
has text: I suspect that they just don't want you to post data. If you rewrite your script as a get it will 200. However if you are trying to use their search, you need to do more than just post. :)

http://stackoverflow.com/comment/84835719
type: QuestionComment
comment on: http://stackoverflow.com/q/48912845
has text: Just a few things which are missing from your question but which have lots of impact how you design such a system: performance requirements, concurrency requirements, amount of data exchange, any kind of authentication or authorization, caching ....
score: 0
type: Comment

http://stackoverflow.com/a/48812681
has comment: http://stackoverflow.com/comment/84658206
type: Answer
has comment: http://stackoverflow.com/comment/84658151
has comment: http://stackoverflow.com/comment/84656742
score: 1
answers question: http://stackoverflow.com/q/48812441
has body: One way is to use np.logical_or.reduce. Here is an example: import pandas as pd, numpy as np df = pd.DataFrame([['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['G', 'A', 'D', 'I'], ['L', 'K', 'A', 'J'], ['S', 'T', 'U', 'V']], columns=['COL1', 'COL2', 'COL3' ,'COL4']) df[~np.logical_or.reduce([df[col].astype(str).str.contains('A') for col in df])] # COL1 COL2 COL3 COL4 # 1 E F G H # 4 S T U V
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48812441
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84667467

http://stackoverflow.com/q/48809799
accepted answer: http://stackoverflow.com/a/48810568
has title: Compare list with data with a list in a python dataframe column
possible better answer: http://stackoverflow.com/a/48810827
tagged with: python
type: AnsweredQuestion
tagged with: compression
tagged with: dataframe
type: Question
has comment: http://stackoverflow.com/comment/84623102
answer count: 2
has answer: http://stackoverflow.com/a/48810827
score: 0
linked to: http://stackoverflow.com/q/6750240
tagged with: pandas
tagged with: regex
has body: I'm a graduate student and working wit python to prepare my data set for my research. I'm not that confident with the use of python, so I would really appreciate your Help. Continuing on a previous asked question (how to do re.compile() with a list in python) I would like to apply this kind of word recognition one column in a dataframe. import pandas as pd from itertools import compress fruits = ['apple', 'banana', 'cherry'] df = pd.DataFrame({"a":['green apple and red cherry', 'blue', 'apple, banana and cherry', 'banana banana split'],"b":[0,2,0,1]}, index = [1,2,3,4]) # Create a list to store the data grades = [] grades = list(compress(fruits, (f in df.a for f in fruits))) df['grades'] = pd.Series(grades) This doesn't work out, since a data frame is generated where all 'grade-values' are NaN. Additionally, I would like to know if this is also possible with a list of sentences, instead of a list of words. And how this could be done. Thank you in advance!
has answer: http://stackoverflow.com/a/48810568

http://stackoverflow.com/a/48921916
score: 2
downvote count: 0
type: Answer
upvote count: 2
has body: Not ideal: text_to_grab = response.xpath('//span[@class="navigation-pipe"]/following-sibling::text()[1]').extract_first()
answers question: http://stackoverflow.com/q/48919935

http://stackoverflow.com/comment/84854735
has text: did you try `self.collection.drop()` or `db.drop_collection(settings['MONGODB_COLLECTION'])` @徐博俊
comment on: http://stackoverflow.com/a/48923771
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/q/48925659
has title: How to download available Windows binaries with pip, and source for all else
type: Question
score: 5
upvote count: 5
answer count: 1
accepted answer: http://stackoverflow.com/a/48925926
downvote count: 0
favorite count: 0
tagged with: pip
tagged with: python
has body: I have to administrate two separate Python setups, one on a Linux Machine with internet connection, and one offline Windows machine. For a given set of required packages, I would like to download the necessary files on the Linux machine, transfer them to the Windows machine and install them there. The following works as expected: pip3 download virtualenv --platform win_amd64 -d py_packages_20180222/ --only-binary=:all: The file virtualenv-15.1.0-py2.py3-none-any.whl is downloaded to the desired location, and ready for transfer. However, if pip doesn't find a binary file, it produces an error: pip3 download ipython --platform win_amd64 -d py_packages_20180222/ --only-binary=:all: Could not find a version that satisfies the requirement simplegeneric&gt;0.8 (from ipython) (from versions: ) No matching distribution found for simplegeneric&gt;0.8 (from ipython) This is the expected output due to the setting --only-binary=:all:, however it is not my desired output. In such a case, I would like pip to download the source code instead (with a warning) and continue. I'm essentially looking for the pip option --only-binary=:if_available:. Does this exist? EDIT: No, it doesn't. Thanks to the accepted answer, I was able to find my solution in using the following bash script: #!/usr/bin/env python3 import subprocess pkges = ['virtualenv', 'ipython'] for pkg in pkges: cmd = ['pip3', 'download', pkg, '--platform', 'win_amd64', '-d py_packages_20180222/', '--only-binary=:all:'] result = subprocess.run(cmd) if result.returncode != 0: print("No binary found for pkg. Downlaoding source code instead") cmdalt = ['pip3', 'download', pkg, '-d py_packages_20180222/'] subprocess.run(cmdalt)
has answer: http://stackoverflow.com/a/48925926
has comment: http://stackoverflow.com/comment/103520610
type: AnsweredQuestion

http://stackoverflow.com/a/58802140
answers question: http://stackoverflow.com/q/48895054
score: 1
has body: One good solution, that I currently implement in one of my systems, if you would like your session to automatically renew on each request would be to write middleware that alters the expiration of the session to be extended in whichever views you need. Note: this solution does make 2 DB queries for each request. 1 for the read and 1 for the update. This is a very small overhead (using debug toolbar at most the calls are usually only a few MS), but it is there. For example: from functools import wraps from [project] import settings class CookieMiddleware(object): """ This middleware sets the login cookie to update timeout on every request """ def __init__(self, get_response): self.get_response = get_response @staticmethod def process_view(request, view_func, args, kwargs): # ensure that we don't want to exclude this from running if getattr(view_func, 'cookie_not_important', False): print('cookie not important:', view_func.__name__) return None # the cookie is set, let's now set a new expire time to 30 minutes from now print('cookie expiry changed:', view_func.__name__) # it is probably smartest to grab this value back from settings expire_time = settings.SESSION_COOKIE_AGE # expire_time = 30 * 60 request.session.set_expiry(expire_time) return view_func(request, *args, **kwargs) def __call__(self, request): response = self.get_response(request) return response def cookie_not_important(view_func): """ Decorator used to allow the exclusion of the cookie time being reset :param view_func: The view being wrapped :return: """ def view_being_wrapped(*args, **kwargs): return view_func(*args, **kwargs) view_being_wrapped.cookie_not_important = True return wraps(view_func)(view_being_wrapped) And now you can login and hit any view not wrapped by @cookie_not_important and the expiration time will reset based on the current value in settings.py This is how the view would look wrapped though for completeness: from django.urls import reverse @cookie_not_important def logout(reques…
downvote count: 0
type: Answer
upvote count: 1

http://stackoverflow.com/comment/84833568
comment on: http://stackoverflow.com/a/48912881
type: Comment
score: 0
type: AnswerComment
has text: I feel like the groupby method should work, and it should be able to be manipulated via apply to get our results

http://stackoverflow.com/a/48846888
has comment: http://stackoverflow.com/comment/84841066
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84837551
accepted answer of: http://stackoverflow.com/q/48846786
has comment: http://stackoverflow.com/comment/84884728
has comment: http://stackoverflow.com/comment/84883214
answers question: http://stackoverflow.com/q/48846786
type: Answer
has comment: http://stackoverflow.com/comment/84756042
score: 1
has comment: http://stackoverflow.com/comment/84839795
has body: Use a Kivy property: from kivy.properties import StringProperty class (YourClass): text_variable_1 = StringProperty() When you reference this property in kv, and its value changes, the gui will automatically update. If you don't use a property this doesn't happen because the kv code has no way to know the value changed. Also, you don't have to follow pep8, but the property name should start with a lower case letter - it probably doesn't matter for your example, but can matter in kv if you try to set the property there.
upvote count: 1
has comment: http://stackoverflow.com/comment/84749512
has comment: http://stackoverflow.com/comment/84883028
has comment: http://stackoverflow.com/comment/84836800
has comment: http://stackoverflow.com/comment/84839927
has comment: http://stackoverflow.com/comment/84757513

http://stackoverflow.com/comment/84695962
score: 0
has text: You are right, I changed it to except Exception as e: and I am getting the error Session is closed. Why would it be closed when I use it in the Class, and not closed when it is not used inside of the Class?
comment on: http://stackoverflow.com/q/48845731
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48910956
has title: Pandas `agg` to list, "AttributeError / ValueError: Function does not reduce"
accepted answer: http://stackoverflow.com/a/48917824
tagged with: python
linked to: http://stackoverflow.com/q/45928415
has comment: http://stackoverflow.com/comment/84829277
has comment: http://stackoverflow.com/comment/84829098
has comment: http://stackoverflow.com/comment/84828742
tagged with: group-by
has comment: http://stackoverflow.com/comment/84828637
has answer: http://stackoverflow.com/a/48917824
tagged with: pandas-groupby
tagged with: pandas
score: 2
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84842688
downvote count: 0
answer count: 1
favorite count: 0
type: Question
upvote count: 2
has body: Often when we perform groupby operations using pandas we may wish to apply several functions across multiple series. groupby.agg seems the natural way to perform these groupings and calculations. However, there seems to be discrepancy between how groupby.agg and groupby.apply are implemented, because I cannot group to a list using agg. Tuple and set works fine, which suggests to me you can only aggregate to immutable types via agg. Via groupby.apply, I can aggregate one series to a list directly with no issues. Below is a complete example. Functions (1), (2), (3) complete successfully. (4) comes back with # ValueError: Function does not reduce. import pandas as pd df = pd.DataFrame([['Bob', '1/1/18', 'AType', 'blah', 'test', 'test2'], ['Bob', '1/1/18', 'AType', 'blah2', 'test', 'test3'], ['Bob', '1/1/18', 'BType', 'blah', 'test', 'test2']], columns=['NAME', 'DATE', 'TYPE', 'VALUE A', 'VALUE B', 'VALUE C']) def grouper(df, func): f = {'VALUE A': lambda x: func(x), 'VALUE B': 'last', 'VALUE C': 'last'} return df.groupby(['NAME', 'DATE', 'TYPE'])['VALUE A', 'VALUE B', 'VALUE C']\ .agg(f).reset_index() # (1) SUCCESS grouper(df, set) # (2) SUCCESS grouper(df, tuple) # (3) SUCCESS df.groupby(['NAME', 'DATE', 'TYPE', 'VALUE B', 'VALUE C'])['VALUE A']\ .apply(list).reset_index() # (4) FAIL grouper(df, list) # AttributeError # ValueError: Function does not reduce

http://stackoverflow.com/comment/84930046
has text: Why don't you use teacher_id as primary key? And what is the point of `TeacherData`? Seems to duplicate the fields in `Teacher`
type: QuestionComment
comment on: http://stackoverflow.com/q/48960764
score: 0
type: Comment

http://stackoverflow.com/comment/84656690
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48826287
has text: Make sure you enabled the messages correctly: https://docs.djangoproject.com/en/2.0/ref/contrib/messages/#enabling-messages including adding the message module to INSTALLED_APPS

http://stackoverflow.com/q/48940274
downvote count: 2
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84888873
favorite count: 0
accepted answer: http://stackoverflow.com/a/48941358
has answer: http://stackoverflow.com/a/48941358
has body: I'm new in python. Want to login on my account My code is: driver = webdriver.Firefox() session = requests.Session() url = "http://tterminal.info/" response = session.post(url) # &lt;div class="auth"&gt; authForm = driver.find_element_by_class_name("auth") # &lt;div class="login"&gt; loginForm = authForm.find_element_by_class_name("login") # Enter login login = loginForm.find_element_by_name("login") login.clear() login.send_keys("mylogin") # Enter pass pswd = loginForm.find_element_by_name("pass") pswd.send_keys("mypassword") # Click login loginForm.find_element_by_class_name("submit").click() But it givesme Unable to find element .auth Where is my wrong?
tagged with: python
tagged with: selenium-webdriver
type: AnsweredQuestion
tagged with: selenium
score: -1
type: Question
has title: python - Authorization selenium

http://stackoverflow.com/q/48872554
tagged with: matplotlib
linked to: http://stackoverflow.com/q/19198920
has body: I am trying to plot a bar graph where the x-axis represents the first element of each tuple and the y-axis is the second element of each tuple. Something very similar to this post: Using Counter() in Python to build histogram? arr = [(0, 152), (1, 106), (2, 71), (3, 89), (4, 69), (5, 83), (6, 139), (7, 141), (8, 164), (9, 75), (10, 98)] How can I do this? I have this so far: Input: plt.bar(counts.items()) Output: TypeError: &lt;lambda&gt;() takes at least 2 arguments (1 given) Thanks :)
upvote count: 0
answer count: 1
favorite count: 0
tagged with: tuples
has comment: http://stackoverflow.com/comment/84748989
tagged with: python
linked to: http://stackoverflow.com/q/18458734
tagged with: list
has answer: http://stackoverflow.com/a/48872661
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/84749191
duplicate of: http://stackoverflow.com/q/18458734
has title: how to plot a list with tuples
type: Question
score: -2

http://stackoverflow.com/comment/84907000
type: AnswerComment
comment on: http://stackoverflow.com/a/48950240
type: Comment
has text: That is a straight forward solution. Thanks. What is the right keyword for this technique (so that I can further read up on this)?
score: 0

vb6
type: Tag
tag name: vb6
tags question: http://stackoverflow.com/q/48875458

http://stackoverflow.com/a/48980855
has comment: http://stackoverflow.com/comment/86097823
score: 0
type: Answer
has body: Which line of your code gives you this error? Look at error trace Let's start with your iterators: it is declared as i, but then you use j. Then check length of your request. It shouldn't be longer than 5k symbols according to JSONDecodeError using Google Translate API with Python3. Anyway, it looks like api responds with empty json and you have to add at least try .. except to avoid this error, smth like this: try: word = translator.translate(str(keywords[j])).text except JSONDecodeError as err: print(err) # if you want to see when error happens else: Translate.append(word)
answers question: http://stackoverflow.com/q/48957624

http://stackoverflow.com/q/48948745
has comment: http://stackoverflow.com/comment/84904437
has body: I am trying to instanciate a object i created witch is a subclass of pygame.sprite.Sprite. This is the code i use to instanciate it: import pygame as pg from GameObject import GameObject player = GameObject("Sprites/Player", 6) And this is the code for the object itself: import pygame as pg class GameObject(pg.sprite.Sprite): def __ini__(self, image_path, number_of_images): for i in range(number_of_images): self.images.append(pg.image.load("{}/sprite{}.png".format(image_path, i))) When i try to run it i get this: Traceback (most recent call last): File "main.py", line 11, in &lt;module&gt; player = GameObject("Sprites/Player", 6) File "/usr/lib/python3.6/site-packages/pygame/sprite.py", line 124, in __init__ self.add(*groups) File "/usr/lib/python3.6/site-packages/pygame/sprite.py", line 142, in add self.add(*group) File "/usr/lib/python3.6/site-packages/pygame/sprite.py", line 142, in add self.add(*group) File "/usr/lib/python3.6/site-packages/pygame/sprite.py", line 142, in add self.add(*group) [Previous line repeated 327 more times] RecursionError: maximum recursion depth exceeded I have looked at sever example codes for creating a subclass of this class but i do not see the difference between my code and others. What am i missing out on?
has answer: http://stackoverflow.com/a/63860825
type: UnansweredQuestion
tagged with: sprite
type: Question
tagged with: recursion
has title: Maximum recursion depth exceeded when creating subclass of pygame.sprite.Sprite
has comment: http://stackoverflow.com/comment/84903776
has comment: http://stackoverflow.com/comment/84904260
score: 0
has comment: http://stackoverflow.com/comment/84904791
answer count: 1
has comment: http://stackoverflow.com/comment/84904483
has comment: http://stackoverflow.com/comment/84903991
tagged with: subclass
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/84903840

http://stackoverflow.com/comment/125849853
type: Comment
score: 2
type: AnswerComment
comment on: http://stackoverflow.com/a/52229694
has text: Thank you for a great explanation. Btw, the result of `view` is `contiguous`. In contrast, the result of `permute` or `transpose` is **not** contiguous. For example, even if we call `.view` many times with different shapes, it works fine without using the `contiguous()` method. But if we permute or transpose first, and then try to `view`, then an error occurs, because `view` only works on the "contiguous" tensor(we need to use `.contiguous()` before `view` to create a contiguous tensor, by creating a new, rearranged underlying storage).

http://stackoverflow.com/a/48957298
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48957252
has body: Side Note In your case there is no newline in text. Probably you wanted to define text = """hello what are you doing with yourself this weekend?""" Answer You don't need a regular expression. Just use text.count("\n")~ Edit: Oh, nevermind. You need it to be a regex? len(re.findall("\n", text)) should work
score: 2
answers question: http://stackoverflow.com/q/48957252

fiona
tags question: http://stackoverflow.com/q/48821050
tag name: fiona
type: Tag

http://stackoverflow.com/q/48828470
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/84660824
type: AnsweredQuestion
tagged with: root
downvote count: 0
tagged with: selenium
has answer: http://stackoverflow.com/a/48907339
accepted answer: http://stackoverflow.com/a/48907339
type: Question
score: 4
has title: How to run selenium chromedriver as root? (not working even with --no-sandbox
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84697522
has body: I'm trying to run chromedriver to create some selenium tests. I followed this manual to install it. I'm trying to run this code: from selenium import webdriver driver = webdriver.Chrome(chrome_options=options) When I call this python script as normal user, it's working. But when I call it as root (it is necessary for me), it's not working. I've tried to follow some advices and I was trying to use several Google chrome options, e.g.: from selenium import webdriver from selenium.webdriver.chrome.options import Options options = Options() options.add_argument('--no-sandbox') driver = webdriver.Chrome(chrome_options=options, service_args=[ '--verbose', '--log-path=/home/me/Projects/selenium.log' ] ) But it's still not working and here is a part of log: [1,001][INFO]: COMMAND InitSession { "capabilities": { "alwaysMatch": { "browserName": "chrome", "goog:chromeOptions": { "args": [ "--no-sandbox" ], "extensions": [ ] }, "platformName": "any" }, "firstMatch": [ { } ] }, "desiredCapabilities": { "browserName": "chrome", "goog:chromeOptions": { "args": [ "--no-sandbox" ], "extensions": [ ] }, "platform": "ANY", "version": "" } } [1,001][INFO]: Populating Preferences file: { "alternate_error_pages": { "enabled": false }, "autofill": { "enabled": false }, "browser": { "check_default_browser": false }, "distribution": { "import_bookmarks": false, "import_history": false, "import_search_engine": false, "make_chrome_default_for_user": false, "show_welcome_page": false, "skip_first_run_ui": true }, "dns_prefetching": { "enabled": false }, "profile": { "content_settings": { "pattern_pairs": { "https://*,*": { "media-stream": { "audio": "Default", "video": "Default" } } } }, "default_content_setting_values": { "geolocation": 1 }, "default_content_settings": { "geolocation": 1, "mouselock": 1, "notifications": 1, "popups": 1, "ppapi-broker": 1 }, "password_manager_enabled": false }, "safebrowsing": { "enabled": false }, "search": { "suggest_enabled": false }, "translate": { "enabled…
has comment: http://stackoverflow.com/comment/84664430

http://stackoverflow.com/q/48935736
type: Question
has title: Cannot import widget from IPython.html.widgets in Jupyter notebook
has answer: http://stackoverflow.com/a/48935839
answer count: 1
downvote count: 0
tagged with: jupyter
tagged with: jupyter-notebook
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: ipywidgets
has body: I am using Jupyter to run my code. from Ipython.html.widgets import interact, ButtonWidget from IPython.display import display, clear_output I am not getting the following error for that: ModuleNotFoundError Traceback (most recent call last) &lt;ipython-input-6-3fa9b991f293&gt; in &lt;module&gt;() ----&gt; 1 from IPython.html.widgets import interact, ButtonWidget 2 from IPython.display import display, clear_output ModuleNotFoundError: No module named 'widgets' I tried to replace IPython.html.widgets to ipywidgets and execute it. It threw me back: from ipywidgets import interact, ButtonWidget ImportError: cannot import name ButtonWidget"

http://stackoverflow.com/a/48807210
answers question: http://stackoverflow.com/q/48804859
has comment: http://stackoverflow.com/comment/84617185
type: Answer
has comment: http://stackoverflow.com/comment/84617442
has comment: http://stackoverflow.com/comment/84617381
has body: IIUC: Use pd.DataFrame.align with a join method of inner. Then pass the resulting tuple unpacked to pd.DataFrame.eq pd.DataFrame.eq(*df.align(dfo, 'inner')) a b c 0 False False False 1 False False False 2 False False False 3 False False False 4 False False True To see rows that have all columns True, filter with this mask: pd.DataFrame.eq(*df.align(dfo, 'inner')).all(1) 0 False 1 False 2 False 3 False 4 False dtype: bool with the sample data however, the result will be empty df[pd.DataFrame.eq(*df.align(dfo, 'inner')).all(1)] Empty DataFrame Columns: [a, b, c] Index: [] Same answer but with clearer code def eq(d1, d2): d1, d2 = d1.align(d2, 'inner') return d1 == d2 eq(df, dfo) a b c 0 False False False 1 False False False 2 False False False 3 False False False 4 False False True
score: 0

http://stackoverflow.com/q/48837384
type: Question
has body: I want to create this tuple: a=(1,1,1),(2,2,2),(3,3,3),(4,4,4),(5,5,5),(6,6,6),(7,7,7),(8,8,8),(9,9,9) I tried with this a=1,1,1 for i in range (2,10): a=a,(i,i,i) However it creates a tuple inside other tuple in each iteration. Thank you
tagged with: for-loop
has answer: http://stackoverflow.com/a/48837471
answer count: 6
tagged with: tuples
has answer: http://stackoverflow.com/a/48838316
has answer: http://stackoverflow.com/a/58972922
has comment: http://stackoverflow.com/comment/84681312
downvote count: 1
upvote count: 17
has answer: http://stackoverflow.com/a/48837461
duplicate of: http://stackoverflow.com/q/75666408
favorite count: 0
linked to: http://stackoverflow.com/q/75666408
tagged with: python
has title: How to create tuple with a loop in python
has answer: http://stackoverflow.com/a/48837443
duplicate of: http://stackoverflow.com/q/252703
accepted answer: http://stackoverflow.com/a/48837443
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48837442
has comment: http://stackoverflow.com/comment/84679614
possible better answer: http://stackoverflow.com/a/48837471
score: 16

http://stackoverflow.com/a/48964410
answers question: http://stackoverflow.com/q/48959098
score: 209
type: AcceptedAnswer
downvote count: 0
has body: Looks like you forgot the mode parameter when calling open, try w: with open("copy.txt", "w") as file: file.write("Your text goes here") The default value is r and will fail if the file does not exist 'r' open for reading (default) 'w' open for writing, truncating the file first Other interesting options are 'x' open for exclusive creation, failing if the file already exists 'a' open for writing, appending to the end of the file if it exists See Doc for Python 2.7 or Python 3.6
upvote count: 209
type: Answer
accepted answer of: http://stackoverflow.com/q/48959098

http://stackoverflow.com/comment/84632860
comment on: http://stackoverflow.com/q/48814572
type: QuestionComment
has text: Functions are first class citizens. You can assign them to variables if you want, but you would need e.g. `a = print` not `a = print()`. The latter usage assigns a function *call* to `a`, which isn't what you want.
type: Comment
score: 1

http://stackoverflow.com/comment/84841784
score: 0
type: Comment
has text: I was trying to avoid creating new strings, as this seems important, but you're right, I've often used that very approach.
comment on: http://stackoverflow.com/a/48917536
type: AnswerComment

http://stackoverflow.com/comment/84753727
comment on: http://stackoverflow.com/q/48874072
type: Comment
type: QuestionComment
has text: In `tkinter`, `Canvas` line objects have an `arrowhead` option that you might be able to use. Here's some [documentation](http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/create_line.html).
score: 1

http://stackoverflow.com/q/48836604
tagged with: conventions
tagged with: git-submodules
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/44732819
type: Question
possible better answer: http://stackoverflow.com/a/48837525
has answer: http://stackoverflow.com/a/48837525
score: 18
linked to: http://stackoverflow.com/q/59895
answer count: 2
tagged with: python-import
has answer: http://stackoverflow.com/a/48836605
favorite count: 0
accepted answer: http://stackoverflow.com/a/48836605
has title: Avoiding pylint complaints when importing Python packages from submodules
upvote count: 18
tagged with: pylint
has body: Background I have a Python application dependent upon another package which is provided as a git submodule, yielding a directory structure similar to the following: foo/ bar/ bar/ __init__.py eggs.py test/ setup.py foo/ __init__.py ham.py main.py Accessing the foo package is simple enough, as main.py is executed from the toplevel foo/ directory; but the bar package is nested within another bar directory and is not directly importable. This is solvable readily enough, by modifying sys.path at the beginning of main.py: import sys # Or sys.path.append() sys.path.insert(0, './bar') from bar.eggs import Eggs from foo.ham import Ham (Note: this code example assumes that main.py will always be invoked from foo/; in cases where this may not be the case, '.bar' could be replaced with os.path.join(os.path.dirname(__file__), 'bar') though this is clearly more unwieldy.) The Problem Unfortunately, pylint doesn't like this solution. While the code works, the linter considers the sys.path modifications to be a block of code ending the "top of the module" and gives an undesirable wrong-import-position warning: C: 6, 0: Import "from bar.eggs import Eggs" should be placed at the top of the module (wrong-import-position) C: 7, 0: Import "from foo.ham import Ham" should be placed at the top of the module (wrong-import-position) Similar questions Adding a path to sys.path in python and pylint This questioner has an issue with pylint failing to correctly parse the imports altogether. The lone answer to the this question suggests adding to pylint's internal path; this does nothing to avoid complaints about an interleaved sys.path modification.
tagged with: python

http://stackoverflow.com/comment/84695580
has text: Yes, that's because your request is being rejected. You could try again after a while, or use an `if match:` to let you know that it's not working.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48845736

http://stackoverflow.com/q/48912638
favorite count: 0
accepted answer: http://stackoverflow.com/a/50450343
type: Question
tagged with: nose2
answer count: 2
upvote count: 7
has title: How to configure pycharm to use nose2 instead of nose
has answer: http://stackoverflow.com/a/50450343
tagged with: python
has answer: http://stackoverflow.com/a/48913065
tagged with: pycharm
downvote count: 0
has body: According to the http://nose.readthedocs.io/en/latest all tests ... should consider using Nose2, py.test, or just plain unittest/unittest2. However, I can't seem to make Pycharm use it instead of nose. Is there some setting I can configure so that it uses nose2 to do its testing instead of nose? EDIT: Nose2 is included in my Project Interpreter's list of packages However, I can't run any tests (which is why I asked this question)
possible better answer: http://stackoverflow.com/a/48913065
type: AnsweredQuestion
score: 7

http://stackoverflow.com/q/48940739
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/48940765
has answer: http://stackoverflow.com/a/48940788
upvote count: 3
possible better answer: http://stackoverflow.com/a/48940788
tagged with: excel
type: AnsweredQuestion
score: 3
accepted answer: http://stackoverflow.com/a/48940765
has answer: http://stackoverflow.com/a/48940783
has title: Converting Year into 12/31/xxxx Format in Python
type: Question
has body: I have a list of years stored in a Pandas.DataFrame (column=df[0]) that looks like this: 0 1939 1 1977 2 1965 3 1982 4 1997 5 1956 What's the easiest method to convert these dates into 12/31/xxxx format where "xxxx" is equal to the year? I need it converted into that format for Excel to recognize the numbers as dates. Note: I found a quick hack for this in Excel using find and replace, but would like to know how to do this in Python, as well.
downvote count: 0
favorite count: 0
answer count: 3
tagged with: pandas

http://stackoverflow.com/q/48836082
tagged with: flask
tagged with: flask-sqlalchemy
has comment: http://stackoverflow.com/comment/84677158
favorite count: 0
has answer: http://stackoverflow.com/a/48838818
tagged with: python
has title: How would I convert this JSON so that I can add it to a MySQL database using Flask-SQLAlchemy?
accepted answer: http://stackoverflow.com/a/48838271
type: Question
type: AnsweredQuestion
has body: JSON {"users": [{"username": "userxyz", "id": 4, "email": "xyz@gmail.com", "events": [{"event_name": "vday"}, {"event_name": "bday"}]}]} DB class User(db.Model): id= db.Column(db.Integer, primary_key=True) username= db.Column(db.String(80), unique=True, nullable=False) email= db.Column(db.String(120), unique=True, nullable=False) events= db.relationship('Event', backref='user') class Event(db.Model): id = db.Column(db.Integer, primary_key=True) event_name = db.Column(db.String(200), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id')) Schemas class UserSchema(ma.ModelSchema): events = fields.Nested('EventSchema', many=True) class Meta: model = User class EventSchema(ma.ModelSchema): class Meta: model = Event exclude = ('id', 'user_id', 'user')
possible better answer: http://stackoverflow.com/a/48838818
score: 1
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/48838271
tagged with: mysql
answer count: 2
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/84689541
has text: `.annotate(total_quantity=Sum('quantity'),total_buy_price=Sum("quantity*open_price"))` somthing like that? Or is there another way, since it doesnt work
type: Comment
comment on: http://stackoverflow.com/a/48842615
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84805974
score: 0
comment on: http://stackoverflow.com/q/48897342
type: Comment
type: QuestionComment
has text: so how to change the default set?

http://stackoverflow.com/comment/84808322
score: 0
has text: Yes, you can do that. Check the edit. `my_str.replace(' ', '\n')` will take care of that.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48897556

http://stackoverflow.com/a/48835454
has body: No need for apply which is a loop. Consider directly assigning column using the vectorized Series.str method. Also, you can use regex in str.replace to extract all numbers and commas and avoid the long chaining. test['res1'] = test['result'].str.replace("c\(", "")\ .str.replace("\)","").str.replace("\"","")\ .str.replace(" ","").str.split(",") test['res2'] = test['result'].str.replace(r'[^0-9,]', '').str.split(",") print(test) # day name result res1 res2 # 0 2018-01-01 john c("7", "6", "") [7, 6, ] [7, 6, ] # 1 2018-01-02 jack c("3", "6", "10") [3, 6, 10] [3, 6, 10] # 2 2018-01-03 albert c("4", "3", "") [4, 3, ] [4, 3, ]
answers question: http://stackoverflow.com/q/48835158
has comment: http://stackoverflow.com/comment/84679763
downvote count: 0
upvote count: 2
has comment: http://stackoverflow.com/comment/84678017
type: Answer
score: 2

variables
tag name: variables
tags question: http://stackoverflow.com/q/48945173
tags question: http://stackoverflow.com/q/48910561
tags question: http://stackoverflow.com/q/48919024
tags question: http://stackoverflow.com/q/48846735
tags question: http://stackoverflow.com/q/48864407
tags question: http://stackoverflow.com/q/48951248
tags question: http://stackoverflow.com/q/48844846
tags question: http://stackoverflow.com/q/48940537
type: Tag
tags question: http://stackoverflow.com/q/48898359
tags question: http://stackoverflow.com/q/48954479
tags question: http://stackoverflow.com/q/48836746
tags question: http://stackoverflow.com/q/48807953
tags question: http://stackoverflow.com/q/48923931
tags question: http://stackoverflow.com/q/48956904
tags question: http://stackoverflow.com/q/48820118
tags question: http://stackoverflow.com/q/48891791
tags question: http://stackoverflow.com/q/48861824
tags question: http://stackoverflow.com/q/48848888

http://stackoverflow.com/comment/90853218
has text: how aboult making SessionRunHook to store the loss?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48940155

http://stackoverflow.com/a/48835059
type: Answer
accepted answer of: http://stackoverflow.com/q/48834972
upvote count: 1
score: 1
has body: Suppose you have all your *_case_words.txt in the present dir import glob in_file = glob.glob('*_case_words.txt') prefix = [i.split('_')[0] for i in in_file] for i, ifile in enumerate(in_file): data = [] with open(ifile, 'r') as f: for line in f: data.append(line) with open(prefix[i] + '_case_sentence.txt' , 'w') as f: f.write(data)
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48834972

http://stackoverflow.com/q/48872145
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84752824
has body: I have previously used the following to ensure my figure-size in my plots is a consistent size: import matplotlib as mpl rc_fonts = {'figure.figsize': (15, 9.3)} mpl.rcParams.update(rc_fonts) import matplotlib.pylab as plt However, I am now finding that for my usual default values (15, 9.3) this is being ignored. The following demonstrates this: import matplotlib as mpl rc_fonts = {'figure.figsize': (15, 9.3)} mpl.rcParams.update(rc_fonts) import matplotlib.pylab as plt # I draw some boring plot. plt.clf() plt.plot(*[range(10)]*2) print plt.gcf().get_size_inches() print mpl.rcParams['figure.figsize'] plt.gcf().set_size_inches(15, 9.3, forward=True) print plt.gcf().get_size_inches() The initial plot size is [10.35, 9.3] and after it is [15, 9.3] as desired. If however I make the default very much large or smaller, e.g. (32, 19.3) then the figure window is correctly sized. I would like to keep my desired route of changing rcParams to set the default, rather than trying to set it twice by making an interim dummy plot. Is this a bug, or am I going about this the wrong way? Details: Python 2.7.12 (inside a virtual environment, a must). Backend TkAgg (I want this kept as it is). Matplotlib version 2.1.0. (This bug/feature persists in version 2.1.2 also). PS - I prefer avoiding having to make matplotlib fig and ax objects and instead use the plt interface directly. If possible I would like to keep it this way with any solutions. Possible known issue: I have found the following issue 2716 on github which I think is causing this, but there don't appear any fixes suitable for the rcParam settings route. So any help or suggestions are still welcome. Current output: Following the comments below is some example output (done using Python 3 to allow me to install the latest version of matplotlib): Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux &gt;&gt;&gt; ... import matplotlib as mpl ... print(mpl.__version__) ... rc_fonts = {'figure.figsize': (15, 9.…
has comment: http://stackoverflow.com/comment/84752484
has comment: http://stackoverflow.com/comment/84752675
has comment: http://stackoverflow.com/comment/84752750
has answer: http://stackoverflow.com/a/48929239
has comment: http://stackoverflow.com/comment/84751677
accepted answer: http://stackoverflow.com/a/48929239
favorite count: 0
upvote count: 1
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84753184
score: 1
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84752481
has title: Matplotlib Figuresize being ignored by rcParams
has comment: http://stackoverflow.com/comment/84749119
type: Question
has comment: http://stackoverflow.com/comment/84751128
has comment: http://stackoverflow.com/comment/84767860

http://stackoverflow.com/a/48818843
has comment: http://stackoverflow.com/comment/84641912
score: 0
type: Answer
has body: You should point all related field exactly, like: class UsersResource(resources.ModelResource): class Meta: model = User fields = ('id', 'name', 'email', 'telephone', 'userRequest__date', 'userRequest__problem') @admin.register(User) class UserAdmin(ImportExportModelAdmin): resource_class = UsersResource search_fields = ('name', 'surname', 'email', 'telephone') And so on
has comment: http://stackoverflow.com/comment/84642086
has comment: http://stackoverflow.com/comment/84642169
answers question: http://stackoverflow.com/q/48817433
has comment: http://stackoverflow.com/comment/84641794
has comment: http://stackoverflow.com/comment/84641825
has comment: http://stackoverflow.com/comment/84641892

http://stackoverflow.com/comment/84758840
has text: you're asking us to debug code that you haven't posted....
comment on: http://stackoverflow.com/q/48877266
type: Comment
score: 1
type: QuestionComment

http://stackoverflow.com/q/48819905
score: 1
has body: I'm trying to display what the user types onto the screen as a preview and when they left click with the mouse, it blits the text onto the screen. from pygame import * init() screen = display.set_mode((640, 480)) clock = time.Clock() running = True font = font.SysFont("comicsansms", 72) # Default font textC = "a" # Stores user input text = font.render(textC, True, (255,0,0)) # Render Text while running: mx, my = mouse.get_pos() mb = mouse.get_pressed() for e in event.get(): if e.type == QUIT: running = False if e.type == KEYDOWN: print(textC) if key.get_pressed()[K_BACKSPACE]: textC = textC[:-1] # removes last letter else: textC += e.unicode # adds letter screen.fill((255, 255, 255)) #fill screen white screen.blit(text, (mx, my)) # display text display.flip() clock.tick(60) quit()
type: Question
answer count: 2
upvote count: 1
has comment: http://stackoverflow.com/comment/84654322
favorite count: 0
has title: Preview keyboard input and blit text on mouse click pygame
accepted answer: http://stackoverflow.com/a/48821479
linked to: http://stackoverflow.com/q/48770344
tagged with: python
possible better answer: http://stackoverflow.com/a/48821258
tagged with: pygame
has answer: http://stackoverflow.com/a/48821258
has answer: http://stackoverflow.com/a/48821479
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/q/48944437
has body: Hello i am trying to save the dataframe in .h5 file but while i am providing command to do that, it fails saying that file is opening in read only mode and file does not exist. table.to_hdf('test.h5', key= 'csdkc', mode='w') I looked for question on stack over but nothing looked relevant.
has title: HDF5 :pandas: error opening file in read only mode while mode used is 'w'
score: 0
has answer: http://stackoverflow.com/a/48944761
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/84897349
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84895988
tagged with: python
has comment: http://stackoverflow.com/comment/84895533
has comment: http://stackoverflow.com/comment/84895615
tagged with: hdf5
type: Question

regex-greedy
tags question: http://stackoverflow.com/q/48902627
type: Tag
tag name: regex-greedy

http://stackoverflow.com/q/48945682
has answer: http://stackoverflow.com/a/77342008
has title: Basemap interpolation alternative - regridding data
tagged with: matplotlib
upvote count: 2
answer count: 3
possible better answer: http://stackoverflow.com/a/48946713
tagged with: matplotlib-basemap
has answer: http://stackoverflow.com/a/48951919
accepted answer: http://stackoverflow.com/a/48951919
favorite count: 0
tagged with: python
tagged with: interpolation
type: AnsweredQuestion
score: 2
downvote count: 0
has answer: http://stackoverflow.com/a/48946713
has body: I'm moving from basemap to cartopy given basemap is going to be phased out. I've previously used the basemap.interp functionality to interpolate data, e.g. say I have data at 1 degree resolution (180x360), I would run the following to interpolate to 0.5 degrees. import numpy as np from mpl_toolkits import basemap Old_Lon = np.linspace(-180,180,360) Old_Lat = np.linspace(-90,90,180) New_Lon = np.linspace(-180,180,720) New_Lat = np.linspace(-90,90,360) New_Lon,New_Lat = np.meshgrid(New_Lon,New_Lat) New_Data = basemap.interp(Old_Data,Old_Lon,Old_Lat,New_Lon,New_Lat,order=0) order gives me options to choose from nearest neighbour, bi-linear etc. Is there an alternative that does this in as simple way? I've seen scipy has interpolation but I'm not sure how to apply it. Any help would be appreciated!
type: Question
tagged with: numpy

http://stackoverflow.com/comment/84680955
comment on: http://stackoverflow.com/q/48838086
type: QuestionComment
type: Comment
has text: Yes, but it doesn't say "successfully opened CUDA library" in the shell, as it does in the tutorial. Is that okay? Thanks.
score: 0

http://stackoverflow.com/a/48919490
type: AcceptedAnswer
has body: So it turns out that I didn't provide enough context to answer this question. The serializer I was testing inherited from another serializer, so instead of manually constructing all the fields in the test, I pulled in the fields from the base serializer, and then updated that data with the additional expected content like so: base_serializer = BaseFooSerializer(foo) additional = { 'more': 'attributes', 'of': 'foos', } expected = base_serializer.data.copy() expected.update(additional) assert foo_serializer.data == expected Because DRF serializers don't return a standard Python dictionary, I think the comparison was going wonky. To fix it, I made the following correction: expected = dict(base_serializer.data.items()) And now it works fine.
answers question: http://stackoverflow.com/q/48895975
has comment: http://stackoverflow.com/comment/85003026
type: Answer
accepted answer of: http://stackoverflow.com/q/48895975
score: 0

http://stackoverflow.com/a/48870891
upvote count: 13
has comment: http://stackoverflow.com/comment/84748860
has comment: http://stackoverflow.com/comment/84747669
has body: With combination of re.findall() (using specific regex patten) and max() functions: import re # extended sample string s = 'asdfewfUBAUBAUBAUBAUBAasdkjnfencsADADADAD sometext' def find_longest_rep(s): result = max(re.findall(r'((\w+?)\2+)', s), key=lambda t: len(t[0])) return result[0] print(find_longest_rep(s)) The output: UBAUBAUBAUBAUBA The crucial pattern: ((\w+?)\2+): (....) - the outermost captured group which is the 1st captured group (\w+?) - any non-whitespace character sequence enclosed into the 2nd captured group; +? - quantifier, matches between one and unlimited times, as few times as possible, expanding as needed \2+ - matches the same text as most recently matched by the 2nd capturing group
has comment: http://stackoverflow.com/comment/84747528
has comment: http://stackoverflow.com/comment/84781587
has comment: http://stackoverflow.com/comment/84764459
type: Answer
has comment: http://stackoverflow.com/comment/84790548
has comment: http://stackoverflow.com/comment/84780284
downvote count: 0
score: 13
answers question: http://stackoverflow.com/q/48870253
has comment: http://stackoverflow.com/comment/84764282

http://stackoverflow.com/comment/84781871
type: Comment
type: QuestionComment
has text: I have many error while running your code : items instead of item, DF.loc[DF.index == str(year)] ... Please could you share a runnable code so I can test and find what's wrong ?
score: 0
comment on: http://stackoverflow.com/q/48886348

http://stackoverflow.com/comment/84830072
comment on: http://stackoverflow.com/a/48891486
score: 0
has text: You have a function called `get_credentials`. In your view you call `get_credentials`, then call `credentials.authorize(Http())`. So if the function `get_credentials` returns an object that does not define the method `authorize`, you'll get the error you describe. Inside `get_credentials`, you return either the `credentials` object you got from the storage, which presumably does define that method, if the credentials exist and they're valid, but if the credentials don't exist, you return an HttpResponseRedirect object, which does not define that method.
type: AnswerComment
type: Comment

cmd
tags question: http://stackoverflow.com/q/48849044
tags question: http://stackoverflow.com/q/48825279
type: Tag
tags question: http://stackoverflow.com/q/48878203
tags question: http://stackoverflow.com/q/48921714
tags question: http://stackoverflow.com/q/48910820
tags question: http://stackoverflow.com/q/48921300
tags question: http://stackoverflow.com/q/48898264
tags question: http://stackoverflow.com/q/48933470
tags question: http://stackoverflow.com/q/48960633
tags question: http://stackoverflow.com/q/48879108
tag name: cmd

http://stackoverflow.com/q/48961283
favorite count: 0
tagged with: python
has body: I'm using a single VL53L0X on the Raspberry Pi 3 in a python2.7. Normally (in the physical set-up) it measures in this loop an infinitive(end of detecting range) distance. When a physical object appears in the line of sight of the VL53L0X, the main software loop detects a (correct) distance change and triggers another process. During some duration tests, I noticed that when its running this loop for a few hours and only detecting end-of-range it; it might come into a situation that an object appearing in the line of sight is not detected anymore. (the VL53L0X keeps detecting end-of-range). This is also the case with the provided VL53L0X_example.py Attempts so far: 1. Replacing the VL53L0X and/or Raspberry Pi does not have any effect. 2. A (sheduled) re-init by performing tof.stop_ranging() followed by tof.start_ranging.(VL53L0X.VL53L0X_BETTER_ACCURACY_MODE) does not help. A software reboot of the complete Raspberry Pi does not help either. 3. Only a complete mains power-plug down and up seems to work. My question: Is there a way in Python to prevent this situation or a Python command to force the VL53L0X to re-initialize or power down and up?
answer count: 0
type: UnansweredQuestion
tagged with: i2c
upvote count: 1
type: Question
has title: VL53L0X failing in duration test when sensing end-of-range for a while
has comment: http://stackoverflow.com/comment/86762921
downvote count: 0
tagged with: raspberry-pi3
score: 1

http://stackoverflow.com/comment/84769317
type: Comment
type: QuestionComment
has text: `datetime.datetime.now() - datetime.datetime.now()` returns `datetime.timedelta(0)`. I can think of an explanation... how slow is your machine? I'd bet you can't reproduce it every time you want.
comment on: http://stackoverflow.com/q/48882468
score: 1

http://stackoverflow.com/q/48932059
upvote count: 1
type: Question
has body: let's say I have the following pandas dataframe called example: city state school_lvl schl_name elem_name middle_name highschoo_name Orlando fl 1 Union Park Union Park Orlando fl 2 Legacy Legacy Orlando fl 3 Colonial Colonial where columns like elem_name were generated using if conditions on school_lvl and schl_name what I would like instead is city state elem_name middle_name highschoo_name Orlando fl Union Park Legacy Colonial How would I go about doing this? It's not really a groupie since there is no aggregate function? I'd greatly appreciate any help
tagged with: group-by
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: grouping duplicates and combining the string columns via Pandas
score: 1
has answer: http://stackoverflow.com/a/48932102

http://stackoverflow.com/q/48934520
answer count: 0
tagged with: string
type: UnansweredQuestion
tagged with: levenshtein-distance
type: Question
has comment: http://stackoverflow.com/comment/84875698
has title: Using Hamming distance to group a list of DNA sequences into similar sequences (Python)?
has comment: http://stackoverflow.com/comment/84878090
tagged with: python
tagged with: string-matching
score: 0
tagged with: hamming-distance
has body: I've extracted a list of DNA sequences from a FASTQ file and its currently being stored in a list for now. sequences = ['ATCT','ATTT','ACGG','ACCG','ACGT','AGGT','ATGC','ATCC','AGTT'] I want to cluster sequences into a list of tuples so that each sequence within the tuple are similar to each other. I initially considered using Hamming Distance (code shown below) for clustering similar sequences together but if I understand Hamming distance correctly, I would have to use a one of the sequences as a reference to compare Hamming distance against another sequence and depending on what my reference sequence is, I would end up with different clusters (e.g.: if I use 'ACGG' as my reference sequence and compare it to other sequences in the list, 'ACCG' and 'ACGT' would be clustered with 'ACGG' if I chose a Hamming distance of 1 as my criteria. Conversely, if I use 'ACCG' as my reference sequence, 'ACGG' would get clustered with it but not 'ACGT' since 'ACGT' has a hamming distance of 2 when compared with 'ACCG'.) def hamming_dist(sequence1, sequence2): assert len(sequence1) == len(sequence2) return sum(sequence1 !=sequence2 for sequence1,sequence2 in itertools.izip(sequence1,sequence2)) With the drawback of using Hamming distance, I've considered using Levenshtein ratio (from the Levenshtein module) or Fuzzywuzzy ratio (from the Fuzzywuzzy module) to cluster the sequences. What are the advantages/disadvantages of each method and how should I set up my code to cluster similar sequences together?

http://stackoverflow.com/comment/93684895
has text: To make variables global, you have to type the following code, not define them outside of a function. `global hi, name, isTrue`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48864478
type: Comment

http://stackoverflow.com/comment/84835568
score: 0
type: Comment
has text: @bwrabbit yw/~ :-) happy coding
comment on: http://stackoverflow.com/a/48914154
type: AnswerComment

http://stackoverflow.com/a/48808421
downvote count: 1
type: Answer
has body: I think you need to put an hold somwere there: ... fig = plt.figure() ax1 = fig.add_subplot(111) ax2 = ax1.twiny() ax1.plot(GetTestData()) hold(True) ax2.plot(range(100), np.ones(100)) # Create a dummy plot ax2.cla()
answers question: http://stackoverflow.com/q/48808320
score: 0
upvote count: 1

http://stackoverflow.com/q/48898359
has comment: http://stackoverflow.com/comment/84802211
tagged with: declare
score: 0
tagged with: variables
duplicate of: http://stackoverflow.com/q/1373164
type: UnansweredQuestion
has body: I'm a beginner of python and I have a question I defined a function named testfunc like below def testfunc(num) : result = num ** 2 return result This is just for test so I made very simple function And I want to declare many variables. x1 = testfunc(1) x2 = testfunc(2) x3 = testfunc(3) like this.. If there are a little variables, I can write all of them. But how about in case of many variables? (about 1000 or 100000) Is there any good way to declare many variables using loop?
linked to: http://stackoverflow.com/q/1373164
tagged with: python
has title: How to declare many variables in same time in python?
answer count: 0
has comment: http://stackoverflow.com/comment/84802196
type: Question
has comment: http://stackoverflow.com/comment/84802104

http://stackoverflow.com/a/48933133
type: AcceptedAnswer
score: 0
type: Answer
has body: You can add drop_duplicates first: print(test['date_col'].drop_duplicates().nlargest(2)) 16 2018-03-01 1 2018-02-01 Name: date_col, dtype: datetime64[ns] Alternative solution: print(test['date_col'].drop_duplicates().sort_values(ascending=False).head(2)) 16 2018-03-01 1 2018-02-01 Name: date_col, dtype: datetime64[ns]
has comment: http://stackoverflow.com/comment/84873039
accepted answer of: http://stackoverflow.com/q/48933119
has comment: http://stackoverflow.com/comment/84873170
answers question: http://stackoverflow.com/q/48933119

http://stackoverflow.com/q/48950626
tagged with: optimization
answer count: 1
downvote count: 0
favorite count: 0
has body: I have an Excel file with items and descriptions and I'm trying to compare descriptions for similarity, and if they're similar, put them in a new Excel file. Those items also have Catalog #'s and I'm comparing them to see if they're nothing like each other and they're from the same vendor (buy_line) put them also on the new Excel file. When I run the file, it takes way too long and after I leave it running, I come back and Spyder is closed and no new file. So this is a 2 part question, is there a way to make the code faster? and why is there no file created? Thank you in advance. My code is below `import xlrd import xlsxwriter from fuzzywuzzy import fuzz AllItems = xlrd.open_workbook('2-18All_Items-CleanUp.xlsx','rb') sheets = AllItems.sheet_names() item = [] base = [] kit = [] buy_line = [] catalogs = [] descriptions = [] similar_desc_item = [] similar_desc = [] diff_catalog_samebuyline = [] sh = AllItems.sheet_by_index(0) def readexcelfunc(): for rownum in range(sh.nrows): row_values = sh.row_values(rownum) item.append((row_values[0])) base.append((row_values[1])) kit.append((row_values[2])) buy_line.append((row_values[6])) catalogs.append((row_values[8])) descriptions.append((row_values[12])) def check_similar_desc(): for i,k in enumerate(descriptions): for j,l in enumerate(descriptions): ratio1 = fuzz.token_sort_ratio(k,l) if ratio1 &gt; 95 and k != l and base[i] != base[j] and kit[i] == "No": similar_desc_item.append(item[i]) def check_notmatching_catalog(): for x,a in enumerate(catalogs): for y,b in enumerate(catalogs): ratio2 = fuzz.token_sort_ratio(a,b) if ratio2 &lt; 10 and buy_line[x] == buy_line[y]: diff_catalog_samebuyline.append(catalogs[x]) def Create_ExcelFile(): NewWorkbook = xlsxwriter.Workbook('Sim_Desc.xlsx') worksheet = NewWorkbook.add_worksheet() row1 = 0 row2 = 0 for items in similar_desc_item: worksheet.write(row1,0,items) row1 += 1 for catalognumb in diff_catalog_samebuyline: worksheet.write(row2,3,catalognumb) NewWorkbook.save() NewWorkbook.…
has answer: http://stackoverflow.com/a/48951525
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84908861
score: 1
tagged with: xlsxwriter
has comment: http://stackoverflow.com/comment/84907867
upvote count: 1
tagged with: excel
type: Question
has title: Python Not Creating Excel File with xlsxwriter
accepted answer: http://stackoverflow.com/a/48951525

http://stackoverflow.com/q/48809100
accepted answer: http://stackoverflow.com/a/48809219
answer count: 1
downvote count: 0
has body: So I was trying to set up the search view for a model. But I think I am doing something wrong. Maybe I pass arguments wrong ? def search(request): query = request.GET.get('q') if query: results = Course.objects.filter(Q(name__icontains=query)) else: results = Course.objects.all() context = { 'results': results, } return render(request, 'courses/index.html', context)
score: 1
favorite count: 0
tagged with: django
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84622214
has answer: http://stackoverflow.com/a/48809219
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84622569
has title: Django search not showing results

http://stackoverflow.com/comment/84925968
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48959662
has text: @SaherAhwal not minimum element, but some specified item
score: 0

http://stackoverflow.com/a/48849992
type: AcceptedAnswer
has body: from Why should you use an ORM? Making data access more abstract and portable. ORM implementation classes know how to write vendor-specific SQL, so you don't have to. (Bill Karwin)
has comment: http://stackoverflow.com/comment/89174491
accepted answer of: http://stackoverflow.com/q/48845022
type: Answer
answers question: http://stackoverflow.com/q/48845022
downvote count: 1
score: 1
has comment: http://stackoverflow.com/comment/84715666
upvote count: 2
has comment: http://stackoverflow.com/comment/84722410
has comment: http://stackoverflow.com/comment/84712000

http://stackoverflow.com/comment/84857204
comment on: http://stackoverflow.com/q/48925238
has text: Welcome to Stack Overflow. However, asking for a package or library is explicitly off-topic for this site. Instead, describe the problem and [what has been done so far](https://meta.stackoverflow.com/questions/254393/what-exactly-is-a-recommendation-question) to solve it. Check the [FAQ](http://stackoverflow.com/tour) and [How to Ask](http://stackoverflow.com/help/how-to-ask).
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48907951
tagged with: python-telegram-bot
type: UnansweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/84821950
tagged with: python
has comment: http://stackoverflow.com/comment/84821830
answer count: 4
has title: Python Telegram Api. How to pick a random image from directory?
has answer: http://stackoverflow.com/a/48908089
has answer: http://stackoverflow.com/a/48908050
has body: I figure out how to pick a specific picture in a directory. bot.send_photo(chat_id=chat_id, photo=open('/Users/Iamawesome/Desktop/test/599d6f972525a.jpg', 'rb')) But how can I pick a random picture? Thank you. UPDATE I figure out a little bit, but i still don't handle any messages or errors @BOT.message_handler(commands=['photo']) def send_rand_photo(message): photo = random.choice([ x for x in os.listdir(PATH) if os.path.isfile(os.path.join(PATH, x)) ]) with open (photo, "rb") as file: BOT.send_photo(message.chat.id, file)
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48921281
score: -1
tagged with: telegram-bot
has answer: http://stackoverflow.com/a/56971594
favorite count: 0

http://stackoverflow.com/q/48912989
has answer: http://stackoverflow.com/a/48913242
tagged with: dataframe
has answer: http://stackoverflow.com/a/48913117
type: Question
has title: Pandas doesn't remove separator
answer count: 2
possible better answer: http://stackoverflow.com/a/48913117
accepted answer: http://stackoverflow.com/a/48913242
score: 0
has body: I have dataset -> data.txt: 4 x x1, x2, x3, x4, x5, x6, x7, x8 6 y y1, y2, y3, y4, y5, y6, y7 9 z z1, z2 That's my code to import this data: df = pd.read_csv('data/xyz.txt', sep=',', names=range(20), delim_whitespace=True) df.dropna(axis=1, how='all', inplace=True) It looks nice but there is problem with 'comma'. df.head() 0 1 2 3 4 5 6 7 8 9 0 4 x x1, x2, x3, x4, x5, x6, x7, x8 1 6 y y1, y2, y3, y4, y5, y6, y7 NaN 2 9 z z1, z2 NaN NaN NaN NaN NaN NaN My goal is remove all commas from all values. I can't do it from hand this is big data. I don't want do it by nested loop over every value.
tagged with: pandas
tagged with: python
has comment: http://stackoverflow.com/comment/84832443
has comment: http://stackoverflow.com/comment/84832354
type: AnsweredQuestion

http://stackoverflow.com/comment/84797580
type: Comment
type: QuestionComment
has text: Are you using tensorflow without adding the very relevant tensorflow-tag (while spamming *sample* which does not help at all)? Also: a more complete (best-case: reproducable) code would be nice.
comment on: http://stackoverflow.com/q/48895892
score: 0

http://stackoverflow.com/a/48855458
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48855413
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48855413
has body: You forgot to change the string input to integer. See the below code snippet : import random print ('min =') MIN = int(input()) print ('max =') MAX = int(input()) print (random.randrange(MIN, MAX)) Also your code might not gonna run if minimum is greater than maximum. So better handle it.
type: Answer

http://stackoverflow.com/comment/137471466
has text: @NoamPeled `--no-builds` allows using different package builds in the new env. This can be useful when working on different OS'es where the same package builds are almost never available, but I don't see the point when the users are on the same OS?
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48871834
type: Comment

http://stackoverflow.com/comment/84807659
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48900923
score: 0
has text: you can use potgresql `\copy my_table to 'filename' csv header` for exporting your table data to csv file

integer
tags question: http://stackoverflow.com/q/48883738
tags question: http://stackoverflow.com/q/48941783
tag name: integer
tags question: http://stackoverflow.com/q/48892414
type: Tag

http://stackoverflow.com/a/48836179
has body: You should create a custom view for the 404 then to use it. for example: in views.py: from django.http import HttpResponseNotFound import json def error404(request, exception): response_data = {} response_data['detail'] = 'Not found.' return HttpResponseNotFound(json.dumps(response_data), content_type="application/json") then in urls.py: from django.conf.urls import handler404 from yourapp.views import error404 handler404 = error404
answers question: http://stackoverflow.com/q/48835946
upvote count: 2
has comment: http://stackoverflow.com/comment/84716658
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84678840
has comment: http://stackoverflow.com/comment/84677412
type: Answer
has comment: http://stackoverflow.com/comment/107006199
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84677664
accepted answer of: http://stackoverflow.com/q/48835946

http://stackoverflow.com/q/48931380
linked to: http://stackoverflow.com/q/5656798
has comment: http://stackoverflow.com/comment/84871193
linked to: http://stackoverflow.com/q/17952279
score: 0
has comment: http://stackoverflow.com/comment/84897401
has comment: http://stackoverflow.com/comment/84897671
has comment: http://stackoverflow.com/comment/84971851
has comment: http://stackoverflow.com/comment/84910259
duplicate of: http://stackoverflow.com/q/5656798
upvote count: 1
downvote count: 1
duplicate of: http://stackoverflow.com/q/17952279
favorite count: 0
has comment: http://stackoverflow.com/comment/84869537
has comment: http://stackoverflow.com/comment/84909702
has comment: http://stackoverflow.com/comment/84869963
has body: I am scratching my head in confusion as I am trying to give better aesthetics to the following plot. import random my_randoms = [random.randint(0,50) for p in range(600)] my_randoms += [random.randint(50,1000) for p in range(300)] bins = range(0, 1000, 50) plt.hist(my_randoms, bins) plt.xticks(bins)`enter code here` plt.yticks(range(0, 500, 50)) plt.grid() plt.show() The problem is that i want to set the y axis tick in an non equal way e.g 0, 10,20, 30, 40, 50, 500 but with the same size and no breaking axes. UPDATE An awesome drawing of what I have in my mind.NO breaking axis. UPDATE 2 Well the log-ed transformed values gave the following result. bins = [math.log10(x) for x in range(0, 1000, 50)] plt.hist(prideG, bins) plt.xticks(bins) plt.grid() plt.show() On the x axis are the log-ed values of 0-1000 with a step of 50.
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84893523
tagged with: python
duplicate of: http://stackoverflow.com/q/28077499
has comment: http://stackoverflow.com/comment/84870978
linked to: http://stackoverflow.com/q/45306099
has title: Matplotlib Plot with equal ticks but not proportional
answer count: 0
has comment: http://stackoverflow.com/comment/84871425
tagged with: matplotlib
has comment: http://stackoverflow.com/comment/84910202
has comment: http://stackoverflow.com/comment/84871728
type: Question
has comment: http://stackoverflow.com/comment/84871422
has comment: http://stackoverflow.com/comment/84869871
has comment: http://stackoverflow.com/comment/84871215
has comment: http://stackoverflow.com/comment/84909042
has comment: http://stackoverflow.com/comment/84870449
has comment: http://stackoverflow.com/comment/84908196
tagged with: histogram

http://stackoverflow.com/q/48855413
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48855458
possible better answer: http://stackoverflow.com/a/48855739
answer count: 2
downvote count: 4
tagged with: random
upvote count: 0
has title: How can i use the random function with variables?
tagged with: python
has answer: http://stackoverflow.com/a/48855739
favorite count: 0
has body: I want creating a random number generator which allows to define the min and max. How can i fix this code : import random print ('min =') MIN = input() print ('max =') MAX = input() print (random.randrange(MIN, MAX))
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48855458
score: -4
has comment: http://stackoverflow.com/comment/84714298
type: Question

http://stackoverflow.com/a/49254380
has comment: http://stackoverflow.com/comment/85565473
type: Answer
upvote count: 0
score: -1
has body: Use extra_columns argument to the table constructor. extra_columns (str, Column) – list of (name, column)-tuples containing extra columns to add to the instance. This will make sure a copy is made of Table.base_columns before the extra columns are added to the table instance.
downvote count: 1
answers question: http://stackoverflow.com/q/48932983

http://stackoverflow.com/q/48860824
answer count: 2
has title: how to manually give weight to features using python in machine learning
tagged with: decision-tree
score: 0
tagged with: python
tagged with: jupyter-notebook
has body: I have a data set with continuous label ranging from one to five with nine different features. So I wanted to give weight to each feature manually because some of the features have very less dependency on the label so I wanted to give more weight to those features which have more dependency on the label. How can I manually give weight to each feature? Will it be possible to give weight like this? I went through different documentations I can only find how to give weight to the label. What I only find is eliminating features ranking features etc. But I wanted to give weight to each feature manually also I wanted to tune these weights (Sometimes the feature weight will be different for different scenario so I wanted to tune the weight according to that) Will it be possible ?
has answer: http://stackoverflow.com/a/48877243
type: UnansweredQuestion
tagged with: regression
has answer: http://stackoverflow.com/a/48877568
type: Question

http://stackoverflow.com/q/48959969
favorite count: 0
type: UnansweredQuestion
downvote count: 2
tagged with: python
tagged with: regex
upvote count: 1
has body: I have an excel file that I am trying to extract information from, specifically from the 5th column ('Summary'). Each element of 'Summary' is a string; I am trying to find the age of the person mentioned. The age info will either be "John Smith, 23," or "John Smith, a 23-year-old". The first row of data isn't valid, so I skipped it. I can't figure out what I am doing wrong. I am searching for 2 digits followed by either a comma or a dash, then trying to return the 2 digits. Thanks for the help import pandas as pd mf=pd.ExcelFile(myFile) m=mf.parse('myDataFile') age = [] s = m['Summary'] for a in s[1:]: x = re.search('[0-9]{2}',a) y=x+1 age.append(a[x,y])
type: Question
has comment: http://stackoverflow.com/comment/84927480
tagged with: dataframe
score: -1
has title: Python regular expression applied to list
has answer: http://stackoverflow.com/a/48967257
answer count: 1
has comment: http://stackoverflow.com/comment/84926492

http://stackoverflow.com/q/48854393
tagged with: python
downvote count: 2
has comment: http://stackoverflow.com/comment/84712203
has answer: http://stackoverflow.com/a/48854432
upvote count: 1
type: Question
score: -1
has title: Error in assignment: 'int' object is not subscriptable
tagged with: int
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84712526
type: UnansweredQuestion
has body: I am writing code for an assignment based on given pseudocode, but I keep getting this error message: 'int' object is not subscriptable I'm not sure what it means or where I went wrong even after searching what the error means. My assignment: In a class with students n &gt;= 2, a bully is a student who is afraid of no one in the class but every other person in the class is afraid of the bully. You are asked to determine if there is a bully in a class. In your task, you are allowed to consider any pair of students (i, j) and ask student i if they are afraid of student j. Although you are allowed to ask as many (possibly intersecting) pairs of students as you wish, your objective is to minimize the number of such questions you need to ask, since the interrogation process can be rather traumatic for bullied students. Assume that all students are truthful when asked. We will represent the class as an n-by-n matrix A, where the entry A[i][j] is 1 if student i is afraid of student j and 0 otherwise. We will set A[i][i] as 0. Note: "student is afraid of student" does not imply that student is a bully. Given pseudocode: find_bully_2(A): initialise C as the list of all students candidate = find_candidate(C, A) if candidate is None: return None if everyone is afraid of candidate and candidate is afraid of no one: return candidate as bully else: return None -- find_candidate(C, A): if C has only one entry: return that entry else: pairs = len(C) // 2 newC = [] # a list containing possible bullies for i in range(pairs): if first person in pair i is afraid of second person: add second person to newC else: add first person to newC if there are an odd number of students in C: add last student to newC return find_candidate(newC, A) What I wrote so far: def find_bully_2(A): C = list(range(len(A))) candidate = find_candidate(C, A) if candidate == None: return None for i in range(n): for j in range(n): if A[i][candidate] == 1 and A[candidate][j] == 0: return candidate else: return None…

http://stackoverflow.com/q/48887674
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48887727
has comment: http://stackoverflow.com/comment/84780761
has comment: http://stackoverflow.com/comment/84780525
has comment: http://stackoverflow.com/comment/84780181
score: 0
accepted answer: http://stackoverflow.com/a/48887727
possible better answer: http://stackoverflow.com/a/48887839
tagged with: python
has answer: http://stackoverflow.com/a/48887839
tagged with: dictionary
tagged with: nlp
answer count: 4
has title: Convert a string to keys of a given dictionary in python
has body: Is there a way to transform a string into the keys of a given dictionary in python? Here's an example. I have a dictionary and a string dict = {0:'this', 1:'is', 2:'a', 3:'sentence', 4:'another'} sentence = 'this is a sentence. this is another' And I would like to use the dictionary to convert this string into something like this: [0, 1, 2, 3, 0, 1, 4] Is there a simpler way than a nested loop through the words of the sentence and the items of the dictionary? Thanks
has answer: http://stackoverflow.com/a/48888015
has answer: http://stackoverflow.com/a/48888112
type: Question

http://stackoverflow.com/q/48951973
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has title: How can i simplify this using only once math.tan()?
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84910530
score: -1
has answer: http://stackoverflow.com/a/48952039
has comment: http://stackoverflow.com/comment/84910616
upvote count: 2
downvote count: 3
has answer: http://stackoverflow.com/a/48952056
has body: How can I simplify this so I only use math.tan() once? def someTan(x): return math.tan(x) / (1 - math.tan(x)**2)
has comment: http://stackoverflow.com/comment/84910587
favorite count: 0

http://stackoverflow.com/q/48807413
upvote count: 1
has comment: http://stackoverflow.com/comment/84644547
type: Question
has body: I need to pass variable through jinja2 to base html template. If requesting python function test happens by URl - then everything is working okay. But I do need to request pyton function send_user_login_status each time when URL is changed. In this case it does not work. How can I achieve python function send_user_login_status executes every time when user changes URL and passing variable through jinja2 to .html file. I am using flask. base.html &lt;li class="{{ login_status_class }}"&gt; {{ login_status }}&lt;/li&gt; test.html {% extends "base.html" %} Python function is working by URL correctly @app.route('/test') def test_api(): login_status_class = 'login' login_status = u'Enter' return render_template("base.html", login_status=login_status, login_status_class=login_status_class) Python function has to work each time when URL changes def send_user_login_status(): login_status_class = 'login' login_status = u'Enter' return render_template("base.html", login_status=login_status, login_status_class=login_status_class) EDIT 1 For example, I'm trying to call a function send_user_login_status when user goes to the home page. But nothing happens. @app.route('/') def home(): send_user_login_status() return render_template("index.html")
downvote count: 0
has title: Passing variable to base html template when url changes
favorite count: 0
has comment: http://stackoverflow.com/comment/84621570
type: UnansweredQuestion
tagged with: python
tagged with: jinja2
answer count: 0
score: 1

http://stackoverflow.com/comment/84656580
comment on: http://stackoverflow.com/a/48813053
score: 0
type: AnswerComment
has text: That returned an error: `('Can only use .str accessor with string values, which use np.object_ dtype in pandas', 'occurred at index AAA')`. Before using your line, I am grouping by and then I am using the following: `pd.merge(df, dfGrouped, how='inner', on='AAA', suffixes=(' ', '_grp'), copy=True)[varsToKeep]`
type: Comment

http://stackoverflow.com/comment/84765946
type: Comment
comment on: http://stackoverflow.com/a/48880284
has text: I fully agree with your solution and explanation, now you have added how you handle the case of "no common pair of key/value". Thanks for this completion.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84659256
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48814213
has text: I guess there isn't any satisfying answer beyond, "this is just the random thing that was committed for Python 3.6, since the devs consider this to essentially be undefined behavior." Thanks for linking the code change. I do think we should be careful about your line, "Python 3.4 didn't support truly reloading an extension module from a changed file..." The question is *not* about re-loading a dynamic extension when its source changed, rather it is just a question of why re-initialization is not *always* attempted, especially when the underlying module *did not* change.
type: AnswerComment

http://stackoverflow.com/comment/84669560
has text: @ncotton there's no need to call `sys.exit()`
type: QuestionComment
comment on: http://stackoverflow.com/q/48832559
score: 0
type: Comment

http://stackoverflow.com/q/48887007
has body: Im new to python (3) and would like to now the following: I'm trying to collect data via pandas from a website and would like to store the results into a mysql database like: import pandas as pd from sqlalchemy import create_engine engine = create_engine("mysql://python:"+'pw'+"@localhost/test?charset=utf8") url = r'http://www.boerse-frankfurt.de/devisen' dfs = pd.read_html(url,header=0,index_col=0,encoding="UTF-8") devisen = dfs[9] #Select the right table devisen.to_sql(name='table_fx', con=engine, if_exists='append', index=False) I'm receiving the following error: .... _mysql.connection.query(self, query) sqlalchemy.exc.OperationalError: (_mysql_exceptions.OperationalError) (1054, "Unknown column '\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tBezeichnung\n\t\t\t\t\t\t\t\n\t\t\t\t' in 'field list'") [SQL: 'INSERT INTO tbl_fx (\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tBezeichnung\n\t\t\t\t\t\t\t\n\t\t\t\t, \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tzum Vortag\n\t\t\t\t\t\t\t\n\t\t\t\t, \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tLetzter Stand\n\t\t\t\t\t\t\t\n\t\t\t\t, \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tTageshoch\n\t\t\t\t\t\t\t\n\t\t\t\t, \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tTagestief\n\t\t\t\t\t\t\t\n\t\t\t\t, \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t52-Wochenhoch\n\t\t\t\t\t\t\t\n\t\t\t\t, \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t52-Wochentief\n\t\t\t\t\t\t\t\n\t\t\t\t, \n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tDatum\n\t\t\t\t\t\t\t\n\t\t\t\t, \nAktionen\t\t\t\t) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)'] [parameters: (('VAE Dirham', '-0,5421%', 45321.0, 45512.0, 45306.0, 46080.0, 38550.0, '20.02.2018 14:29:00', None), ('Armenischer Dram', '-0,0403%', 5965339.0, 5970149.0, 5961011.0, 6043443.0, 5108265.0, '20.02.2018 01:12:00', None), .... How can sqlalchemy INSERT respective data into table_fx? Problem is the header with the multiple \n and \t. The mysql table hase the following structur: ( name varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, bezeichnung varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, diff_vortag varc…
answer count: 1
has answer: http://stackoverflow.com/a/48888459
accepted answer: http://stackoverflow.com/a/48888459
upvote count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84778889
has comment: http://stackoverflow.com/comment/84779630
has title: sqlalchemy: Insert html table into mysql db
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84781682
downvote count: 0
score: 1
tagged with: sqlalchemy
type: Question

http://stackoverflow.com/q/48908044
tagged with: ssl
has body: In the official doc of HTTP PROTOCOL CLIENT class http.client.HTTPSConnection(host, port=None, key_file=None, cert_file=None, [timeout, ]source_address=None, *, context=None, check_hostname=None) A subclass of HTTPConnection that uses SSL for communication with secure servers. Default port is 443. If context is specified, it must be a ssl.SSLContext instance describing the various SSL options. Is there any option to disable ssl verification like python requests library as verify=fasle For some reasons I can't use HTTPConnection class which would be a straight forward solution. I have to use HTTPSConnection and work with HTTPConnection.putrequest() to send request without the ssl verification.
has title: How to disable ssl verification for http.client.HTTPSConnection class in python?
has answer: http://stackoverflow.com/a/50949266
answer count: 1
tagged with: httpclient
upvote count: 16
favorite count: 0
tagged with: python
type: AnsweredQuestion
downvote count: 0
score: 16
type: Question
accepted answer: http://stackoverflow.com/a/50949266

http://stackoverflow.com/a/48894129
upvote count: 31
answers question: http://stackoverflow.com/q/48894060
type: Answer
has body: Python's dictionaries have no order, so indexing like you are suggesting (fruits[2]) makes no sense as you can't retrieve the second element of something that has no order. They are merely sets of key:value pairs. To retrieve the value at key: 'kiwi', simply do: fruit['kiwi']. This is the most fundamental way to access the value of a certain key. See the documentation for further clarification. And passing that into a print() call would actually give you an output: print(fruit['kiwi']) #2.0 Note how the 2.00 is reduced to 2.0, this is because superfluous zeroes are removed. Finally, if you want to use a for-loop (don't know why you would, they are significantly more inefficient in this case (O(n) vs O(1) for straight lookup)) then you can do the following: for k, v in fruit.items(): if k == 'kiwi': print(v) #2.0
score: 30
downvote count: 1

awk
tag name: awk
type: Tag
tags question: http://stackoverflow.com/q/48826469

http://stackoverflow.com/comment/84796401
type: Comment
has text: Alright by doing that it created File "U:/CISP253/Final/test", line 11, in <module> for row in readCSV: io.UnsupportedOperation: not readable
comment on: http://stackoverflow.com/a/48895047
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84824677
type: QuestionComment
comment on: http://stackoverflow.com/q/48890084
has text: @Felk I updated my answer, not sure the problem is with setup, to begin with. Also `Example1` needs its own `__init__.py` if it is to be a package.
score: 0
type: Comment

http://stackoverflow.com/comment/84624289
comment on: http://stackoverflow.com/a/48809765
score: 0
type: Comment
has text: @chetan I added some explanation to the answer
type: AnswerComment

http://stackoverflow.com/comment/84865639
score: 0
type: AnswerComment
has text: Using your file I get the data validation warning, but saving back to file with `wb.save(filename)` works for me. The version is the same, but I am using Linux. Try performing the same operations in an interactive Python terminal and see if that works. If it does then you will need to look at your code, perhaps the file is not being saved where you think it is?
type: Comment
comment on: http://stackoverflow.com/a/48925892

http://stackoverflow.com/comment/84801947
comment on: http://stackoverflow.com/q/48898216
score: 0
has text: i was converting the output from another program to string before writing out to file using file.write(str(field1)+str(field2)+str(field3))
type: Comment
type: QuestionComment

self-organizing-maps
tags question: http://stackoverflow.com/q/48902586
type: Tag
tag name: self-organizing-maps

http://stackoverflow.com/comment/84736897
type: Comment
type: QuestionComment
has text: You need to replace sample.xlsx with your custom name (in your custom dir). You can choose a custom name and dir with your modal window, and store those custom in your class attribute so you will be able to reuse it. i don't know if I'm clear, but I can't provide an example if I don't have a minimal code to run in local.
comment on: http://stackoverflow.com/q/48864655
score: 0

http://stackoverflow.com/comment/84922070
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48954847
score: 0
has text: @DebanjanB Thank you for that. I didn't know that. It's just for academic purposes

http://stackoverflow.com/comment/84723887
type: QuestionComment
score: 0
has text: Honestly I can't figure out what your question is here. Please edit to clarify.
comment on: http://stackoverflow.com/q/48860258
type: Comment

http://stackoverflow.com/q/48814529
tagged with: neural-network
favorite count: 0
accepted answer: http://stackoverflow.com/a/48814841
tagged with: perceptron
tagged with: python
has title: how to make pseudocode of perceptron in python?
downvote count: 1
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48814841
has body: This code was written in python 3, could you tell me what your pseudocode would look like? I can not understand the calculations that are being made: #dobro n * 2 # x * weight import random import numpy as np def derivada(n): return n*(1-n) x = 0.85 y = 0.25 w = random.random() #épocas for i in range(10): a=np.tanh(x*w) e = y-a#erro w+= x* derivada(e) print(a) I tried to do the pseudocode this way, but it's not working too well. algoritm "untitled" var er, n, f, x1, w1, w2, u, y : real b, yd, i : inteiro Begin b &lt;- 1 x1 &lt;- 1 w1 &lt;- 0 u &lt;- (x1*w1)+b y &lt;- tan(u) yd &lt;- 5 er &lt;- yd-y for i de 1 to 10 do n &lt;- 0.5 f &lt;- (n*x1*er) w1 &lt;- w1+f Write(w1) endfor // Commands End Can you tell me what's wrong?
score: -1
type: Question
upvote count: 0
answer count: 1

http://stackoverflow.com/a/48902281
downvote count: 0
has comment: http://stackoverflow.com/comment/84809992
has comment: http://stackoverflow.com/comment/84812250
has body: This is code developed on PyQt4 for detachable tab widget in PyQt. Hope this will help you. from PyQt4 import QtGui, QtCore from PyQt4.QtCore import pyqtSignal, pyqtSlot ## # The DetachableTabWidget adds additional functionality to Qt's QTabWidget that allows it # to detach and re-attach tabs. # # Additional Features: # Detach tabs by # dragging the tabs away from the tab bar # double clicking the tab # Re-attach tabs by # closing the detached tab's window # double clicking the detached tab's window frame # # Modified Features: # Re-ordering (moving) tabs by dragging was re-implemented # class DetachableTabWidget(QtGui.QTabWidget): def __init__(self, parent=None): QtGui.QTabWidget.__init__(self, parent) self.tabBar = self.TabBar(self) self.tabBar.onDetachTabSignal.connect(self.detachTab) self.tabBar.onMoveTabSignal.connect(self.moveTab) self.setTabBar(self.tabBar) ## # The default movable functionality of QTabWidget must remain disabled # so as not to conflict with the added features def setMovable(self, movable): pass ## # Move a tab from one position (index) to another # # @param fromIndex the original index location of the tab # @param toIndex the new index location of the tab @pyqtSlot(int, int) def moveTab(self, fromIndex, toIndex): widget = self.widget(fromIndex) icon = self.tabIcon(fromIndex) text = self.tabText(fromIndex) self.removeTab(fromIndex) self.insertTab(toIndex, widget, icon, text) self.setCurrentIndex(toIndex) ## # Detach the tab by removing it's contents and placing them in # a DetachedTab dialog # # @param index the index location of the tab to be detached # @param point the screen position for creating the new DetachedTab dialog @pyqtSlot(int, QtCore.QPoint) def detachTab(self, index, point): # Get the tab content name = self.tabText(index) icon = self.tabIcon(index) if icon.isNull(): icon = self.window().windowIcon() contentWidget = self.widget(index) contentWidgetRect = contentWidget.frameGeometry() # Create a new detached tab window detachedT…
has comment: http://stackoverflow.com/comment/84810920
answers question: http://stackoverflow.com/q/48901854
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48901854
has comment: http://stackoverflow.com/comment/84812491
has comment: http://stackoverflow.com/comment/84811964
has comment: http://stackoverflow.com/comment/84810130
upvote count: 2
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84810820

http://stackoverflow.com/q/48856754
type: Question
has body: Good morning, i'm trying to install a package on portable python. I found that i do not have the easy_install.exe file, I just have the easy_install.py file. I tried the following from prompt_CDOS: 1) C:\Software\Portable Python 3.2.5.1&gt;app\py thon.exe textract-1.6.1.tar\textract-1.6.1\setup.py Traceback (most recent call last): File "textract-1.6.1.tar\textract-1.6.1\setup.py", line 4, in &lt;module&gt; from setuptools import setup File "C:\Software\Portable Python 3.2.5. 1\app\lib\site-packages\setuptools\__init__.py", line 2, in &lt;module&gt; from setuptools.extension import Extension, Library File "C:\Software\Portable Python 3.2.5. 1\app\lib\site-packages\setuptools\extension.py", line 5, in &lt;module&gt; from setuptools.dist import _get_unpatched File "C:\Software\Portable Python 3.2.5. 1\app\lib\site-packages\setuptools\dist.py", line 103 except ValueError, e: ^ SyntaxError: invalid syntax 2) C:\Software\Portable Python 3.2.5.1&gt;App\py thon.exe App\easy_install.py textract-1.6.1.tar\textract-1.6.1\setup.py Traceback (most recent call last): File "App\easy_install.py", line 4, in &lt;module&gt; from setuptools.command.easy_install import main File "C:\Software\Portable Python 3.2.5. 1\App\lib\site-packages\setuptools\__init__.py", line 2, in &lt;module&gt; from setuptools.extension import Extension, Library File "C:\Software\Portable Python 3.2.5. 1\App\lib\site-packages\setuptools\extension.py", line 5, in &lt;module&gt; from setuptools.dist import _get_unpatched File "C:\Software\Portable Python 3.2.5. 1\App\lib\site-packages\setuptools\dist.py", line 103 except ValueError, e: ^ SyntaxError: invalid syntax any suggestion? thanks
tagged with: failed-installation
score: 0
has answer: http://stackoverflow.com/a/48857765
answer count: 1
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48857765
tagged with: pip
has title: How to install packages on portable python

http://stackoverflow.com/comment/84828333
type: AnswerComment
has text: I am trying to read the both English and banglish text files here to my classifier. So it can give me the confusion rate of banglish and english as in positive and negative format just like the movie review files.
type: Comment
comment on: http://stackoverflow.com/a/48901924
score: 0

http://stackoverflow.com/comment/84870726
has text: Its possible, but would not be worth doing that much complex. You are better off doing it separately
comment on: http://stackoverflow.com/q/48925311
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84721002
has text: yeah so dog.take_part_of_list would return a single linked list of the removed nodes from dog also if possible could it be done in my sortedlist class?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48858091
type: Comment

http://stackoverflow.com/a/48838338
has comment: http://stackoverflow.com/comment/84681155
answers question: http://stackoverflow.com/q/48838289
has body: You can parse and eval the string like: Code: @classmethod def from_str(cls, a_str): return cls(**eval("dict({})".format(a_str))) Test Code: class Sample: def __init__(self, a, b, c): self.a = a self.b = b self.c = c @classmethod def from_str(cls, a_str): return cls(**eval("dict({})".format(a_str))) x = Sample.from_str("a=100,b=100,c=100") print(x.a) Results: 100
score: 4
upvote count: 4
downvote count: 0
has comment: http://stackoverflow.com/comment/84681168
type: Answer

http://stackoverflow.com/comment/84783651
comment on: http://stackoverflow.com/q/48887664
type: Comment
type: QuestionComment
score: 0
has text: My guess is that this number of problems in the code are _very_ unlikely, and a Python2/3 mismatch is _extremely_ likely. Please keep looking in the book! Or, alternatively, see if you have Python 2 installed, or install it.

http://stackoverflow.com/a/48857684
has body: In Python 2, the third argument to the method type constructor was mostly used for unbound method objects: &gt;&gt;&gt; class Foo(object): ... def bar(self): ... pass ... &gt;&gt;&gt; Foo.bar &lt;unbound method Foo.bar&gt; A direct constructor call to create one of these would have looked like types.MethodType(bar, None, Foo), where bar is the function. Unbound method objects did a bit of type checking to ensure they weren't used for objects of the wrong type, but they were deemed not useful enough to justify their existence, so they got taken out in Python 3. With no more unbound method objects, there wasn't much reason for the method constructor to take a third argument, so that was removed too.
accepted answer of: http://stackoverflow.com/q/48857612
answers question: http://stackoverflow.com/q/48857612
upvote count: 5
type: AcceptedAnswer
downvote count: 0
score: 5
type: Answer

datetime
tags question: http://stackoverflow.com/q/48865905
tags question: http://stackoverflow.com/q/48911913
tags question: http://stackoverflow.com/q/48824516
tags question: http://stackoverflow.com/q/48860428
tags question: http://stackoverflow.com/q/48877457
tags question: http://stackoverflow.com/q/48844665
tags question: http://stackoverflow.com/q/48843335
tags question: http://stackoverflow.com/q/48870463
tags question: http://stackoverflow.com/q/48936196
tags question: http://stackoverflow.com/q/48943571
tags question: http://stackoverflow.com/q/48852586
tags question: http://stackoverflow.com/q/48892614
tags question: http://stackoverflow.com/q/48884480
tags question: http://stackoverflow.com/q/48857390
tags question: http://stackoverflow.com/q/48855400
tags question: http://stackoverflow.com/q/48906608
tags question: http://stackoverflow.com/q/48956392
tags question: http://stackoverflow.com/q/48937900
tags question: http://stackoverflow.com/q/48871617
tags question: http://stackoverflow.com/q/48808636
tags question: http://stackoverflow.com/q/48940739
tags question: http://stackoverflow.com/q/48896940
tags question: http://stackoverflow.com/q/48935408
tags question: http://stackoverflow.com/q/48935398
tag name: datetime
tags question: http://stackoverflow.com/q/48820188
tags question: http://stackoverflow.com/q/48825041
tags question: http://stackoverflow.com/q/48836549
tags question: http://stackoverflow.com/q/48935506
tags question: http://stackoverflow.com/q/48818380
tags question: http://stackoverflow.com/q/48927466
tags question: http://stackoverflow.com/q/48811627
tags question: http://stackoverflow.com/q/48924148
tags question: http://stackoverflow.com/q/48958534
tags question: http://stackoverflow.com/q/48861328
tags question: http://stackoverflow.com/q/48847264
tags question: http://stackoverflow.com/q/48939168
type: Tag
tags question: http://stackoverflow.com/q/48947759
tags question: http://stackoverflow.com/q/48882468
tags question: http://stackoverflow.com/q/48949193
tags question: http://stackoverflow.com/q/48819972
tags question: http://stackoverflow.com/q/48934245
tags question: http://stackoverflow.com/q/48895952
tags question: http://stackoverflow.com/q/48892148

http://stackoverflow.com/comment/84868942
type: Comment
has text: @Jaffer, the code in your jupyter notebook is working as it should. The issue is that these Linear Regression models are really poor to do the job, specially when you use them to estimate the input variables as well. It is really important to have some kind of Random Walk to make those models work better. But even that, it might be a lot of work put into to something that will not have much predictive power. Anyways, I made a Random Walk model for you, and added to my answer, so you can get a better idea of what I am talking about.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48886754

http://stackoverflow.com/q/48846606
has comment: http://stackoverflow.com/comment/84698099
tagged with: scrapy
type: Question
has answer: http://stackoverflow.com/a/48854067
score: 0
answer count: 2
has body: I have a web spider that looks like: def parse(self, response): links = LinkExtractor(unique=True).extract_links(response) for link in links: if '/item/' in link.url: yield response.follow(link, self.parse_item) else: yield response.follow(link, self.parse) def parse_item(self, response): res = MyItem() res['Param1'] = response.xpath('_get_param_1') res['Param2'] = response.xpath('_get_param_2') res['Param3'] = response.xpath('_get_param_3') yield res My problem is that each item has additional information on other page so I need to modify my code like this: def parse_item(self, response): res = MyItem() res['Param1'] = response.xpath('_get_param_1') res['Param2'] = response.xpath('_get_param_2') res['Param3'] = response.xpath('_get_param_3') new_url = response.url + '/more_info/' # Goto new_url res['Param4'] = response.xpath('_get_param_4') res['Param5'] = response.xpath('_get_param_5') yield res But I don't know how to do it with scrappy. UPD: What exactly I need. I need to parse a site with different apartments for rent. Each apartment has such url like site.com/item/id12345678 this page has price, address and some other information useful for me and I can parse them as usual with scrappy But also the same apartment has some additional information like sellers_phone on second page site.com/item/id12345678/more_info. And finally I want to get a list of records with: id, price, address, sellers_phone
has comment: http://stackoverflow.com/comment/84697832
has answer: http://stackoverflow.com/a/48847099
has title: How to parse item that consiste of multiple pages?
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84697622

http://stackoverflow.com/q/48824351
type: AnsweredQuestion
tagged with: pycharm
has title: PyCharm TensorFlow warning - Type 'Variable' doesn't have expected attribute '__sub__'
has body: Upon copying retrain.py from the TensorFlow GitHub repository And then opening it in PyCharm, on lines 794 and 802 PyCharm shows the following warning: Type 'Variable' doesn't have expected attribute '__sub__' Here is a screenshot if that helps: Can somebody please explain: What does this mean? How can this be resolved or the warning suppressed? Clearly PyCharm thinks that layer_weights does not have an attribute "__sub__", but what does this mean and why would a __sub__ attribute be necessary? The function variable_summaries() does not refer to an attribute __sub__ (copied/pasted starting at line 735): def variable_summaries(var): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar('stddev', stddev) tf.summary.scalar('max', tf.reduce_max(var)) tf.summary.scalar('min', tf.reduce_min(var)) tf.summary.histogram('histogram', var) # end of function Can somebody explain why an attribute __sub__ would be necessary? After reading the this post, I'm under the impression that a comment to suppress this warning could be added, possibly something like: @type whatGoesHere: ?? @attribute __sub__: comment here?? # is this correct? @param whatGoesHere: ?? Is something like this doable, and what should the comment be? I prefer to not disable PyCharm's warnings as I find them helpful in many cases. Can somebody please provide some enlightenment on the above so as to avoid disabling this warning in PyCharm? - Edit: Thanks for the explanation Shu. For the moment this seems to be the best way to deal with this in PyCharm without disabling that inspection entirely: # this comment is necessary to suppress an unnecessary PyCharm warning # noinspection PyTypeChecker variable_summaries(layer_weights) If eventually somebody could inform me of a better option that would be gr…
score: 6
tagged with: tensorflow
accepted answer: http://stackoverflow.com/a/48836872
type: Question
has answer: http://stackoverflow.com/a/48836872
linked to: http://stackoverflow.com/q/6318814
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/93292605
tagged with: python
upvote count: 6

http://stackoverflow.com/comment/84680088
comment on: http://stackoverflow.com/q/48837063
type: Comment
type: QuestionComment
score: 0
has text: I specifically changed the id to "checkbx" from "checkbox" to see where i'm going wrong. also adding a value doesn't change a thing. request.form.getlist('checkbox')[1] continues to return []

qtablewidgetitem
tags question: http://stackoverflow.com/q/48933553
type: Tag
tag name: qtablewidgetitem

http://stackoverflow.com/q/48869453
tagged with: python
tagged with: opencv
has answer: http://stackoverflow.com/a/48931943
tagged with: anaconda
accepted answer: http://stackoverflow.com/a/48931943
possible better answer: http://stackoverflow.com/a/48922427
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48922427
has comment: http://stackoverflow.com/comment/84743321
tagged with: python-2.7
type: Question
has title: opencv with anaconda python2
has body: I know there is lot of questions about it but I still can't find a useful answer. I have anaconda installed with python 2 and i have builded my own version of opencv with cmake and visual studio, how can i connect my anaconda python2 to opencv? When I just copy cv2.pyd from opencv into python, I can import cv2 but cv2.face is missing; what can I do? I need that cv2.face, i am working on face recognition project. error: File "C:/Users/Gio/Desktop/Face Proj/main.py", line 54, in &lt;module&gt; face_recognizer = cv2.face.LBPHFaceRecognizer_create(); AttributeError: 'module' object has no attribute 'face'
score: 0
has comment: http://stackoverflow.com/comment/84743113
answer count: 2

http://stackoverflow.com/comment/84796040
comment on: http://stackoverflow.com/q/48895054
type: Comment
has text: Which version of Django are you using? You might want to take a look at: https://docs.djangoproject.com/en/2.0/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84756026
has text: @Evert due to time constraint, I ended up extracting the dates from the file name instead, however I'll lose the exact datetime for each entry in the file. I might create a function in the future to do this if I still need it. Thanks for your suggestion!
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48861328

http://stackoverflow.com/comment/84830753
score: 0
has text: You are attempting to decode a reader, which is not possible. Try decoding individual words `w.decode()` instead.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48911850

http://stackoverflow.com/comment/84858913
comment on: http://stackoverflow.com/a/48926353
type: AnswerComment
score: 0
type: Comment
has text: Can you give me an idea of what "all addresses" means? Because it doesn't include "0.0.0.0" and it doesn't include "1.1.1.1".

http://stackoverflow.com/comment/84716750
type: Comment
comment on: http://stackoverflow.com/q/48856477
score: 0
type: QuestionComment
has text: Please update your question with more examples like this.

http://stackoverflow.com/q/48917438
type: AnsweredQuestion
upvote count: 3
type: Question
score: 3
tagged with: pyspark
has title: PySpark ML Pipeline.load results throws java.lang.UnsupportedOperationException: empty collection
has answer: http://stackoverflow.com/a/48936379
answer count: 1
downvote count: 0
favorite count: 0
tagged with: apache-spark-ml
has body: I have a PySpark fitted pipeline that I am saving to disk for later use. Here is my pipeline code : model = Pipeline(stages=[segment_indexer, model_name_indexer, make_name_indexer, engine_type_indexer, segment_encoder, model_name_incoder, make_name_incoder, engine_type_incoder, x_assembler, estimator]).fit(trainingData) model.save('file:/opt/app/fitted-model' ) This saves the model to disk. I am trying to load the model back like so model2 = pyspark.ml.pipeline.PipelineModel.load("file:/tmp/mymodels/fitted-model") which throws Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/spark/python/pyspark/ml/util.py", line 257, in load return cls.read().load(path) File "/usr/lib/spark/python/pyspark/ml/util.py", line 197, in load java_obj = self._jread.load(path) File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__ File "/usr/lib/spark/python/pyspark/sql/utils.py", line 63, in deco return f(*a, **kw) File "/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling o2760.load. : java.lang.UnsupportedOperationException: empty collection at org.apache.spark.rdd.RDD$$anonfun$first$1.apply(RDD.scala:1370) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112) at org.apache.spark.rdd.RDD.withScope(RDD.scala:362) at org.apache.spark.rdd.RDD.first(RDD.scala:1367) at org.apache.spark.ml.util.DefaultParamsReader$.loadMetadata(ReadWrite.scala:382) at org.apache.spark.ml.Pipeline$SharedReadWrite$.load(Pipeline.scala:266) at org.apache.spark.ml.PipelineModel$PipelineModelReader.load(Pipeline.scala:347) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(…
accepted answer: http://stackoverflow.com/a/48936379
tagged with: python

http://stackoverflow.com/a/48934328
accepted answer of: http://stackoverflow.com/q/48934188
has body: The glob package should be used like: import glob f = glob.glob("*.xlsx") The glob is not a method but glob.glob is. ======================================== import glob excel_files = glob.glob('C:/Users/username/Documents/TestFolder/JanuaryDataSentToResourcePro/*.xlsx') # assume the path for excel in excel_files: out = excel.split('.')[0]+'.csv' df = pd.read_excel(excel) # if only the first sheet is needed. df.to_csv(out)
answers question: http://stackoverflow.com/q/48934188
has comment: http://stackoverflow.com/comment/84875834
has comment: http://stackoverflow.com/comment/84875456
has comment: http://stackoverflow.com/comment/84876015
score: 12
has comment: http://stackoverflow.com/comment/84876067
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84876751
has comment: http://stackoverflow.com/comment/84876192
has comment: http://stackoverflow.com/comment/84875814
has comment: http://stackoverflow.com/comment/84876028
has comment: http://stackoverflow.com/comment/84875632
type: Answer
upvote count: 12
downvote count: 0
has comment: http://stackoverflow.com/comment/84876499

http://stackoverflow.com/comment/84878110
comment on: http://stackoverflow.com/a/48935527
type: Comment
has text: Another question: Shouldn't I use "rnn_cell.LSTMCell.zero_state(batch_size, dtype)" instead of "rnn_cell.zero_state", if yes, then the first input is the number of frames in one sequence or the number of sequences I feed each time? Thanks a lot @Maxim
type: AnswerComment
score: 0

http://stackoverflow.com/a/48924566
score: 1
has body: Here is one way: d = {"stripes": [1,0,5,3], "legs": [4,4,2,3], "colour": ['red', 'grey', 'blue', 'green']} def get_element(d, i): return dict(zip(d, list(zip(*d.values()))[i])) get_element(d, 2) # {'colour': 'blue', 'legs': 2, 'stripes': 5}
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48924491

http://stackoverflow.com/comment/84845879
comment on: http://stackoverflow.com/q/48919764
has text: https://docs.python.org/3/library/shutil.html?highlight=shutil%20ignore_patterns#shutil.ignore_patterns ?
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84664446
type: Comment
has text: @Riccardo, I also made the changes in my answer.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48829513

http://stackoverflow.com/comment/84681415
type: QuestionComment
comment on: http://stackoverflow.com/q/48838478
has text: To add a new directory to your include-path, put -I/the/directory/where/python.h/is/located into your CFLAGS variable (replace the path after -I with the Python.h file's actual location, of course... and btw that is dash-capital-eye, not a dash-lower-case-ell, in case your browser's font makes it hard to tell which letter it is)
score: 1
type: Comment

http://stackoverflow.com/comment/84679064
type: Comment
has text: Thanks but what about the loop to make it restart or quit?
comment on: http://stackoverflow.com/a/48836608
type: AnswerComment
score: 0

http://stackoverflow.com/a/48818316
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48818181
has body: Your problem is that you have as many tags within 1 as many products you have displayed. They all have the same name, so you always get the value of the first one. I'd recommend getting rid of and attaching the value of product.id to the button itself (or to be exact). Here's the more descriptive explanation: How can I build multiple submit buttons django form? An alternative would be to change your code to have multiple forms, like that: {% for product in products %} {% csrf_token %} {{ product.name }} Add to Basket {{ product.id }} {% endfor %}
score: 2
answers question: http://stackoverflow.com/q/48818181

http://stackoverflow.com/comment/84845032
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48919279
has text: @miradulo this is the kind of information I am after, thank you
score: 0

http://stackoverflow.com/comment/84681821
has text: yes definitely, the socketio.on('connect') bind won't fire until the client has connected
comment on: http://stackoverflow.com/q/48836493
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84642937
type: Comment
type: QuestionComment
has text: define a recursive function to do that
comment on: http://stackoverflow.com/q/48819547
score: 0

http://stackoverflow.com/comment/84721561
type: AnswerComment
has text: @YepramYeransian You're welcome! Please be sure to accept my answer and upvote it :)
type: Comment
comment on: http://stackoverflow.com/a/48858975
score: 0

http://stackoverflow.com/a/49015093
type: Answer
accepted answer of: http://stackoverflow.com/q/48812379
answers question: http://stackoverflow.com/q/48812379
has body: Your code is all kinds of wrong. First of all, the 2nd call to "get()" is not necessary here: return c = Products.get(Products.sku == article).get() Second of all, you are returning an assignment (?) which makes no sense. Change to: return Products.get(Products.sku == article) If the product exists, it will be returned. If not, a DoesNotExist exception will be raised, making it unnecessary to call "count()" anywhere. To make the code work even if the product is not found: try: return Products.get(Products.sku == article) except Products.DoesNotExist: # Product was not found. return
type: AcceptedAnswer
score: 0

http://stackoverflow.com/a/61538231
upvote count: 2
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48907073
has body: The David Tourrel is a nice workaround, and it's working, but the same issue is something that happened to me since yesterday, when I had to uninstall/reinstall glances. I still don't know why it's happening. it seems related to the sensors (heat? fan) idk). When looking for in the internet I found the glances --disable-sensors makes appear the warning message just once during its startup, and not during the running.

http://stackoverflow.com/comment/84790325
type: AnswerComment
comment on: http://stackoverflow.com/a/48892356
type: Comment
has text: conn.commit() fixed the issue
score: 0

http://stackoverflow.com/q/48838151
has title: storing csv data in python list and accessing through list indices
type: Question
accepted answer: http://stackoverflow.com/a/48838185
score: -1
upvote count: 0
answer count: 1
has body: I have a csv file with 1000000 records, having data as below: age zipcode salary occupation 33 2139 1001 'Financial analyst' 65 2139 1060 'Shoemaker' 46 2139 1061 'Domestic worker' 38 2140 1003 'Vicar' 54 2140 1029 'Mason' 44 2139 1002 'Philosopher' I want to store it in a list Gtable using Python as below, I want to read a csv file(testReading.csv) in Gtable variable, which further i can access via Gtable[0] and Gtable[1]. How will i do this in Python, please guide, Thankyou all. Gtable = [[age],[zipcode],[salary],[occupation]] Thank you
favorite count: 0
has answer: http://stackoverflow.com/a/48838185
tagged with: python
type: AnsweredQuestion
downvote count: 1

http://stackoverflow.com/comment/84761096
type: Comment
has text: You're wrong, that's not "partially true", I only referred to Worst Case. I never once talked about best case or average case. If I was talking about best case I would have used the correct symbol. And the reason why we are doing this check is because sometimes the list is not sorted, therefore it is O(N log N)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48869154

http://stackoverflow.com/a/48811481
has comment: http://stackoverflow.com/comment/84626689
has comment: http://stackoverflow.com/comment/84626773
answers question: http://stackoverflow.com/q/48811332
score: 0
upvote count: 1
type: Answer
has body: You were very close, just use update(): d = {'A':[1,2], 'B':[0], 'c':[4]} d.update({x: y+[0] for (x,y) in d.items() if len(y) &lt; 2}) d # {'A': [1, 2], 'B': [0, 0], 'c': [4, 0]} Like others have said, don't use reassign reserved names like dict, it's a one way street down to debugging hell.
downvote count: 1

http://stackoverflow.com/comment/84762040
comment on: http://stackoverflow.com/q/48878848
type: Comment
score: 1
type: QuestionComment
has text: I am indeed a real person, yes. Cheers ;)

http://stackoverflow.com/a/48888246
answers question: http://stackoverflow.com/q/48886737
has comment: http://stackoverflow.com/comment/84781845
score: 0
type: Answer
has body: Surprisingly, combining the two methods also solved it: fig, ax = plt.subplots() fig.set_size_inches(20,20) x = df['x'].tolist() y = df['y'].tolist() ax.scatter(x, y) for i, txt in enumerate(data['c'].tolist()): ax.annotate(txt, (x[i],y[i])) for c in np.unique(data['c'].tolist()): df = tsne_df[data['c'].isin([c])] plt.plot(data['x'].tolist(),data['y'].tolist(),'o') plt.show()

http://stackoverflow.com/comment/84704444
comment on: http://stackoverflow.com/q/48849192
type: Comment
type: QuestionComment
has text: @MarioNikolaus ITs just there freezed and after some time, timeout.
score: 0

http://stackoverflow.com/a/48874849
has comment: http://stackoverflow.com/comment/84755211
type: Answer
has comment: http://stackoverflow.com/comment/84755136
has body: Capture all the return values, then test them individually. ... numsum,dif = example(5,3) self.assertEqual(numsum,8) self.assertEqual(dif,2) or, as @sleigh_bells points out compare a tuple to the returned tuple: self.assertEqual(example(5,3),(8,2))
downvote count: 0
answers question: http://stackoverflow.com/q/48874769
score: 7
has comment: http://stackoverflow.com/comment/84753822
upvote count: 7
has comment: http://stackoverflow.com/comment/84755193

http://stackoverflow.com/comment/84813969
comment on: http://stackoverflow.com/q/48904160
score: 0
has text: Do you change `__table__` parameter of your class when changing the db?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84841881
type: QuestionComment
comment on: http://stackoverflow.com/q/48917405
has text: @DanielPryden Op is right with his/her concern about processing the whole string if he needs the first three letters in a million letter string (if that's the only concern). I couldn't speak for the rest of the problem of course, which I don't know.
score: 1
type: Comment

http://stackoverflow.com/a/49682573
type: Answer
has body: As stated in one of the comments the HTML you are trying to get is added with JavaScript running on the browser. I recommend you this package Requests-HTML created by the author of very popular requests. from requests_html import HTMLSession session = HTMLSession() r = session.get('https://www.pullandbear.com/rs/man/sale-c1030036006.html') r.html.render() print(r.html.html)
answers question: http://stackoverflow.com/q/48874874
score: 0

http://stackoverflow.com/comment/84737649
comment on: http://stackoverflow.com/q/48866559
score: 0
type: Comment
type: QuestionComment
has text: I have installed and trained using the Tensorflow GPU install which it shows the app is using that for training. The code we’re using is just the standard script available to everyone on the Tensorflow Object Detection github download. This would be label_image.py and object_detection.py

http://stackoverflow.com/comment/86230864
has text: Ok, so I need to move pytest_runtest_setup to the directory conftest. I use pytest_runtest_setup for skiping tests if a condition based on a test variable and an external variable is True. I have access to the test variable from item._request.function.func_globals .
score: 0
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48980082

http://stackoverflow.com/comment/84721288
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48858791
has text: @cᴏʟᴅsᴘᴇᴇᴅ Could you, please check the last version?

http://stackoverflow.com/a/48914428
has comment: http://stackoverflow.com/comment/84835532
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/84836805
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48913525
has body: According to the scrapy docs: By default, Scrapy runs a single spider per process when you run scrapy crawl. However, Scrapy supports running multiple spiders per process using the internal API. For example: import scrapy from scrapy.crawler import CrawlerProcess class MySpider1(scrapy.Spider): # Your first spider definition ... class MySpider2(scrapy.Spider): # Your second spider definition ... process = CrawlerProcess() process.crawl(MySpider1) process.crawl(MySpider2) process.start() # the script will block here until all crawling jobs are finished If you want to run another spider after you've called process.start then I expect you can just issue another process.crawl(SomeSpider) call at the point in your program where you determine the need to do this. Examples of other scenarios are given in the docs.

machine-learning
tags question: http://stackoverflow.com/q/48820093
tags question: http://stackoverflow.com/q/48814051
tags question: http://stackoverflow.com/q/48873321
tags question: http://stackoverflow.com/q/48865972
tags question: http://stackoverflow.com/q/48954694
tags question: http://stackoverflow.com/q/48940155
tags question: http://stackoverflow.com/q/48872742
tags question: http://stackoverflow.com/q/48922811
tags question: http://stackoverflow.com/q/48870593
tags question: http://stackoverflow.com/q/48880557
tags question: http://stackoverflow.com/q/48815431
tags question: http://stackoverflow.com/q/48920795
tags question: http://stackoverflow.com/q/48869343
tags question: http://stackoverflow.com/q/48846894
tags question: http://stackoverflow.com/q/48884497
tags question: http://stackoverflow.com/q/48862451
tags question: http://stackoverflow.com/q/48853484
tags question: http://stackoverflow.com/q/48865055
tags question: http://stackoverflow.com/q/48854669
tags question: http://stackoverflow.com/q/48940148
tags question: http://stackoverflow.com/q/48941825
tags question: http://stackoverflow.com/q/48832093
tags question: http://stackoverflow.com/q/48804734
tags question: http://stackoverflow.com/q/48881901
tags question: http://stackoverflow.com/q/48901427
tags question: http://stackoverflow.com/q/48941208
tags question: http://stackoverflow.com/q/48872738
tags question: http://stackoverflow.com/q/48962963
tags question: http://stackoverflow.com/q/48839618
tags question: http://stackoverflow.com/q/48842037
tags question: http://stackoverflow.com/q/48934737
tags question: http://stackoverflow.com/q/48930933
tag name: machine-learning
tags question: http://stackoverflow.com/q/48901691
tags question: http://stackoverflow.com/q/48831851
tags question: http://stackoverflow.com/q/48920762
tags question: http://stackoverflow.com/q/48942865
tags question: http://stackoverflow.com/q/48901491
tags question: http://stackoverflow.com/q/48826912
tags question: http://stackoverflow.com/q/48938120
tags question: http://stackoverflow.com/q/48843721
tags question: http://stackoverflow.com/q/48818434
type: Tag
tags question: http://stackoverflow.com/q/48827687
tags question: http://stackoverflow.com/q/48958204
tags question: http://stackoverflow.com/q/48931265
tags question: http://stackoverflow.com/q/48826588
tags question: http://stackoverflow.com/q/48880934
tags question: http://stackoverflow.com/q/48909418
tags question: http://stackoverflow.com/q/48954453
tags question: http://stackoverflow.com/q/48857159
tags question: http://stackoverflow.com/q/48856766
tags question: http://stackoverflow.com/q/48880922
tags question: http://stackoverflow.com/q/48845016
tags question: http://stackoverflow.com/q/48867788
tags question: http://stackoverflow.com/q/48858878
tags question: http://stackoverflow.com/q/48933449
tags question: http://stackoverflow.com/q/48853066
tags question: http://stackoverflow.com/q/48950421
tags question: http://stackoverflow.com/q/48929072
tags question: http://stackoverflow.com/q/48938828
tags question: http://stackoverflow.com/q/48823289
tags question: http://stackoverflow.com/q/48956252
tags question: http://stackoverflow.com/q/48873387
tags question: http://stackoverflow.com/q/48898104
tags question: http://stackoverflow.com/q/48886477
tags question: http://stackoverflow.com/q/48827414
tags question: http://stackoverflow.com/q/48829294
tags question: http://stackoverflow.com/q/48843521
tags question: http://stackoverflow.com/q/48955382
tags question: http://stackoverflow.com/q/48899303
tags question: http://stackoverflow.com/q/48821582
tags question: http://stackoverflow.com/q/48962697
tags question: http://stackoverflow.com/q/48835999
tags question: http://stackoverflow.com/q/48807841
tags question: http://stackoverflow.com/q/48808985
tags question: http://stackoverflow.com/q/48849540
tags question: http://stackoverflow.com/q/48813968
tags question: http://stackoverflow.com/q/48816873
tags question: http://stackoverflow.com/q/48938905

pywinauto
tags question: http://stackoverflow.com/q/48927607
tags question: http://stackoverflow.com/q/48861296
tags question: http://stackoverflow.com/q/48835228
tags question: http://stackoverflow.com/q/48859825
tags question: http://stackoverflow.com/q/48926844
tag name: pywinauto
type: Tag

http://stackoverflow.com/comment/84766966
score: 0
comment on: http://stackoverflow.com/q/48870977
type: QuestionComment
has text: what type of data you feed this network what the right shape for this data
type: Comment

http://stackoverflow.com/comment/84727515
type: Comment
comment on: http://stackoverflow.com/q/48862090
score: 0
type: QuestionComment
has text: @Yohboy only one to store

http://stackoverflow.com/q/48896940
accepted answer: http://stackoverflow.com/a/48918232
tagged with: datetime
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: matplotlib
type: Question
has body: I'm trying to read a csv file that has a date that looks like this: 2018-02-20T22:41:33.793000Z and I can't figure out how to use that as the x axis in matplotlib. I obviously have no idea what I"m doing with datetime because I can't seem to get it to be usefull numbers for matplotlib. from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np import pandas as pd import sys import os import matplotlib import matplotlib.dates as mdates import datetime from datetime import datetime data = pd.read_csv(os.path.join(os.path.dirname(__file__), 'new.csv')) fig = plt.figure() ax = fig.add_subplot(111, projection='3d') b = data.iloc[:, 8] #reading from column 8 a = pd.to_datetime(b, format='%Y-%m-%dT%H:%M:%S.%fZ', errors='ignore') print(a) x = a #date #.iloc[:, 0] grabs column without header y = data.iloc[:, 2] #number #reading from column 2 z = data.iloc[:, 6] #quantity #reading from column 6 #c = data.bluered #blue or red ax.scatter(x, y, z) #ax.scatter(x, y, z, c=c) plt.xlim(-1, 35) plt.ylim(0, 300) ax.set_zlim(-1,150) plt.show()
has answer: http://stackoverflow.com/a/48918232
has title: trying to convert iso 8601 time to be used with matplotlib
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/q/48846417
tagged with: count
tagged with: python
type: Question
tagged with: sum
has answer: http://stackoverflow.com/a/48846591
has answer: http://stackoverflow.com/a/48846479
score: 0
answer count: 2
tagged with: pandas
has body: In pandas with python I need to total the number of rows in each csv file then add them together under the variable total_months but I keep getting an error and I have no idea what I am doing incorrectly not sure what attributes i should use to get this working. what i want to do is count up the total number of rows in each file and then add them together # Modules import numpy as np import pandas as pd import csv # Read my budget data into pandas df1 = pd.read_csv(budget_1_csv) df2 = pd.read_csv(budget_2_csv) budget_one_months = df1["Date"].value_counts budget_two_months = df2["Date"].value_counts I try this total_months = [budget_one_months].value_counts() + ["budget_two_months"].value_counts() And get this error message # --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-19-2cd6e6e55bc7&gt; in &lt;module&gt;() ----&gt; 1 total_months = [budget_one_months].value_counts() + ["budget_two_months"].value_counts() 2 total_months AttributeError: 'list' object has no attribute 'value_counts' total_months = [budget_one_months].value_counts() + ["budget_two_months"].value_counts() total_months
has title: need to total number of rows in two csv files and add them together in pandas
type: UnansweredQuestion
tagged with: http://stackoverflow.com/tag/csv

http://stackoverflow.com/comment/84696148
score: 1
comment on: http://stackoverflow.com/a/48843247
type: AnswerComment
type: Comment
has text: Don't just post code. Please add an explanation of why this would answer the question.

http://stackoverflow.com/comment/84887169
type: QuestionComment
comment on: http://stackoverflow.com/q/48939676
has text: Did it occur to you that the definition of `f` might be important?
score: 0
type: Comment

http://stackoverflow.com/comment/84928834
type: Comment
has text: Thank you very much! That is interesting, seems better than repeating ' df['ColX'] ' in the choicelist part. Here we could say comma and | in the conditions-list don't affect the end result differently I assume.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48852911

http://stackoverflow.com/a/48846479
has comment: http://stackoverflow.com/comment/84697177
has comment: http://stackoverflow.com/comment/84697091
answers question: http://stackoverflow.com/q/48846417
has comment: http://stackoverflow.com/comment/84697094
score: 0
type: Answer
has body: You have a typo [budget_one_months].value_counts() + ["budget_two_months"].value_counts() because you want to call the variable budget_two_months and not the string "budget_two_months" You forgot the parenthesis when defining budget_one_months and budget_two_months. It should be budget_one_months = df1["Date"].value_counts() and same for budget_two_months You should not call value_counts() again. You're calling these methods on lists while they are pd.DataFrame() methods. And you already have these counts computed because you created variables budget_one_months and budget_two_months just above. I think you just want to use this : total_months = budget_one_months + budget_two_months
has comment: http://stackoverflow.com/comment/84697197
has comment: http://stackoverflow.com/comment/84697135

http://stackoverflow.com/q/48891471
has comment: http://stackoverflow.com/comment/84788625
tagged with: conditional-statements
tagged with: if-statement
has body: Apologies for the title, I don't know the terminology for what I am trying to do. I have a function that has a series of nested loops, that runs a huge amount of times. The loops have many conditions as to whether they continue, or start over. Occasionally, this function is called such that it needs to meet certain conditions that are rare. However, to check for them, I need to add even more if statements into my code. Here is an example of what I am talking about, some of the looping in my function: while 1: for node in currset: for (sum1, weight1, l1, r1) in pathdict[(0, node)]: if sum1 &amp; sum != sum1 or r1 == left or r1 == right or l1 == left: continue if level &lt; connectright: if l1 == right: continue elif l1 != right: continue for (sum2, weight2, l2, r2) in pathdict[(level, r1)]: if sum2&amp;sum != sum2: continue if l2 != left or l2 == right: continue andsum = sum1&amp;sum2 if andsum != r1: continue Now, what do I do if I have a special case where many of these conditions no longer apply? The way I see it now, I can either 1.)write an entirely new function, 2.)rewrite the entire block of code and put it after another if statement, 3.)add a series of even more conditions, or 4.)write a function that checks my conditions at a given step. The first 2 options seem bulky but at least my code would go fast. The 3rd seems horrible because the code becomes hard to read, and it slows down. And the 4th, I am unsure but it seems like calling these functions so many times would slow down my loops. So my question is, is there some way that I can write "conditional if statements", where depending on the variables passed to the function, I could do something like: if variable_passed == thing#1: my_if_statement = (if level &lt; connectright: continue) else: my_if_statement = (if level &gt; connectright: continue) This way I could easily change my conditions at the start of the function, before I begin looping.
has title: Can an if statement be a variable?
tagged with: loops
type: Question
tagged with: algorithm
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48892792
accepted answer: http://stackoverflow.com/a/48892792
favorite count: 0
has comment: http://stackoverflow.com/comment/84789883
upvote count: 2
has comment: http://stackoverflow.com/comment/84788543
tagged with: python
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/48847010
tagged with: django
tagged with: python
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
answer count: 2
possible better answer: http://stackoverflow.com/a/48847579
accepted answer: http://stackoverflow.com/a/48847058
has title: In Django, can the choices defined in a model class be accessed elsewhere outside the model class?
has body: I have the following model class class Movies(models.Model): MOVIE_CHOICES = ( ('SHAW', 'Shashank Redemption'), ('NIGHT', 'In the Heat of the Night'), ('GOD', 'The God Father'), ('INVIC', 'Invictus'), ) title = models.CharField(max_length = 100, choices = MOVIE_CHOICES) and I am writing the values to a database table. When I query the database table, I will get the key back, e.g. I get INVIC back. In my code I will need to get the value for the key, in this case Invictus. To be able to do this, I need access to the data structure that holds the key-value pair. How to access MOVIE_CHOICES by key outside of the model class? Alternatively, can I use a dictionary to set values for choices?
has answer: http://stackoverflow.com/a/48847058
favorite count: 0
has answer: http://stackoverflow.com/a/48847579

http://stackoverflow.com/q/48856369
has title: how to merge based on boolean condition in python?
has comment: http://stackoverflow.com/comment/84744063
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84716435
has body: I have two data frames, e.g. &gt;&gt;&gt;df1 datetime id 2018-01-01 1:00:11 abc 2018-01-01 12:00:00 flllds &gt;&gt;&gt;df2 datetime2 id 2018-01-01 1:30:11 abc 2018-01-01 1:30:32 abc 2018-01-01 2:30:32 abc 2018-01-01 12:00:00 flllds I have to join the data frames based on the id and select rows where datetime - datetime2 &lt; 1 hour My issue is that my data frames are huge, so I get a MemoryError when I first merge and then filter based on condition. Is there a way I can limit the size of the data frame during the merge? df = pd.merge(df1, df2, on=['id'])
answer count: 0
has comment: http://stackoverflow.com/comment/84716843
type: Question
score: 0
tagged with: pandas

http://stackoverflow.com/comment/84843539
comment on: http://stackoverflow.com/q/48918145
score: 0
type: Comment
type: QuestionComment
has text: Got some sample inputs? | I probably wouldn't call this trivial. However, I'd suggest to remove that part of the question, as that is rather opinion base.

http://stackoverflow.com/q/48831733
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48832336
type: UnansweredQuestion
tagged with: python
tagged with: php
downvote count: 0
score: 1
has title: Invalid Content Verification Signature (HMAC in Python)
type: Question
has body: I need help with PHP to Python 3+ code conversion. By the link https://icobench.com/developers at Auth and examples section, you can find the code of a class for work with website API. I already wrote Python class, but it doesn't work correctly. import html import io import json import hashlib import hmac import pycurl class ICObenchAPI: private_key = '' public_key = '' api_url = 'https://icobench.com/api/v1/' result = None def get_icos(self, parameter='all', data=''): return self.send('icos/{0}'.format(parameter), data) def get_ico(self, ico_id, data=''): return self.send('ico/{0}'.format(str(ico_id)), data) def get_other(self, parameter): return self.send('other/{0}'.format(parameter), '') def get_people(self, parameter='registered', data=''): return self.send('people/{0}'.format(parameter), data) def send(self, action, data): data_json = json.dumps(data) print("data_json: ", data_json) #$sig = base64_encode(hash_hmac('sha384', $dataJson, $this-&gt;privateKey, true)); signature = hmac.new(self.private_key.encode('utf-8'), msg=data_json.encode('utf-8'), digestmod=hashlib.sha384).hexdigest() print("signature: ", signature) headers = [ 'Content-Type: application/json', 'Content-Length: {0}'.format(len(data_json)), 'X-ICObench-Key: {0}'.format(self.public_key), 'X-ICObench-Sig: {0}'.format(signature) ] print("headers: ", headers) buffer = io.BytesIO() action_url = self.api_url + action print("action_url: ", action_url) ch = pycurl.Curl() ch.setopt(pycurl.URL, action_url) ch.setopt(pycurl.POSTFIELDS, data_json) ch.setopt(pycurl.SSL_VERIFYPEER, False) ch.setopt(pycurl.HTTPHEADER, headers) ch.setopt(pycurl.WRITEFUNCTION, buffer.write) ch.perform() reply = buffer.getvalue().decode('UTF-8') ff = reply reply = json.loads(reply) if reply['error'] is not None: self.result = reply['error'] return False elif reply['message'] is not None: self.result = reply['message'] return True elif reply is not None: self.result = json.dumps(reply) return True else: self.result = html.escape…
tagged with: api
upvote count: 1

http://stackoverflow.com/comment/84823847
score: 0
type: AnswerComment
has text: Thank you very much for your answer, but it gives the following error: Shape must be rank 1 but is rank 4 for 'Tile_4' (op: 'Tile') with input shapes: [5], [4]. I am guessing that is because range (b) and multiples are not of the same shape
comment on: http://stackoverflow.com/a/48907764
type: Comment

http://stackoverflow.com/comment/84836374
type: Comment
type: QuestionComment
has text: You mention threads and it's clear you're using SQLite: see [How to share single SQLite connection in multi-threaded Python application](https://stackoverflow.com/questions/22739590/how-to-share-single-sqlite-connection-in-multi-threaded-python-application) for some potential issues
comment on: http://stackoverflow.com/q/48914609
score: 0

http://stackoverflow.com/comment/84788646
has text: Upload text file and post a link of it. Also give the output for the test file. Only then, we can help you.
comment on: http://stackoverflow.com/q/48891613
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/84832956
type: QuestionComment
comment on: http://stackoverflow.com/q/48913149
has text: can you try to use the levenshtein distance?? https://en.wikipedia.org/wiki/Levenshtein_distance
score: 0
type: Comment

http://stackoverflow.com/comment/84923027
score: 0
type: AnswerComment
has text: What df.info() prints?
type: Comment
comment on: http://stackoverflow.com/a/48957820

http://stackoverflow.com/q/48912485
answer count: 0
upvote count: 1
has comment: http://stackoverflow.com/comment/84866843
type: Question
tagged with: python-imaging-library
has body: Suppose I have already saved an image in JPEG format and quality 90 using PIL. If I load this image and try to save it again do I need to specify quality 100 this time so that the image will not be further compressed or does PIL recognize that the image is in quality 90 format and saves it without more compression? I have this question because I want to save all my images in an LMDB file. I have the images saved in the disk with 90 JPEG compression and wonder if the following snippet img = Image.open(imagePath) faux_file = BytesIO() img.save(faux_file, 'JPEG') contents = faux_file.getvalue() faux_file.close() will further downgrade the image (which I do not want to happen).
downvote count: 0
score: 1
has title: Python Imaging Library Resave Image
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84866178
has comment: http://stackoverflow.com/comment/84832694
tagged with: python
has comment: http://stackoverflow.com/comment/84956565

http://stackoverflow.com/q/48848465
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84700788
tagged with: python
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84700827
has title: Web scraping pdf using URL Python 3 TypeError
type: Question
has answer: http://stackoverflow.com/a/48848537
linked to: http://stackoverflow.com/q/26494211
has comment: http://stackoverflow.com/comment/84700800
answer count: 2
has body: I am trying to code code that downloads a PDF from a URL. I found a method of doing this, but it was not written in Python 3 and used the file() function. I tried replacing this with open() in the line fp = open(path, 'rb'). However I get this error: TypeError: expected str, bytes or os.PathLike object, not HTTPResponse. I cant find a solution online. Any help would be appreciated. Here is the code: import bs4 as bs import urllib.request from urllib.request import urlopen from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.pdfpage import PDFPage from pdfminer.layout import LAParams from io import StringIO from io import open 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) fp.close() device.close() stri = retstr.getvalue() retstr.close() return stri pdfFile = urlopen("http://pythonscraping.com/pages/warandpeace/chapter1.pdf"); outputString = convert_pdf_to_txt(pdfFile) print(outputString) pdfFile.close() Resources used http://zempirians.com/ebooks/Ryan%20Mitchell-Web%20Scraping%20with%20Python_%20Collecting%20Data%20from%20the%20Modern%20Web-O'Reilly%20Media%20(2015).pdf (page 101) Extracting text from a PDF file using PDFMiner in python? (the top answer)
upvote count: 1
has answer: http://stackoverflow.com/a/48849588
favorite count: 0

http://stackoverflow.com/comment/84693332
type: Comment
has text: There's nothing special about the y-values of those interpolation points, so the structure of the code would be exactly the same. Obviously, the exact form of the exponential function would need to be changed, and the parameters to the interp1d() used to calculate linearVals.
comment on: http://stackoverflow.com/a/48843444
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84895685
type: Comment
comment on: http://stackoverflow.com/a/48944107
score: 1
type: AnswerComment
has text: Thanks a lot. That's working for me. i just modified the last line to result.to_csv("my_csv_file.csv", index=False,columns=['doc_type','key','mem_num','current_flag','mem_flag','child_mem_num','first_name','middle_name','last_name','created_datetime'])

http://stackoverflow.com/a/48956589
has comment: http://stackoverflow.com/comment/134688135
type: Answer
has body: Hmm, interesting. I thought this would be a duplicate question, or that a straightforward way to do this would be documented, but if so I can't find it. The documentation does have a section about Data migrations and multiple databases, but the techniques there only apply to RunPython and RunSQL operations. They are: Add a hints argument to your RunPython or RunSQL operation. That value will be passed to the database router, where you can decide whether or not the operation should be applied. Within the RunPython function, check schema_editor.connection.alias to determine which database is being used, and switch on that. Unfortunately, the schema_editor isn't exposed on the Migration class. Looking at the code, you could override the apply() method, since that does expose the schema_editor. class Migration(migrations.Migration): dependencies = [...] operations = [...] def apply(self, project_state, schema_editor, collect_sql=False): if schema_editor.connection.alias == "my_sqlite_database": return super().apply(project_state, schema_editor, collect_sql=collect_sql) else: return project_state Please note that this is untested, and relies on undocumented behavior. I hope a better solution exists.
answers question: http://stackoverflow.com/q/48951238
upvote count: 1
downvote count: 0
score: 1

http://stackoverflow.com/comment/84678750
score: 3
comment on: http://stackoverflow.com/q/48836955
type: Comment
type: QuestionComment
has text: Because n is zero.

http://stackoverflow.com/q/48950645
has comment: http://stackoverflow.com/comment/84910349
answer count: 1
has comment: http://stackoverflow.com/comment/84908173
has comment: http://stackoverflow.com/comment/84931722
favorite count: 0
has comment: http://stackoverflow.com/comment/84929487
has title: django-admin dbshell CommandError: You appear not to have the 'sqlite3' program installed or on your path
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84907952
tagged with: django
tagged with: python
tagged with: django-database
has comment: http://stackoverflow.com/comment/84912497
score: 1
has comment: http://stackoverflow.com/comment/84911691
has answer: http://stackoverflow.com/a/48963238
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84908613
has body: I use two sqlite databases in my django project . One for default and another for customer_data. This is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, 'customers': { 'NAME': 'customer_data', 'ENGINE': 'django.db.backends.sqlite3', 'USER': 'db2', 'PASSWORD': 'db2password' } } DATABASE_ROUTERS = ['theapp.routers.CustomerRouter',] This is my routers.py class CustomerRouter: """ A router to control all database operations on models in the auth application. """ def db_for_read(self, model, **hints): """ Attempts to read auth models go to auth_db. """ if model._meta.app_label == 'customer': return 'customer_data' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to auth_db. """ if model._meta.app_label == 'customer': return 'customer_data' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the auth app is involved. """ if obj1._meta.app_label == 'customer' or \ obj2._meta.app_label == 'customer': return True return None def allow_migrate(self, db, app_label, model_name=None, **hints): """ Make sure the auth app only appears in the 'auth_db' database. """ if app_label == 'customer': return db == 'customer_data' return None

http://stackoverflow.com/q/48904636
tagged with: dataframe
tagged with: slice
has comment: http://stackoverflow.com/comment/84815618
tagged with: pandas
has title: For a DataFrame with sorted, numeric index and columns return the tuple of index values and column names closest to the given values passed
has comment: http://stackoverflow.com/comment/84815225
has comment: http://stackoverflow.com/comment/84815262
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48905428
tagged with: python
type: AnsweredQuestion
score: 1
linked to: http://stackoverflow.com/q/36275459
upvote count: 1
type: Question
has body: I am working with a DataFrame having sorted numeric index and columns: 6 9 15 22 3 5 2 1 7 5 0 2 9 1 8 7 3 1 1 Given some values of index and column name, for example (6, 12), I would like to obtain the slice of the original DataFrame: 9 15 5 2 9 8 3 1 Or the index values, so for the same example of (6, 12), the result would be: (5, 9), (8, 15) In case the input is matching the index or column names, then the return slice should be adjusted, for example for (8, 12) the return slice should be: 9 15 8 3 1 Which could be interpreted in the index result as: (8, 9), (8, 15) And in the best case of matching index and column names, for example (8, 9) it should be: 9 8 3 Which could be interpreted in the index (to be consistent) result as: (8, 9), (8, 9)
has answer: http://stackoverflow.com/a/48905428

http://stackoverflow.com/comment/84706150
has text: So you want `20180101` to be `2018-01-01`?
comment on: http://stackoverflow.com/q/48851337
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48901412
has title: NameError: name 'MainPage' is not defined python-2.7
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48901515
type: Question
has body: Im trying to complete an exercise to learn more about google appengine with python 2.7 i have this code so far in my main.py file, but when im trying to access it via my localhost i get the following error message: NameError: name 'MainPage' is not defined I can't find where the error origins from and would appreciate any help in that regard as im fairly new to the subject. import webapp2 import jinja2 from google.appengine.api import users from google.appengine.ext import ndb import os from myuser import MyUser JINJA_ENVIRONMENT = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.dirname(__file__)), extensions=['jinja2.ext.autoescape'], autoescape=True ) class MainPage(webapp2.RequestHandler): def get(self): self.response.headers['Content-Type'] = 'text/html' url = '' url_string = '' welcome = 'Welcome back' myuser = None user = users.get_current_user() if user: url = users.create_logout_url(self.request.uri) url_string = 'logout' myuser_key = ndb.Key('MyUser', user.user_id()) myuser = myuser_key.get() if myuser == None: welcome = 'Welcome to the application' myuser = MyUser(id=user.user_id()) myuser.put() else: url = users.create_login_url(self.request.uri) url_string = 'login' template_values = { 'url' : url, 'url_string' : url_string, 'user' : user, 'welcome' : welcome, 'myuser' : muyser } template = JINJA_ENVIRONMENT.get_templaet('main.html') self.response.write(template.render(template_values)) app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True) def post(self): self.response.header['Content-Type'] = 'text/html' user = users.get_current_user() myuser_key = ndb.Key('MyUser', user.user_id()) myuser = myuser_key.get() myuser.name = self.request.get('users_name') myuser.age = int(self.request.get('users_age')) myuser.put() self.redirect('/')
has comment: http://stackoverflow.com/comment/84808165
tagged with: nameerror
score: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48901515

http://stackoverflow.com/a/48887821
score: 2
upvote count: 2
has body: Because you are inferring the confusion_matrix wrong. The matrix returned from confusion_matrix will be of the form 0 TN FP True 1 FN TP 0 1 Predicted So according to the formula for TPR, the value should be 110/ (110+11) = 0.9090...
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48887096
downvote count: 0
answers question: http://stackoverflow.com/q/48887096
type: Answer

http://stackoverflow.com/comment/84700854
score: 0
type: Comment
type: QuestionComment
has text: OK, I finally get what you're saying... Sorry, I didn't understand what you were saying until I tested your idea vs my (bad) idea using modulo to dedup in `unchunk()`. You're saying as long as there are a lot more rows than keys, then it's ok since the threads will take longer, but it'll cancel out since I require less threads anyway. Thanks for your help!
comment on: http://stackoverflow.com/q/48817008

http://stackoverflow.com/comment/84824934
type: Comment
has text: @Hamish, I've added a specific example.
type: QuestionComment
comment on: http://stackoverflow.com/q/48895975
score: 0

http://stackoverflow.com/q/48878729
has title: numpy: check for 1 every 6 element every row
accepted answer: http://stackoverflow.com/a/48879641
score: -1
type: Question
tagged with: numpy
answer count: 2
has comment: http://stackoverflow.com/comment/84761559
has answer: http://stackoverflow.com/a/48879641
possible better answer: http://stackoverflow.com/a/48880255
has comment: http://stackoverflow.com/comment/84761905
has comment: http://stackoverflow.com/comment/84761553
has body: I need to have something like this: arr = array([[1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0]]) Where each row contains 36 elements, every 6 element in a row represents a hidden row, and that hidden row needs exactly one 1, and 0 everywhere else. In other words, every entry mod 6 needs exactly one 1. This is my requirement for arr. I have a table that's going to be used to compute a "fitness" value for each row. That is, I have a table = np.array([10, 5, 4, 6, 5, 1, 6, 4, 9, 7, 3, 2, 1, 8, 3, 6, 4, 6, 5, 3, 7, 2, 1, 4, 3, 2, 5, 6, 8, 7, 7, 6, 4, 1, 3, 2]) table = table.T and I'm going to multiply each row of arr with table. The result of that multiplication, a 1x1 matrix, will be stored as the "fitness" value of that corresponding row. UNLESS the row does not fit the requirement described above, which should return 0. an example of what should be returned is result = array([5,12,13,14,20,34]) I need a way to do this but I'm too new to numpy to know how to.
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84762547
favorite count: 0
has answer: http://stackoverflow.com/a/48880255
type: AnsweredQuestion
upvote count: 0

http://stackoverflow.com/a/48837910
upvote count: 1
answers question: http://stackoverflow.com/q/48835009
downvote count: 0
score: 1
type: Answer
has body: There can be several reasons for returning a generator object instead of a list in Python. Among these are efficiency and data availability. In the case of reading a YAML stream of documents, it is less memory efficient to load all of those in memory in case you want process them one at a time with little or no data exchange between documents. It can also be more efficient in time, e.g. for someone waiting for the result of reading the first document in a stream to show up on a screen, if you load the first document, show the results and then proceed to loading the second document, etc. But the most important reasons is data availability: if you are processing a stream, that stream can still be written to and might not be complete: additional data might be added to the current YAML document in the stream, or additional documents might be added to the stream. Your file is just a (boring) edge case of a stream where the complete stream is available up front. If you have a stream based API and use generators, you can easily make it into a re-iterable list if the above efficiency are of no concern to you by putting [] around the generator. But doing the reverse (presenting a list as an generator) doesn't make it memory efficient and will have you wait for any resulting list, until the stream is closed (i.e. in general you have no information if the final ... of the last document in the stream is not going to be followed by another document). Similar processing and presenting before all data is available is done by web browser and video showing programs: A browsers gets the main page for which you provided the URL and starts displaying it, although not all image are loaded. If you have lots of images on a long page and/or a slow internet connection, you can start reading before the page is fully loaded. And some image formats support displaying of low resolution images before all data is streamed in. (This was more important in the early 90's with slow modem connections …

http://stackoverflow.com/comment/84917347
has text: That is exactly what I'm trying to say. `form.paper.data` should not be a string, it's supposed to be an object. You're trying to do `msg.attach(object.filename, 'application/octet-stream', object.read())` when your object is just a string. Strings (or 'str') don't have attributes. Please show your imported modules at the top of the code so that I can see what you're using.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48897712
type: Comment

http://stackoverflow.com/comment/113021787
type: Comment
has text: Could the model be trained in an increased way after this rewrite?
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/54258997

http://stackoverflow.com/comment/84769919
type: Comment
comment on: http://stackoverflow.com/a/48824641
type: AnswerComment
score: 0
has text: Yes @VitorCampos, you'll be able to perform all operations like normal. The only difference between an `OrderedDict` and a regular `dict` is that the order of keys is maintained (rather than a `dict` which will come back randomly if you iterate over them).

http://stackoverflow.com/q/48891714
tagged with: python
tagged with: tweepy
upvote count: 3
tagged with: twitter
has comment: http://stackoverflow.com/comment/84789351
type: Question
linked to: http://stackoverflow.com/q/47137849
downvote count: 0
has answer: http://stackoverflow.com/a/48892188
has answer: http://stackoverflow.com/a/53356730
has comment: http://stackoverflow.com/comment/84789611
has comment: http://stackoverflow.com/comment/109402208
has comment: http://stackoverflow.com/comment/84789045
has answer: http://stackoverflow.com/a/53354367
score: 3
has title: Unable to import tweepy (Python 3.7 - tweepy 3.5)
has answer: http://stackoverflow.com/a/48891828
has comment: http://stackoverflow.com/comment/84789486
has body: I'm facing a problem trying to import tweepy library in my code, I've tried to uninstall it and then install it again but I still get the same problem. This is my code (error) and command line: Thank you.
favorite count: 0
has comment: http://stackoverflow.com/comment/84789192
answer count: 5
has answer: http://stackoverflow.com/a/48892938
type: UnansweredQuestion

http://stackoverflow.com/comment/84896542
score: 0
has text: Hi @Jai, I am considering two consecutive digits. For your example, the count will be 4.
type: Comment
comment on: http://stackoverflow.com/a/48944853
type: AnswerComment

http://stackoverflow.com/q/48962555
has comment: http://stackoverflow.com/comment/84931347
tagged with: pandas
downvote count: 0
answer count: 1
favorite count: 0
has body: I scraped twitter and wanted to sort out the locations of tweets. All data is in a pandas dataframe and I'm using Python 3. I want to do some work on the location column, which looks similar to this: ['location'] Scottsdale, AZ London, UK USA (no value) Mission Viejo, CA etc... The location data is messy and I want simplify it, starting by classifying the USA as one. To do this I have a list of state codes: state_list. I am trying to replace the cells containing any state code to USA. I have found how to do this by hard coding a specific state. df.loc[df.location.str.contains('CA'), 'location'] = 'USA' Above was comparing the entire column value is equal to an item in the state_list But I'm unable to do it using state_list, I tried using isin(state_list) in place of str.contains('CA') df.loc[df.location.isin(state_list), 'location'] = 'USA' which seems to do nothing. I also attempted a for loop, with various iterations of the code below, but with no avail. for states in state_list: if df.loc[df.location.isin(state_list)]: df['location'] = 'USA' I feel like there should be a 'simplish' answer to this problem but cant find a solution and have started going round in circles now so have decided to ask. Any help much appreciated and thanks for reading. The answer is below, thanks for the help guys. pat = r', \b{}\b'.format('|'.join(state_list)) df.loc[df.location.str.contains(pat), 'location'] = 'USA' Although as Håken pointed out this might cause an *'unexpected match for CA in CANADA (for example).' see comments below answer for more info.
has comment: http://stackoverflow.com/comment/84931059
tagged with: python
has title: If a column contains a substring ( a US state) in a list (of states) change value (to USA) in a pandas df
has answer: http://stackoverflow.com/a/48962608
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48962608

http://stackoverflow.com/a/48838549
downvote count: 0
has comment: http://stackoverflow.com/comment/84699547
type: Answer
upvote count: 1
has body: import calendar print ("Welcome to my leap year program") print ("You may type any year and I will tell you if it is a leap year") count = 0 for i in range(5): count = count + i t1= int(input()) if calendar.isleap(t1): # returns true if t1 is leap year else returns false print (t1, "is a leap year.") # if test condition is true else: print (t1, "is not a leap year.") # if test condition is false I learned proper syntax and I was able to come up with this. Thanks everyone who posted suggestions on learning about for.
score: 1
answers question: http://stackoverflow.com/q/48837553

http://stackoverflow.com/q/48835298
has answer: http://stackoverflow.com/a/48841906
accepted answer: http://stackoverflow.com/a/48839650
possible better answer: http://stackoverflow.com/a/48835739
type: Question
has answer: http://stackoverflow.com/a/48835739
score: 2
favorite count: 0
has comment: http://stackoverflow.com/comment/84683344
tagged with: beautifulsoup
answer count: 3
has title: To remove all div from data extracted by web scraping
has answer: http://stackoverflow.com/a/48839650
upvote count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/84699742
downvote count: 1
type: AnsweredQuestion
has body: I wanted to remove all div from data before storing it in excel data. for example: seven_days= soup.find('div', attrs={'class':'price'}) name= seven_days.text.strip() It can remove only one div, I want something like this seven_days= soup.find_all('div', attrs={'class':'price'}) But I can't remove div start and end tag.

http://stackoverflow.com/a/48935181
score: 1
answers question: http://stackoverflow.com/q/48935143
type: AcceptedAnswer
downvote count: 0
type: Answer
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48935143
has body: You could use with open ("file_here.txt", "r") as fin, open("output.txt", "w") as fout: output = re.findall(r'(?:.*\r?\n){2}.*?random data.*', fin.read()) fout.write("\n".join(output))

deep-learning
tags question: http://stackoverflow.com/q/48830257
tags question: http://stackoverflow.com/q/48840025
tags question: http://stackoverflow.com/q/48819393
tags question: http://stackoverflow.com/q/48859378
tags question: http://stackoverflow.com/q/48878639
tags question: http://stackoverflow.com/q/48820093
tags question: http://stackoverflow.com/q/48832052
tags question: http://stackoverflow.com/q/48851439
tags question: http://stackoverflow.com/q/48805407
tags question: http://stackoverflow.com/q/48860586
tags question: http://stackoverflow.com/q/48832753
tags question: http://stackoverflow.com/q/48946706
tags question: http://stackoverflow.com/q/48865055
tags question: http://stackoverflow.com/q/48888159
tags question: http://stackoverflow.com/q/48941208
tags question: http://stackoverflow.com/q/48872738
tags question: http://stackoverflow.com/q/48912038
tags question: http://stackoverflow.com/q/48840499
tags question: http://stackoverflow.com/q/48890758
tags question: http://stackoverflow.com/q/48874635
tags question: http://stackoverflow.com/q/48942865
tags question: http://stackoverflow.com/q/48906570
tags question: http://stackoverflow.com/q/48879228
tags question: http://stackoverflow.com/q/48812613
tags question: http://stackoverflow.com/q/48921326
type: Tag
tags question: http://stackoverflow.com/q/48827687
tags question: http://stackoverflow.com/q/48910821
tags question: http://stackoverflow.com/q/48888007
tags question: http://stackoverflow.com/q/48880922
tags question: http://stackoverflow.com/q/48955015
tags question: http://stackoverflow.com/q/48835595
tags question: http://stackoverflow.com/q/48873387
tags question: http://stackoverflow.com/q/48831585
tags question: http://stackoverflow.com/q/48958765
tag name: deep-learning
tags question: http://stackoverflow.com/q/48829294
tags question: http://stackoverflow.com/q/48843521
tags question: http://stackoverflow.com/q/48878554
tags question: http://stackoverflow.com/q/48893528
tags question: http://stackoverflow.com/q/48849715
tags question: http://stackoverflow.com/q/48819022
tags question: http://stackoverflow.com/q/48900949
tags question: http://stackoverflow.com/q/48816873
tags question: http://stackoverflow.com/q/48836502
tags question: http://stackoverflow.com/q/48917447

http://stackoverflow.com/q/48947494
tagged with: python
tagged with: pycharm
type: UnansweredQuestion
upvote count: 59
has answer: http://stackoverflow.com/a/48948131
has body: I want to be able to use the paraview.simple library in PyCharm. I already have paraview installed in my computer. This package cannot be installed with pip and there are no .whl files as far as I can tell. The website docs recommend that the directory containing all the python files be added to PYTHONPATH. How do I add the relevant folder in PYTHONPATH on my PyCharm session, and keep it there by default, such that when I close out and reopen the paraview.simple library is still available?
score: 59
answer count: 6
type: Question
tagged with: pythonpath
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84901333
has answer: http://stackoverflow.com/a/67568828
has answer: http://stackoverflow.com/a/48947563
has answer: http://stackoverflow.com/a/65503508
has title: Add directory to Python path in PyCharm?
has answer: http://stackoverflow.com/a/55278260
has answer: http://stackoverflow.com/a/76276542

http://stackoverflow.com/q/48948415
has comment: http://stackoverflow.com/comment/84907067
tagged with: celerybeat
has comment: http://stackoverflow.com/comment/84906459
tagged with: django
tagged with: python
tagged with: celery
score: 2
type: AnsweredQuestion
downvote count: 0
type: Question
upvote count: 2
has body: I am trying to setup a task to run every ten seconds.Using Celery Beat. I am using: Django==1.11.3 celery==4.1.0 django-celery-beat==1.1.1 django-celery-results==1.0.1 It is giving me the following error: Received unregistered task of type 'operations.tasks.message' I am new to Celery, I have tried numerous solutions and cannot seem to find a solution,would appreciate the help settings.py CELERY_BROKER_URL = 'pyamqp://guest@localhost//' CELERY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Africa/Johannesburg' CELERY_BEAT_SCHEDULE = { 'message': { 'task': 'operations.tasks.message', 'schedule': 10.0 } } celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'nodiso.settings') app = Celery('nodiso') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) __init__.py from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ = ['celery_app'] task.py from __future__ import absolute_import, unicode_literals from celery import shared_task from operations import models from .celery import periodic_task @task def message(): t = models.Celerytest.objects.create(Message='Hello World') t.save() files structure proj- proj- __init__.py settings.py- celery.py- app- tasks.…
accepted answer: http://stackoverflow.com/a/48956976
has title: Celery 4.1 periodic tasks error
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48956976

http://stackoverflow.com/comment/84630938
type: Comment
has text: @askpython Sorry, I did not understand that. What I meant was just that `d`, when printed, will look a bit different that what I've shown in the answer, including information that it's a `defaultdict` and what function is used for creating the default values. It still behaves like an ordinary `dict` for all practical purposes, though.
comment on: http://stackoverflow.com/a/48810555
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84736828
type: Comment
type: QuestionComment
has text: seek set up pointer at specific position it's used when I need to write to file from that pointer but not exactly when i want to read.
score: 0
comment on: http://stackoverflow.com/q/48866806

http://stackoverflow.com/a/48850705
upvote count: 1
has comment: http://stackoverflow.com/comment/84705157
has body: As Ofek pointed out, using a combination of requests/urllib and bs4 would be a better option for scraping. In order to get the text you are interested in, you could do something like this: import requests from bs4 import BeautifulSoup page = requests.get("https://twitter.com/FoxNews/status/964981093127655424") soup = BeautifulSoup(page.content, "html.parser") tweet = soup.select_one(".js-tweet-text-container .TweetTextSize--jumbo") print(tweet.get_text()) Your output would look like: 'On Twitter, former President @BillClinton called for a renewal of the Assault Weapons Ban.pic.twitter.com/hPaFyhGSfd' Now, let's break down what we did. First, requests makes a GET request to the Twitter server, and the content of the input URL is saved as a Response object in page. We then proceed to create a BeautifulSoup object using page. And to find the tweet text, we use CSS selectors. This is a simple scraping job, and if any of it doesn't make sense to you, I suggest you go through some tutorials. You could start with this article, which will teach you the basics of web scraping and help you get started. Hope this helps!
answers question: http://stackoverflow.com/q/48850545
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/q/48870618
score: -1
has answer: http://stackoverflow.com/a/48870775
answer count: 2
has title: How to compare two arrarys and create new array with multiple conditional statement?
upvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48870811
tagged with: python
accepted answer: http://stackoverflow.com/a/48870775
has comment: http://stackoverflow.com/comment/84745978
possible better answer: http://stackoverflow.com/a/48870811
has comment: http://stackoverflow.com/comment/84748613
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84745206
has body: I have a two arrays x and y with same dimensions. I want to do multiple comparisons (or operator) values in these arrays and generate a new array with same dimensions. The new array should have the values assigned by me. Here is the little demonstration of what I am trying to do:- In [1]: import numpy In [2]: import numpy as np In [3]: x = np.array([5, 2, 3, 1, 4, 5]) In [4]: y = np.array([2, 3, 3, 8, 8, 6]) In [5]: result_array = [y &gt; 3] or [x &lt; 5] In [6]: print(result_array) [array([False, False, False, True, True, True], dtype=bool)] I am able to compare multiple statement and result in new array. However, I would like to replace the True with value 10. So when I try this line, it gives me an error:- result_array = 10 if [y &gt; 3] or [x &lt; 5]: File "&lt;ipython-input-21-780bf095bc56&gt;", line 1 result_array = 10 if [y &gt; 3] or [x &lt; 5]: ^ SyntaxError: invalid syntax What I am expecting is:- [array([False, False, False, 10, 10, 10], dtype=bool)] Any help is appreciated
has comment: http://stackoverflow.com/comment/84745287
downvote count: 1
type: Question
tagged with: numpy
has comment: http://stackoverflow.com/comment/84745135

http://stackoverflow.com/comment/84913453
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48937703
score: 1
has text: You should consider joining [Build-Scripts](https://github.com/noloader/Build-Scripts) as a collaborator. We seem to have a lot of overlap. The scripts have been around for a while so they are fairly mature. They are also cross-platform. I think it would be a lot easier for you to add Python to the build scripts as opposed to reinventing and repairing the the wheel. For example, the missing runpaths and dtags, and missing options to OpenSSL and Git.

http://stackoverflow.com/q/48896762
score: 1
upvote count: 1
tagged with: tensorflow
type: Question
type: AnsweredQuestion
has body: Say I received csv dataset files with filenames of the form index_channel.csv where index is the index of the example (running from 1 to 10000) and channel is the index of the channel (running from 1 to 5). So 7_3.csv is the 3rd channel of the 7th example. I want to load all these csv files and concatenate the channels to get the correct tensors as my data set. I am missing references to functions which will enable me to do this. Below is the code I have so far. When I get to running it, it complains that TypeError: expected str, bytes or os.PathLike object, not Tensor. I am guessing it is trying to evaluate the expression instead of only after sess.run() has been called, but not sure how to circumvent that. from __future__ import absolute_import from __future__ import division from __future__ import print_function # Imports import numpy as np import tensorflow as tf from tensorflow.contrib.data import Dataset, Iterator def main(unused_argv): train_imgs = tf.constant(["1","2","3"]) #just trying the 3 first examples tr_data = Dataset.from_tensor_slices((train_imgs)) tr_data = tr_data.map(input_parser) # create TensorFlow Iterator object iterator = Iterator.from_structure(tr_data.output_types, tr_data.output_shapes) next_element = iterator.get_next() training_init_op = iterator.make_initializer(tr_data) with tf.Session() as sess: # initialize the iterator on the training data sess.run(training_init_op) # get each element of the training dataset until the end is reached while True: try: elem = sess.run(next_element) print(elem) except tf.errors.OutOfRangeError: print("End of training dataset.") break def input_parser(index): dic={} for d in range(1,6): a=np.loadtxt(open("./data_for_tf/" + index +"_M"+str(d)+".csv", "rb"), delimiter=",", skiprows=1) dic[d]=tf.convert_to_tensor(a, dtype=tf.float32) metric=np.stack((dic[1],dic[2],dic[3])) return metric Sorry, I am a newbie at TF. My question seems trivial but none of the examples I found by googling answered my questions.
tagged with: file-io
has answer: http://stackoverflow.com/a/48897620
answer count: 1
downvote count: 0
favorite count: 0
has title: How to use the Tensorflow Dataset API to read files with different names without evaluating the filename string
tagged with: python
accepted answer: http://stackoverflow.com/a/48897620

http://stackoverflow.com/q/48808636
has comment: http://stackoverflow.com/comment/84620383
has comment: http://stackoverflow.com/comment/84620416
has title: Python datetime.strftime and datetime.strptime
has comment: http://stackoverflow.com/comment/84620412
tagged with: strptime
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84620401
type: UnansweredQuestion
tagged with: datetime
tagged with: python
score: 2
answer count: 0
upvote count: 2
type: Question
has comment: http://stackoverflow.com/comment/84642230
has body: I was reading a chapter on datetime from 'Effective Python' and stumbled upon this strange behavior of datetime.strptime: it raises a ValueError on the very string formatted with datetime.strftime using the same format. if I remove the timezone component then it parses just fine. Anyone has an explanation? Thanks in advance! code here: from datetime import datetime import pytz TIME_FORMAT = '%Y-%m-%d %H:%M:%S %Z' pacific = pytz.timezone('US/Pacific') time = datetime.now().astimezone(pacific) time_str = time.strftime(TIME_FORMAT) # &gt;&gt;&gt; '2018-02-15 05:20:50 PST' # next line: ValueError: time data '2018-02-15 05:30:34 PST' does not match format '%Y-%m-%d %H:%M:%S %Z' time_parsed = datetime.strptime(time_str, TIME_FORMAT)

http://stackoverflow.com/comment/106322211
comment on: http://stackoverflow.com/a/58731540
type: AnswerComment
has text: When you do `data = blob.download_blob()`, the contents of the blob will be in `data`, you don't need to write to a file.
type: Comment
score: 3

http://stackoverflow.com/comment/96465506
type: Comment
has text: Why couldn't the callee simply call `contiguous()` by itself?
comment on: http://stackoverflow.com/a/52229694
score: 4
type: AnswerComment

http://stackoverflow.com/comment/85066473
type: Comment
has text: send.config (command = answer2) root.bind ("<Return>", lambda event: answer2 ()) return answer1
type: AnswerComment
comment on: http://stackoverflow.com/a/48812382
score: 0

http://stackoverflow.com/q/48864407
has body: This is my experimenting code: def settingValues(): hi = "Hello" name = "Jake" isTrue = True def callingValues(): print(hi, name, isTrue) settingValues() callingValues() Obviously this emmits an error... Is there an easy way to transfer the variables throughout the two functions? What I will be using this for requires setting quite a lot of variables... so I cant use 'global' for all of them. :)
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84732019
tagged with: python
has title: How to use variables from a function in a different function
score: -5
has comment: http://stackoverflow.com/comment/84732167
has comment: http://stackoverflow.com/comment/84732069
has answer: http://stackoverflow.com/a/48864478
type: Question
downvote count: 5
linked to: http://stackoverflow.com/q/19326004
answer count: 2
tagged with: function
upvote count: 0
has answer: http://stackoverflow.com/a/48864471
has comment: http://stackoverflow.com/comment/84732008
tagged with: variables
has comment: http://stackoverflow.com/comment/84732002
favorite count: 0

http://stackoverflow.com/q/48885246
type: AnsweredQuestion
favorite count: 0
accepted answer: http://stackoverflow.com/a/48885590
type: Question
has body: Problem: Let's say I have two tensors, a and b. Both have the same shape: [?, 10, 4096]. How do I zip the two in a manner that the resulting tensor has a shape of [?, 20, 4096], but also such that the ith element of a comes right before the ith element of b. Example with lists: a = [1, 3, 5] b = [2, 4, 6] and now I want a tensor that looks like [1, 2, 3, 4, 5, 6] and not [1, 3, 5, 2, 4, 6], which is what would happen if I were to tf.stack the two and then use tf.reshape, right?. Or perhaps a more general question would be, how do you know in what order tf.reshape reshapes a tensor?
has title: Zipping and reshaping in Tensorflow
tagged with: python
score: 0
upvote count: 1
answer count: 1
downvote count: 1
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48885590

http://stackoverflow.com/a/48864960
has comment: http://stackoverflow.com/comment/84733332
upvote count: 1
answers question: http://stackoverflow.com/q/48864857
has body: change your form &lt;form role="form" action="add_support_user/" method="post"&gt; to this &lt;form role="form" action="" method="post"&gt;
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48864857
type: Answer
score: 1

http://stackoverflow.com/comment/84883028
type: AnswerComment
comment on: http://stackoverflow.com/a/48846888
type: Comment
has text: I suppose the fundamental question here is: how do I update an existing method rather than just create a new instance of that method?
score: 0

http://stackoverflow.com/q/48833211
score: 1
tagged with: matplotlib
type: Question
has body: I am plotting 2 shapefiles (converted to geopandas dataframe) using this. But there is too much whitespace. How can I reduce it to fill the box more with the map? The xlim and ylim doesn't seem to have any impact f, ax = plt.subplots(1, figsize=(8, 8)) polydatx.plot(ax = ax, column = 'Elev_Avg', cmap='OrRd', scheme='quantiles') segdatx.plot(ax = ax) ax.grid(False) ax.set_ylim(47, 47.3) plt.axis('equal');
upvote count: 1
tagged with: geopandas
tagged with: geospatial
answer count: 1
favorite count: 0
has title: How can I reduce whitespace in Python plot?
tagged with: python
has answer: http://stackoverflow.com/a/48833352
accepted answer: http://stackoverflow.com/a/48833352
type: AnsweredQuestion
downvote count: 0

http://stackoverflow.com/comment/84663202
type: Comment
has text: I'm going to creater my own exporter instead overwriting it. https://stackoverflow.com/questions/33290876/how-to-create-custom-scrapy-item-exporter
comment on: http://stackoverflow.com/a/48828894
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84919973
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48956379
has text: That was a really clever way to use `value_counts()`. Thanks :)

http://stackoverflow.com/q/48855441
downvote count: 2
tagged with: count
tagged with: python
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48855541
score: 1
has comment: http://stackoverflow.com/comment/84714834
type: Question
possible better answer: http://stackoverflow.com/a/48856006
has comment: http://stackoverflow.com/comment/84714814
has answer: http://stackoverflow.com/a/48856006
favorite count: 0
answer count: 3
tagged with: pandas
has answer: http://stackoverflow.com/a/48855541
has answer: http://stackoverflow.com/a/64167879
has comment: http://stackoverflow.com/comment/84714419
has body: I have a large dataset with columns labelled from 1 - 65 (among other titled columns), and want to find how many of the columns, per row, have a string (of any value) in them. For example, if all rows 1 - 65 are filled, the count should be 65 in this particular row, if only 10 are filled then the count should be 10. Is there any easy way to do this? I'm currently using the following code, which is taking very long as there are a large number of rows. array = pd.read_csv(csvlocation, encoding = "ISO-8859-1") for i in range (0, lengthofarray) for k in range(1,66): if array[k][i]!="": array["count"][i]=array["count"][i]+1
has title: pandas count number of filled cells within row
upvote count: 3

http://stackoverflow.com/a/48953314
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/115450131
score: 6
accepted answer of: http://stackoverflow.com/q/48953313
answers question: http://stackoverflow.com/q/48953313
type: AcceptedAnswer
downvote count: 0
has body: This will effectively give identical values for the first / last values since the window is identical for them. So there's no need for a rolling window to bound at the start or end just to fill these numbers. Instead: s2 = s.rolling(window, center=True).median() s2.iloc[-window//2:] = s2.iloc[-window//2] s2.iloc[:window//2] = s2.iloc[window//2] print (s2) 0 2.0 1 2.0 2 2.0 3 3.0 4 4.0 5 4.0 6 4.0 dtype: float64 Sidenote Another possibility to fill in values is setting min_periods=window//2 in the given case (otherwise the default is the window width, which is why there appears NaN in the first place). The first and last values still have 3 valid values to consider. This may be a preferred strategy in many cases. print (s.rolling(window, min_periods=(window//2), center=True).median()) 0 2.0 1 2.0 2 2.0 3 3.0 4 4.0 5 4.5 6 5.0 dtype: float64

http://stackoverflow.com/a/48866996
answers question: http://stackoverflow.com/q/48866770
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48866770
type: Answer
has body: Ok, I found an answer. One can specifically give two points to the plot function. fig2 = plt.figure() shapeplot1 = fig2.add_subplot(111) coordinates = [[1,2], [10,11], [12,12], [14,15]] data = np.array(coordinates) x1, y1 = data.T shapeplot1.scatter(x1,y1, color='red') shapeplot1.plot([coordinates[0][0], coordinates[1][0]], [coordinates[0][1], coordinates[1][1]]) shapeplot1.plot([coordinates[2][0], coordinates[3][0]], [coordinates[2][1], coordinates[3][1]]) plt.show()

http://stackoverflow.com/q/48845256
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: riot-games-api
has comment: http://stackoverflow.com/comment/84694951
has title: Multiple python nested for loops, possibly recursively traverse lists. python 3
accepted answer: http://stackoverflow.com/a/48845472
tagged with: python
type: AnsweredQuestion
upvote count: 0
has answer: http://stackoverflow.com/a/48845472
tagged with: http://stackoverflow.com/tag/json
type: Question
has body: I am trying to match the first item in participantId to the first list in str(each['participantId']). And then the second item in participantId to second list, and so on. participantId = ['2','5','7','4','10','9','2'] each['participantId'] = [[1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10]] So I want to use a for loop on participantId but have just the first item in the list do an if statement with the first list, then the second item in participantId do an if statement with the second list. As of Now my code just matches all participantId's with each list. here is a snippet of my code: for each in json['participants']: for x in str(each['participantId']): print(x) for i in participantId: if x == i: kills = each['stats']['deaths'] print('kills') print(kills) I have looked at recursively traverse lists as a solution but I cant seem to make that work. I'm very new to python and coding so maybe there is some function im missing.
score: -2
downvote count: 2
has comment: http://stackoverflow.com/comment/84695071

http://stackoverflow.com/comment/84746993
type: QuestionComment
score: 1
has text: are the timestamps unique in each dataframe, and do you want to match rows where the delta = 0?
comment on: http://stackoverflow.com/q/48871617
type: Comment

http://stackoverflow.com/a/48854721
has body: You are quite close. You can access the href by accessing the builtin __getitem__ method of the results returned from finding the a attributes: print(titles.find('a')['href'])
answers question: http://stackoverflow.com/q/48854663
score: 0
type: Answer

http://stackoverflow.com/comment/84720096
score: 0
has text: yes i had read that and it says "For python, you'll read a zero length string" but when I read the string that is received to check if it is empty, it gives error so IDK which is correct.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48858177

http://stackoverflow.com/comment/84820082
has text: I still can not find a solution, can you help me please? thank you
comment on: http://stackoverflow.com/a/48872095
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84886182
type: QuestionComment
comment on: http://stackoverflow.com/q/48939473
has text: @BUZZY The top function is not outputting the correct answer.
score: 0
type: Comment

http://stackoverflow.com/a/48847034
type: Answer
score: 2
upvote count: 2
has body: Try this, loops until you don't enter a name, increments the current key each iteration: dct = {} i = 1 while(True): name = input("Please enter a name: ") if name == "": break age = input("Please enter an age: ") dct[i] = {"name": name, "age": age} i += 1 print(dct) Example input/output: Please enter a name: Chris Please enter an age: 23 Please enter a name: Daryll Please enter an age: 22 Please enter a name: {1: {'name': 'Chris', 'age': '23'}, 2: {'name': 'Daryll', 'age': '22'}}
downvote count: 0
answers question: http://stackoverflow.com/q/48846997

http://stackoverflow.com/a/48939075
score: 2
upvote count: 2
has body: I think it's not a bug. The size method is not always equals to number of rows. Let's look your case: import pandas as pd crimes_df = pd.read_csv("CrimeDataWithSquare.csv") crimes_df.shape #(476798, 13) crimes_df.shape[0] * crimes_df.shape[1] #6198374 crimes_df.size #6198374 len(crimes_df) #476798 What documentation says about the size method? number of elements in the NDFrame Generally, Dataframe has 2 dimensions (X rows by Y columns). Thus, the dataframe size method returns X times Y (number of elements in it). What if you have one single column? crimes_df2 = crimes_df.iloc[:, 0] len(crimes_df2) == crimes_df2.size #True It's the result you were expecting for.
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48890702
answers question: http://stackoverflow.com/q/48890702
type: Answer

http://stackoverflow.com/a/48910611
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48910416
type: Answer
answers question: http://stackoverflow.com/q/48910416
score: 1
has body: since you were getting a FailedPreconditionError: Attempting to use uninitialized value, I Initialising the global variables and that made it work. import tensorflow as tf import numpy as np tf.InteractiveSession() batch_size = 3 seqlen = 5 nfeats = 3 mini_batch = np.random.randint(1,10, (batch_size, seqlen, nfeats)) d = dict((n, t.eval()) for n,t in enumerate(tf.unstack(mini_batch, 3))) d0 = tf.convert_to_tensor(d[0],dtype=tf.int32) d0 = tf.reshape(d0, [seqlen, batch_size]) d0_lin = tf.layers.dense(inputs=d0, units=100) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(d0_lin.eval()) output: [[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]]
upvote count: 1

http://stackoverflow.com/comment/84681252
type: QuestionComment
score: 2
has text: Simple speedups ideas: 1) use symmetry as the result of i, j is the same as for j, i. i.e. run i on all items but j only from first to i-th item. 2) Normalize all items in advance to prevent normalization inside the loop.
comment on: http://stackoverflow.com/q/48838346
type: Comment

http://stackoverflow.com/comment/84666701
has text: I know I have misunderstood how mocking works. I'm just not sure 'where' I should be mocking.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48812097

http://stackoverflow.com/q/48953515
score: 0
has comment: http://stackoverflow.com/comment/84916841
type: UnansweredQuestion
tagged with: python
has title: Node_color not matching with nodelist in networkx graph
answer count: 0
tagged with: nodes
tagged with: networkx
type: Question
tagged with: graph
has body: I am making graphs with networkx. My nodes are book titles, each of which has an attribute for the race of the author. I am coloring the nodes according to race, with the following code: node_color = [] for node in C.nodes(data=True): try: if node[1]['RACE'] == 0.0: node_color.append('blue') elif node[1]['RACE'] == 1.0: node_color.append('red') elif node[1]['RACE'] == 2.0: node_color.append('green') except(TypeError, KeyError): node_color.append('brown') The dictionary of the nodes and attributes is working correctly (writers are correctly matched with race), but the nodes are incorrectly colored in the end (Toni Morrison's The Bluest Eye is colored blue, ie, instead of red). Here is my drawing code: print (nx.draw_random(C, node_color=node_color, labels=labelDict,node_size=[v * 300 for v in eigDict.values()], width = .02, font_size=9)) I'm not sure why node_color=node_color is not correctly mapping. My only thought is that I also create a dictionary of eigenvector centrality for the size of the nodes. Maybe this changes the order of the nodelist when I graph C? import operator eigDict = nx.eigenvector_centrality(C) sorted_eigDict = sorted(eigDict.items(), key=operator.itemgetter(1), reverse=True) How can I get the nodes correctly colored?
has comment: http://stackoverflow.com/comment/84928215
has comment: http://stackoverflow.com/comment/84920060

http://stackoverflow.com/comment/84750114
comment on: http://stackoverflow.com/q/48872847
has text: Possible duplicate of [Calling an external command in Python](https://stackoverflow.com/questions/89228/calling-an-external-command-in-python)
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48953548
has body: They are actually very different. nn.batch_normalization performs the basic operation (i.e. a simple normalization) layers.batch_normalization is a batchnorm "layer", i.e. it takes care of setting up the trainable parameters etc. At the end of the day, it is a wrapper around nn.batch_normalization. Chances are this is the one you want to use, unless you want to take care of setting up variables etc. yourself. It's similar to the difference between nn.conv2d and layers.conv2d, for example. As for the contrib version, I can't say for sure, but it seems to me like an experimental version with some extra parameters not available in the "regular" layers one.
score: 3
upvote count: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48949318
answers question: http://stackoverflow.com/q/48949318
type: Answer

http://stackoverflow.com/comment/84723509
comment on: http://stackoverflow.com/a/48860023
score: 0
type: AnswerComment
type: Comment
has text: @Majeteosorio, I've tested this code (kept it running till the end) and it downloaded all the images without any errors. So, you can use this code as it is.

http://stackoverflow.com/comment/84668016
type: AnswerComment
comment on: http://stackoverflow.com/a/48831849
score: 0
type: Comment
has text: And why not...?

http://stackoverflow.com/q/48864655
tagged with: desktop-application
has comment: http://stackoverflow.com/comment/84733157
has comment: http://stackoverflow.com/comment/84735830
has comment: http://stackoverflow.com/comment/84736641
has comment: http://stackoverflow.com/comment/84733063
has comment: http://stackoverflow.com/comment/84737863
score: 0
has comment: http://stackoverflow.com/comment/84737313
tagged with: pyqt
has comment: http://stackoverflow.com/comment/84734506
answer count: 1
has comment: http://stackoverflow.com/comment/84737234
has comment: http://stackoverflow.com/comment/84737531
has answer: http://stackoverflow.com/a/48867654
has title: Proper Save As function in Python
tagged with: python
has comment: http://stackoverflow.com/comment/84736897
has comment: http://stackoverflow.com/comment/84733228
has comment: http://stackoverflow.com/comment/84733490
has comment: http://stackoverflow.com/comment/84732649
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84736154
has comment: http://stackoverflow.com/comment/84736180
has comment: http://stackoverflow.com/comment/84737465
type: Question
accepted answer: http://stackoverflow.com/a/48867654
has body: I have a default Save As function bound to a button click, that calls a modal window. Also, I have a function, that saves needed arrays as a .xlsx file. self.data_processing.clicked.connect(self.process) def process(self): sample = pd.read_excel(self.fileName) list_of_index = [] for i in range(len(sample.columns)): sample2 = sample.iloc[:, lambda sample: [i]] sample2 = sample2.columns[0] list_of_index.append(sample2) list_of_index ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... Area where all the data is computed ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... workbook = xlsxwriter.Workbook('Sample.xlsx') worksheet1 = workbook.add_worksheet() worksheet2 = workbook.add_worksheet() worksheet3 = workbook.add_worksheet() worksheet4 = workbook.add_worksheet() row = 0 for col, data in enumerate(fulllist): worksheet1.write_column(row, col, data) for col, data in enumerate(fulllist_percent): worksheet2.write_column(row, col, data) for col, data in enumerate(fulllist_click): worksheet3.write_column(row, col, data) for col, data in enumerate(additional_info): worksheet4.write_column(row, col, data) workbook.close() Basically, what I'm asking is: how to insert xlsx writer into saveFile(), so that my arrays would be saved as xlsx, using default saveAs window My UI code from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(802, 996) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.dataChoose_label = QtWidgets.QLabel(self.centralwidget) self.dataChoose_label.setGeometry(QtCore.QRect(20, 10, 211, 31)) font = QtGui.QFont() font.setPointSize(13) self.dataChoose_label.setFont(font) self.dataChoose_label.setObjectName("dataChoose_label") self.data_processing = QtWidgets.QPushButton(self.centralwidget) self.data_processing.setGeometry(QtCore.QRect(640, 50, 141, 61)) self.data_proces…
has comment: http://stackoverflow.com/comment/84736813

http://stackoverflow.com/q/48949604
has comment: http://stackoverflow.com/comment/84905560
has answer: http://stackoverflow.com/a/48949919
accepted answer: http://stackoverflow.com/a/48949919
downvote count: 1
type: Question
possible better answer: http://stackoverflow.com/a/48949852
has comment: http://stackoverflow.com/comment/84905671
has answer: http://stackoverflow.com/a/48949732
score: 9
has comment: http://stackoverflow.com/comment/84905626
has title: Regex - Replace \\n and \n in string by but not \\\\n
favorite count: 0
has answer: http://stackoverflow.com/a/48949852
upvote count: 10
has body: I am trying to replace all \\n and \n from a string by &lt;br&gt; but I dont want the \\\\n to be replaced. Im trying with the following expression using negative lookbehind but it does not return the correct result because all the "n" and "\" are replaced: import re string = "this is a sample\\nstring\\\\ncontaining\nall cases\n\\n\n!" re.sub(r"(?&lt;!\\)([\\n\n]+)", r"&lt;br&gt;", string) &gt;&gt;'this is a sample&lt;br&gt;stri&lt;br&gt;g&lt;br&gt;co&lt;br&gt;tai&lt;br&gt;i&lt;br&gt;g&lt;br&gt;all cases&lt;br&gt;!' expected output "this is a sample&lt;br&gt;string\\\\ncontaining&lt;br&gt;all cases&lt;br&gt;&lt;br&gt;&lt;br&gt;!"
tagged with: python
tagged with: regex
answer count: 4
has answer: http://stackoverflow.com/a/48949758
type: AnsweredQuestion

http://stackoverflow.com/comment/84720181
type: QuestionComment
has text: Only show the relevant parts of code. Remove all the comments at the top, including your name
score: 1
comment on: http://stackoverflow.com/q/48858234
type: Comment

http://stackoverflow.com/comment/84629434
comment on: http://stackoverflow.com/q/48812559
score: 0
type: QuestionComment
has text: Parse the regex's to create a list of permutations, then permutate.
type: Comment

http://stackoverflow.com/comment/84797931
has text: Your traceback looks inconsistent. You have `from myapp.core.templatetags` which does not match `from myapp.core.templatetags.` Using made up names makes it trickier to help, as you may be hiding the real problem. Please show the full traceback. Which file is your import `from myapp.core.templatetags.customised_template_tags` in?
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48896000
type: QuestionComment

http://stackoverflow.com/comment/84694144
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48844563
has text: *"it does not print anything."* - why should it? There is no output statement anywhere in the code you've shown.
type: Comment

http://stackoverflow.com/a/48865788
accepted answer of: http://stackoverflow.com/q/48811239
upvote count: 4
answers question: http://stackoverflow.com/q/48811239
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can do it in this way: aliasForC = aliased(C) # And then: join(aliasForC, aliasForC.firstId == A.firstId ) For All statement, you can use all_()
score: 4

http://stackoverflow.com/comment/84880376
has text: @Animamorta why it bothers you to use temp vars in the first place? to settle this question, the goal should be fix this misunderstanding.
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48936533

http://stackoverflow.com/a/48825274
has comment: http://stackoverflow.com/comment/84655217
score: 3
has comment: http://stackoverflow.com/comment/84655053
has comment: http://stackoverflow.com/comment/84655161
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48825078
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/48825078
has comment: http://stackoverflow.com/comment/84655101
has body: Source DF: In [27]: df Out[27]: start end 0 1 2 1 4 7 2 12 15 3 32 36 4 38 41 In [28]: threshold = 10 Vectorized solution: In [31]: (df.groupby(df['start'].sub(df['end'].shift()).ge(threshold).cumsum()) ...: .agg({'start':'first','end':'last'})) ...: Out[31]: start end 0 1 15 1 32 41 Explanation: In [32]: df['start'].sub(df['end'].shift()) Out[32]: 0 NaN 1 2.0 2 5.0 3 17.0 4 2.0 dtype: float64 In [33]: df['start'].sub(df['end'].shift()).ge(threshold) Out[33]: 0 False 1 False 2 False 3 True 4 False dtype: bool In [34]: df['start'].sub(df['end'].shift()).ge(threshold).cumsum() Out[34]: 0 0 1 0 2 0 3 1 4 1 dtype: int32

http://stackoverflow.com/q/48931254
has title: Relative import in Python 3.6
type: Question
has comment: http://stackoverflow.com/comment/110894444
has comment: http://stackoverflow.com/comment/84870782
accepted answer: http://stackoverflow.com/a/48932151
has comment: http://stackoverflow.com/comment/84870092
tagged with: python-import
linked to: http://stackoverflow.com/q/28400690
linked to: http://stackoverflow.com/q/14132789
answer count: 1
tagged with: relative-path
tagged with: python-3.x
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48932151
score: 0
has body: I want to use relative import in Python 3. My project: main_folder - __init__.py - run.py - tools.py I want to have in run.py (MyClass declared in __init__.py): from . import MyClass And in run.py: from .tools import my_func An ImportError is raise. Alternatively, with absolute import, debugging in PyCharm does not work and the library takes from installed packages, not my directory. I know one way, but it is terrible: sys.path.append(os.path.dirname(os.path.realpath(__file__))) How to use this import in my project?

http://stackoverflow.com/q/48907773
downvote count: 0
has title: Getting refresh_token with lepture/authlib
tagged with: oauth-2.0
type: Question
has body: I'm using Authlib, and attempting to get a refresh_token from a Hydra server. I have the following code: from authlib.client import OAuth2Session client_id = "my-client" client_secret = "client secret" token_url = "https://myhydraserver/token" scope = 'openid email profile offline' session = OAuth2Session(client_id, client_secret, scope=scope) token = session.fetch_access_token(token_url) print(token) This prints out {'access_token': 'the-token', 'expires_in': 3599, 'scope': '', 'token_type': 'bearer', 'expires_at': 1519224804} From the docs, I see that there's a function to get an access token from a refresh_token, but can't find a way to get a refresh_token in the first place. How would I go about getting a refresh_token? Hydra's configured with: --grant-types authorization_code,refresh_token,client_credentials,implicit --response-types token,code,id_token which should hand out refresh_tokens.
linked to: http://stackoverflow.com/q/51305430
upvote count: 2
answer count: 1
accepted answer: http://stackoverflow.com/a/48920198
favorite count: 0
tagged with: openid-connect
tagged with: authlib
tagged with: python
has answer: http://stackoverflow.com/a/48920198
type: AnsweredQuestion
score: 2

http://stackoverflow.com/q/48928944
tagged with: python
answer count: 3
has answer: http://stackoverflow.com/a/48929178
has body: I have these two 1d arrays A = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] and its label L = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; where L[i] is the label of A[i]. Objective : I need to randomly shuffle both the 1d arrays in such a way that their labels stay in the same index. e.g: After shuffle: A= [2, 4, 9, 1, 3, 6, 0, 7, 5] then L= [7, 5, 0, 8, 6, 3, 9, 2, 4], A[i] and L[i] should remain same as the original one. I was thinking of concatenating the above two 1d arrays into a single 2d array and reshuffle it, then again separate the two 1d arrays. It's not working. And I am stuck at reshuffle. Below is the code that I tried import numpy as np import random # initializing the contents A = np.arange(0,10) length= len(A) print length print A labels = np.zeros(10) for index in range(length): labels[index] = A[length-index-1] print labels # end, contents ready combine = [] combine.append([A, labels]) print combine random.shuffle(combine) print "After shuffle" print combine
tagged with: numpy
tagged with: arrays
has title: concatenate two 1d array into one 2d array and again break it after reshuffle in python
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/26194389
has answer: http://stackoverflow.com/a/48929042
tagged with: python-2.7
score: 2
has answer: http://stackoverflow.com/a/48941581
downvote count: 0
favorite count: 0
type: Question
upvote count: 2
linked to: http://stackoverflow.com/q/19339

http://stackoverflow.com/a/48938209
has comment: http://stackoverflow.com/comment/84883639
has body: Not completely sure this is what you're looking for, but I think you want to get the index from inside the loop. The main ways to do this would be loop using the index, e.g. for i in range(0,255): and then index into the array iterate using enumerate, which returns an index as well as value in a collection use the index method I think the easiest option for you will be the index method. for row in CrpImg: for cell in row: print(np.nonzero) if (cell == [136,136,0,255]).all: print(CrpImg.index(row), row.index(cell)) Note that this is going to give you the index inside your crop rather than the full image. You can either adjust (by adding 14 and 12), or you can iterate over the full image.
score: 1
answers question: http://stackoverflow.com/q/48938086
has comment: http://stackoverflow.com/comment/84884757
has comment: http://stackoverflow.com/comment/84883636
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84883902
upvote count: 1

http://stackoverflow.com/comment/84646576
score: 1
comment on: http://stackoverflow.com/q/48821533
type: Comment
type: QuestionComment
has text: Construct your `result` correctly then. You get what you wrote.

http://stackoverflow.com/comment/84713716
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48855090
has text: Yeah. I just want it to create a table through python 1st and save it. Later on, I can change the sql code to do whatever I want.

http://stackoverflow.com/comment/84650552
has text: I believe my question is clear. I don't know if I have to use the mentioned class, or if there is another way to achieve what I want, and that's why I described what's my goal. And yes, I did some research, which got to me the the `UserNotificationListener`. I don't need anybody to do all the work for me - I asked if there's a certain functionality from a certain environment, pretty straightforward. Any suggestion how that could be asked instead?
comment on: http://stackoverflow.com/q/48822555
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84844597
has text: So you want columns like "Shot - Wounded/Injured", "Shot - Dead", and so on? Is what you've shown an example of data from a single row of your "incident_characteristics" column?
comment on: http://stackoverflow.com/q/48919003
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84898958
comment on: http://stackoverflow.com/a/48945773
score: 0
type: AnswerComment
has text: ['1', '1', '0', '0', '1', '1', '0', '0', '1', '0', '1', '0', '1', '0', '1', '0', '1', '1', '1', '1', '1', '1', '1', '1', '0', '1', '1', '1', '1', '1', '0', '1', '1', '1', '0', '1', '0', '1', '0', '1', '0', '1', '0', '1', '0', '1', '1', '0', '0', '1', '1', '0', '1', '0', '0', '0'] This result is totally wrong. I just took positions 33 and 41 as examples of that it is not working correctly. Yes, I know, the first position is 0, thats not the issue really. Just think of the leftmost as position 1 when counting to pos 33 and 41 in KEY.
type: Comment

http://stackoverflow.com/q/48811807
has title: Python : Plotting outlier using plt
has comment: http://stackoverflow.com/comment/84628242
tagged with: python-2.7
score: 0
tagged with: scikit-learn
has comment: http://stackoverflow.com/comment/84627917
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
answer count: 0
tagged with: outliers
has body: I am performing outlier detection on a dataset having six columns. A B C D E F 0 166 11.3 0.37 15.8 14.7 251 1 165 11.4 0.37 15.9 15.4 254 2 168 11.2 0.38 14.7 14.2 248 3 168 11.1 0.38 14.1 15.0 248 4 170 11.1 0.37 14.3 15.6 250 Then, I used Isolation forest from sklearn as shown below. ifo = IsolationForest(n_estimators=100, max_samples='auto', contamination=0.1, max_features=1.0,bootstrap=True, n_jobs=-1, random_state=None, verbose=2) ifo.fit(X) Out[39]: array([ 0.1147684 , 0.0967917 , 0.12101755, ..., 0.07251437, 0.07300837, 0.03996958]) ifo_preds = ifo.predict(X) There is a contamination variable in Iso Forest, it is default to 0.2, if I don't know how many outliers are there, should I use it as default or the approach should be different. Next, I want to plot the outliers on a graph as shown in sklearn example. import numpy as np import matplotlib.pyplot as plt from sklearn.neighbors import LocalOutlierFactor np.random.seed(42) # Generate train data X = 0.3 * np.random.randn(100, 2) # Generate some abnormal novel observations X_outliers = np.random.uniform(low=-4, high=4, size=(20, 2)) X = np.r_[X + 2, X - 2, X_outliers] # fit the model clf = LocalOutlierFactor(n_neighbors=20) y_pred = clf.fit_predict(X) y_pred_outliers = y_pred[200:] # plot the level sets of the decision function xx, yy = np.meshgrid(np.linspace(-5, 5, 50), np.linspace(-5, 5, 50)) Z = clf._decision_function(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape) plt.title("Local Outlier Factor (LOF)") plt.contourf(xx, yy, Z, cmap=plt.cm.Blues_r) a = plt.scatter(X[:200, 0], X[:200, 1], c='white', edgecolor='k', s=20) b = plt.scatter(X[200:, 0], X[200:, 1], c='red', edgecolor='k', s=20) plt.axis('tight') plt.xlim((-5, 5)) plt.ylim((-5, 5)) plt.legend([a, b], ["normal observations", "abnormal observations"], loc="upper left") plt.show() Which gives the output as shown in the figure. How can i plot this to fit my example. I am also attaching link to my dataset. https://drive.google.com/file/d/1GFTV…
type: Question

http://stackoverflow.com/comment/84760753
has text: @user3326870 Do you have variable names in the file? If so, you can get variable value like this `eval(input_list[0])`
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48878102
type: Comment

http://stackoverflow.com/q/48870459
has body: Problem: In Python program, the size of the list in bytes is less than the size of all its elements. Here is my code to test. I use sys.getsizeof() to get the size of variables as bytes. import sys l = range(10) for i in range(0,10): print(sys.getsizeof(l[i])) i = i + 1 #and it returns 12 bytes for each element print(sys.getsizeof(l)) #and it returns 76 , not 120 What is the reason?
accepted answer: http://stackoverflow.com/a/48873365
answer count: 1
has comment: http://stackoverflow.com/comment/84747412
tagged with: list
has comment: http://stackoverflow.com/comment/84744772
has title: Why is the size of a list not equal to the sum of its elements' size in Python?
has comment: http://stackoverflow.com/comment/84747452
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48873365
tagged with: byte
type: Question
tagged with: python
has comment: http://stackoverflow.com/comment/84744707
score: 0

http://stackoverflow.com/q/48843120
has body: I'm trying to make a loop to go through a 2 dimensional list, if the loop finds the matching string that is in the first element then it adds +1 to the second element of the list. An example of the list: [[mike, 0], [john, 2], [henry, 0], [sam, 1]] If the required search was for John this would happen: [[mike, 0], [john, 3], [henry, 0], [sam, 1]] And then for Mike: [[mike, 1], [john, 3], [henry, 0], [sam, 1]] In the below scenario 'name' is the string getting brought in that needs to be found. I'm also pulling the list of names in from a CSV file and then writing the updated list back. I can't seem to get this to work, and the error that is coming back to me is 'TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'' def count(name): with open('nameList.csv', 'r') as csvfile: reader = csv.reader(csvfile) nameList = list(reader) for x in range(len(nameList)): if nameList[x][0] == name: print(nameList== name) nameList[1] = nameList[1] + 1 with open("nameList.csv", "w", newline='') as f: writer = csv.writer(f) for i in nameList: writer.writerow(i) Any ideas about how to get this working? Much appreciated!
tagged with: arrays
downvote count: 0
has answer: http://stackoverflow.com/a/48843171
favorite count: 0
tagged with: http://stackoverflow.com/tag/csv
has title: Find a matching string and then + 1 to element
has answer: http://stackoverflow.com/a/48843302
accepted answer: http://stackoverflow.com/a/48843302
upvote count: 1
tagged with: python
possible better answer: http://stackoverflow.com/a/48843171
type: AnsweredQuestion
tagged with: list
score: 1
tagged with: loops
type: Question
answer count: 2

http://stackoverflow.com/comment/84674376
comment on: http://stackoverflow.com/q/48833908
score: 0
has text: But most commenters here were just throwing "multithread" at this problem, when the answer is to go asynchronous, in a way that is collaborative with the GUI framework.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/112901381
type: Comment
comment on: http://stackoverflow.com/a/48992229
has text: Thanks for the explanation! How can we make sure that t1 runs before t2? Is this related to SubDAGs?
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84764753
score: 1
comment on: http://stackoverflow.com/a/48879753
has text: `(?<!$)` is a lookbehind (see Option 2 description). You might want to use a lookahead, but `(?<!$)` = `(?!$)` since `$` is a zero-width assertion.
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48825041
tagged with: python-2.7
score: 0
answer count: 2
has body: I've generated a list of timestamps using the following code: no_of_readings = int(math.ceil(no_of_seconds/measurement_interval)) timestamps = [time_intervals[0]["timestamp"] - timedelta(seconds=x * measurement_interval) for x in range(1, int(math.ceil(no_of_readings))) ] timestamps.reverse() But when I try to reverse the timestamps list, It returns none. What should I do to resolve this? I believe that problem lies because elements are in form of dataetime.datetime(2018,02,16,0,0,1) . Any help would be appreciated.
favorite count: 0
tagged with: datetime
tagged with: python
has title: Reversing a DateTime list in python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84653642
has answer: http://stackoverflow.com/a/48825185
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84653603
possible better answer: http://stackoverflow.com/a/48825115
has answer: http://stackoverflow.com/a/48825115
accepted answer: http://stackoverflow.com/a/48825185

qpushbutton
type: Tag
tag name: qpushbutton
tags question: http://stackoverflow.com/q/48835586

http://stackoverflow.com/comment/84908106
type: QuestionComment
score: 1
has text: raising an `HTTP 404` error because the requested user is not a `staff` and `superuser`
comment on: http://stackoverflow.com/q/48947777
type: Comment

http://stackoverflow.com/a/48928390
has body: df['num1'] = df.num1.str[0] df.dropna(axis=0, inplace=True) A solution inspired by suleiman answer but without using loc And here is the output : num1 num2 0 2.0 10 1 3.0 20 2 4.0 30 3 5.0 40 4 6.0 50 7 10.0 80 9 15.0 100
score: 0
has comment: http://stackoverflow.com/comment/84865303
answers question: http://stackoverflow.com/q/48928026
type: Answer
has comment: http://stackoverflow.com/comment/84863229
has comment: http://stackoverflow.com/comment/84865388

http://stackoverflow.com/a/48844511
type: Answer
has body: Try using this on your Ubuntu machine on a separate terminal ssh -L &lt;local-port&gt;:&lt;remote-IP&gt;:&lt;Remote-Port&gt; -N &lt;remote-user&gt;@&lt;remote-IP&gt; This will start forwarding your =2019 traffic (local traffic) to the AMI Instance which is a remote machine in this case.
score: 0
answers question: http://stackoverflow.com/q/48844384
has comment: http://stackoverflow.com/comment/84694115
has comment: http://stackoverflow.com/comment/84710905

http://stackoverflow.com/comment/84758747
comment on: http://stackoverflow.com/a/48877329
has text: its a csv file i dont know how to do it i am new to python and pandas how to import and remove address column and add 2 more columns and save the file plz help !!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84730128
has text: You should not work with JSON as a string. Decode the JSON into a dict, modify it, re-encode it to JSON.
type: Comment
comment on: http://stackoverflow.com/q/48863493
type: QuestionComment
score: 3

http://stackoverflow.com/comment/84812082
score: 1
has text: what's your pandas version?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48903008

http://stackoverflow.com/q/48877088
tagged with: python
has answer: http://stackoverflow.com/a/48877142
has body: I am trying to create a discord bot for a personal project to better myself at Python programming. However, I ran into an issue. When the bot gets this block of code: def bloodbath(tribs): event = "null" for person in tribs: bloodbath_type = ["bloodbath_solo","bloodbath_duo"] output = ["Bloodbath Day."] type = random.choice(bloodbath_type) if type == "bloodbath_solo": output.append((random.choice(bloodbath_solo)) % (person)) else: if len(current_duo) &lt; 2: current_duo.append(person) if len(current_duo) == 2: output.append((random.choice(bloodbath_duo)) % (current_duo[0], current_duo[1])) current_duo.clear() return output await self.bot.say(bloodbath(tributes)) A few issues arise. First: The for person in tribs loop only runs once, or not at all. Here is an example of an output. https://i.sstatic.net/M8Nba.jpg What I want to occur is for the loop to append to the output list 6 times or less (depending if there are situations that call for 2 people) and return it to the bot, where it can input it into the chat. Here is a hastebin to the entire code. https://hastebin.com/lumekazula.py
downvote count: 3
type: Question
upvote count: 0
has title: For loop not executing properly, not appending to list
has comment: http://stackoverflow.com/comment/84758350
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84758301
type: UnansweredQuestion
score: -3

http://stackoverflow.com/a/51710943
answers question: http://stackoverflow.com/q/48814200
upvote count: 10
type: Answer
has comment: http://stackoverflow.com/comment/128134876
has body: You get this error when your Python client receives an empty response (header /body). BTW newer Python version will throw a different Exception, It can happen when the server disconnects the connections, or a network issue. In my case, we spent some weeks trying to reproduce it until we found the main cause, We have a Python application sending requests to a service behind Nginx loadbalancer, We found that Nginx disconnects the connection when the client exceeded the default Nginx configurations client_header_timeout / client_body_timeout (60 sec), it's the time that Nginx will wait for additional data packet from the client. You can follow this reference http://nginx.org/en/docs/http/ngx_http_core_module.html#client_body_timeout When our application is loaded with CPU processing, connections are established but header and request body have a long delay until transmitted, over 82 seconds. So Nginx closes the connection and returns reset packet (recorded tcpdump with empty body and headers), officially it should return status code 408, which is not happening. We solved it by increasing the client_header_timeout / client_body_timeout to 180s for both params: server { .. client_body_timeout 180s; client_header_timeout 180s; }
score: 10
downvote count: 0

tesseract
tags question: http://stackoverflow.com/q/48928592
type: Tag
tags question: http://stackoverflow.com/q/48850502
tag name: tesseract
tags question: http://stackoverflow.com/q/48844980
tags question: http://stackoverflow.com/q/48915449

http://stackoverflow.com/a/48820619
type: Answer
accepted answer of: http://stackoverflow.com/q/48820580
score: 3
answers question: http://stackoverflow.com/q/48820580
upvote count: 3
downvote count: 0
has body: in script1: a = 1 import script2 b = script2.dosomething(a) print(b) in script 2: def dosomething(a): return a+2 I think the mistake is dosomething does not return anything, and the variable b in the function is a local variable.
type: AcceptedAnswer

http://stackoverflow.com/comment/84805947
type: QuestionComment
comment on: http://stackoverflow.com/q/48899123
has text: `ch2 and ch4` will never be true. Your numbers cannot start with both a 2 **and** 6
score: 0
type: Comment

http://stackoverflow.com/q/48824313
has title: Installing python isopleths module
has comment: http://stackoverflow.com/comment/84701471
answer count: 1
has comment: http://stackoverflow.com/comment/84675348
tagged with: python
has comment: http://stackoverflow.com/comment/84673557
type: UnansweredQuestion
has body: I wonder if there is anybody who is able to use the tephi module in python to plot tephigrams. When I try i get the error that there is no module isopleths. I have tried to install isopleths with pip as follows pip install --upgrade isopleths and I get the following Collecting isopleths Could not find a version that satisfies the requirement isopleths (from versions: ) No matching distribution found for isopleths with anaconda conda install isopleths I get Fetching package metadata ........... PackageNotFoundError: Packages missing in current channels: - isopleths We have searched for the packages in the following channels: - https://repo.continuum.io/pkgs/main/linux-32 - https://repo.continuum.io/pkgs/main/noarch - https://repo.continuum.io/pkgs/free/linux-32 - https://repo.continuum.io/pkgs/free/noarch - https://repo.continuum.io/pkgs/r/linux-32 - https://repo.continuum.io/pkgs/r/noarch - https://repo.continuum.io/pkgs/pro/linux-32 - https://repo.continuum.io/pkgs/pro/noarch If anybody has any experience of how to find this module, I would appreciate if they could share
type: Question
has comment: http://stackoverflow.com/comment/84652322
has answer: http://stackoverflow.com/a/53265634
score: 0

http://stackoverflow.com/a/48872926
has comment: http://stackoverflow.com/comment/84799512
has comment: http://stackoverflow.com/comment/84799732
has comment: http://stackoverflow.com/comment/84799996
score: 4
upvote count: 4
answers question: http://stackoverflow.com/q/48872731
has comment: http://stackoverflow.com/comment/84799714
downvote count: 0
has comment: http://stackoverflow.com/comment/84794820
type: Answer
has body: This is a common pitfall, such that the documentation espectially mentions it: Note that c should not be a single numeric RGB or RGBA sequence because that is indistinguishable from an array of values to be colormapped. It also directly gives you the solution: c can be a 2-D array in which the rows are RGB or RGBA, however, including the case of a single row to specify the same color for all points. In this case: c=np.atleast_2d(cmap(i/10.)) A different option is of course to specify the color as a string such that this abiguity is resolved. c = matplotlib.colors.rgb2hex(cmap(i/10.))

http://stackoverflow.com/comment/84686156
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48836035
has text: Because you should really be saying `for ind, row in data_file.iterrows():` The iterator gives you a tuple of index, row
type: AnswerComment

http://stackoverflow.com/comment/84666314
type: AnswerComment
score: 0
has text: Thanks! Glad I could help!
type: Comment
comment on: http://stackoverflow.com/a/48830858

http://stackoverflow.com/q/48940663
has comment: http://stackoverflow.com/comment/84888294
accepted answer: http://stackoverflow.com/a/48940786
has body: I have read a few other similar questions here and still not been able to get my head around this. Im working on a Flask app that grabs crypto prices from an API endpoint based on a list of coins I pass in. I then want to store each coin and price in this SQLite DB: drop table if exists prices; create table prices ( id integer primary key autoincrement, coin text not null, usd int not null ); this is my Flask route and function below along with my first attempt. So here I passed all the data into a dictionary and then tried to put that into the DB using 'db.executemany' which didnt work and threw the error below. @app.route('/coindata') def coindata(): coins = ['BTC', 'ETH', 'XRP', 'LTC', 'BCH', 'ADA', 'XLM', 'NEO', 'IOTA', 'DASH' ] base_url = 'https://min-api.cryptocompare.com/data/price?fsym=' connector = '&amp;tsyms=' fiat = 'USD' coindata = {} db = get_db() for coin in coins: endpoint = base_url+coin+connector+fiat with urllib.request.urlopen(endpoint) as url: data = json.loads(url.read().decode()) print(data) #returns {'USD': 9769.35} for k,v in data.items(): price = v coindata.update({coin:v}) print(coindata) db.executemany('insert into prices (coin, usd) values (?, ?)', (coindata,)) #sqlite3.ProgrammingError: Binding 1 has no name, but you supplied a dictionary (which has only names). so I think I need to call 'db.execute' within the for loop and then commit each coin from my coin list plus the USD price that is returned to the DB then, but Im not sure how to implement that. This is what I have tried in the for loop: with urllib.request.urlopen(endpoint) as url: data = json.loads(url.read().decode()) print(data) db.execute('INSERT INTO prices (coin) VALUES (coin)') db.execute('INSERT INTO price (usd) VALUES (data[1])') this returns the following error: db.execute('INSERT INTO prices (coin) VALUES (coin)') sqlite3.OperationalError: no such column: coin which is weird as my schema has coin setup in it. I have also tried this: db.execute('INSERT INTO prices (coi…
has title: Insert JSON response data into SQLite3 DB
has comment: http://stackoverflow.com/comment/84888298
upvote count: 1
tagged with: python
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84888557
has comment: http://stackoverflow.com/comment/84888711
has comment: http://stackoverflow.com/comment/84888715
type: Question
has answer: http://stackoverflow.com/a/48940786
downvote count: 0
tagged with: sqlite
answer count: 1
has comment: http://stackoverflow.com/comment/84888796
favorite count: 0

http://stackoverflow.com/q/48858167
has answer: http://stackoverflow.com/a/48863203
tagged with: python
type: AnsweredQuestion
tagged with: web-scraping
tagged with: scrapy
type: Question
linked to: http://stackoverflow.com/q/48797819
accepted answer: http://stackoverflow.com/a/48863203
has title: scrapy json output all items on one line
tagged with: http://stackoverflow.com/tag/json
has body: I'm trying to get my output to look like the following in json format. {"loser": "De Schepper K." ,"winner": "Herbert P.", "url": "https://www.sofascore.com/tennis/2018-02-07"} But I'm currently getting individual lines for each loser item and winner item. I would like both winner and loser to be on the same line with the url. {"loser": "De Schepper K.", "url": "https://www.sofascore.com/tennis/2018-02-07"} {"winner": "Herbert P.", "url": "https://www.sofascore.com/tennis/2018-02-07"} {"loser": "Sugita Y.", "url": "https://www.sofascore.com/tennis/2018-02-07"} I'm not sure if it's my selectors that's causing this behaviour but I'd like to know how I can customise the pipelines so the loser, winner and date are all on the same json line I've never extracted json format before so it's new to me. How do you specify what json keys and values will be on each line using custom pipeline? I also tried to use csv item exporter to do this and got strange behaviour too. ref Scrapy output is showing empty rows per column Here's my spider.py import scrapy from scrapy_splash import SplashRequest from scrapejs.items import SofascoreItemLoader from scrapy import Spider import json from scrapy.http import Request, FormRequest class MySpider(scrapy.Spider): name = "jsscraper" start_urls = ["https://www.sofascore.com/tennis/2018-02-07"] def start_requests(self): for url in self.start_urls: yield SplashRequest(url=url, callback=self.parse, endpoint='render.html', args={'wait': 1.5}) def parse(self, response): for row in response.css('.event-team'): il = SofascoreItemLoader(selector=row) il.add_css('winner' , '.event-team:nth- child(2)::text') il.add_css('loser' , '.event-team:nth- child(1)::text') il.add_value('url', response.url) yield il.load_item() items.py import scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst, MapCompose from operator import methodcaller from scrapy import Spider, Request, Selector class SofascoreItem(scrapy.Item): loser …
score: 0
answer count: 2
possible better answer: http://stackoverflow.com/a/48859488
has answer: http://stackoverflow.com/a/48859488

http://stackoverflow.com/a/48938796
has comment: http://stackoverflow.com/comment/84886152
upvote count: 5
type: Answer
accepted answer of: http://stackoverflow.com/q/48933964
has body: It appears you are trying to make an entry field show the validity of the content by changing the background. However you are trying to reconfigure the style each time which is not the right way to go. Instead you should configure the dynamic properties according to the widget state. This is how the disabled/!disabled and pressed/!pressed aappearance changes are handled. The ttk widgets have a state method where you can change a number of flags. disabled is the most common and pressed for button-type widgets. The other is active for when the widget changes its appearance when the pointer is hovering over it making it look 'hot'. For your purpose there is a handy invalid state defined. We just need to add it to the style map for the widget style. As we don't want to affect all Entry widgets we can copy the current style to a new Custom.Entry style: style = ttk.Style() style.layout("Custom.Entry", style.layout('TEntry')) style.configure("Custom.Entry", **style.configure('TEntry')) style.map("Custom.Entry", **style.map('TEntry')) style.map("Custom.Entry", fieldbackground=[(['invalid','!disabled'], '#ff4040'), (['invalid','disabled'], '#ffc0c0')]) entry = ttk.Entry(root, style='Custom.Entry') On the Tk-based themes this will be sufficient to have the background of the widget change colour according to the widget invalid state. ie: entry.state(['invalid']) will make it use a red background. On themes that use native drawing elements like the Windows and MacOS themes this needs a bit more work. We can't necessarily change the look of a native themeing engine drawn element unless the native engine supports the invalid state already. If it does not then we can override the elements that make up the widget presentation by cloning in new ones from one of the Tk-based themes. To illustrate this see the createCustomEntry function below which copies the fieldbackground from the 'default' theme so that we can change the look on Windows. On Linux it looks like this now: On Windows…
has comment: http://stackoverflow.com/comment/84886116
downvote count: 0
answers question: http://stackoverflow.com/q/48933964
score: 5
has comment: http://stackoverflow.com/comment/123972915
has comment: http://stackoverflow.com/comment/84885010
type: AcceptedAnswer

http://stackoverflow.com/comment/84747913
comment on: http://stackoverflow.com/a/48870126
score: 0
type: AnswerComment
type: Comment
has text: While searching didn't work for me, I also arrived to a similar solution. I found the build page at https://github.com/h2oai/h2o-3/releases/tag/jenkins-3.14.0.1 and based on that formulated the download URL as http://h2o-release.s3.amazonaws.com/h2o/rel-weierstrass/1/h2o-3.14.0.1.zip (which zip happens to contain a ```python``` subdirectory with a pip installable ```whl``` inside)

http://stackoverflow.com/q/48912467
has answer: http://stackoverflow.com/a/48923804
upvote count: 1
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48923804
has body: Some code has been refactored to make imports direct and there is a bit of a mess with reverted commits etc.. I am getting an ImportError and don't understand the Python import system well enough to know why. Have spent a long time looking at comparisons between branches etc but just can't find what it is.. Given the following directory structure, our_project/ __init__.py directory1/ __init__.py file1.py file2.py file3.py directory2/ __init__.py file3.py file4.py file5.py directory3/ __init__.py file6.py file7.py file8.py All the __init__.py 's are empty except the one in the our_project/ directory which has some code in it. Would the following at the top of directory3/file7.py work, and not cause an ImportError: from out_project.directory1.file1 import my_function Or do you need to write from our_project.directory1 import my_function ? It just feels as if this empty __init__.py is somehow interfering with things..
has comment: http://stackoverflow.com/comment/84853754
has answer: http://stackoverflow.com/a/48923979
has comment: http://stackoverflow.com/comment/84853924
has comment: http://stackoverflow.com/comment/84854111
score: 0
possible better answer: http://stackoverflow.com/a/48923979
answer count: 2
favorite count: 0
has title: Will an empty __init__.py interfere with a direct import and cause an error?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84853926
has comment: http://stackoverflow.com/comment/84854017
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48822463
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48938860
tagged with: multiprocessing
type: Question
answer count: 2
has body: I'm trying to use python's multiprocessing Pool method in pytorch to process a image. Here's the code: from multiprocessing import Process, Pool from torch.autograd import Variable import numpy as np from scipy.ndimage import zoom def get_pred(args): img = args[0] scale = args[1] scales = args[2] img_scale = zoom(img.numpy(), (1., 1., scale, scale), order=1, prefilter=False, mode='nearest') # feed input data input_img = Variable(torch.from_numpy(img_scale), volatile=True).cuda() return input_img scales = [1,2,3,4,5] scale_list = [] for scale in scales: scale_list.append([img,scale,scales]) multi_pool = Pool(processes=5) predictions = multi_pool.map(get_pred,scale_list) multi_pool.close() multi_pool.join() I'm getting this error: `RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the 'spawn' start method ` In this line: predictions = multi_pool.map(get_pred,scale_list) Can anyone tell me what I'm doing wrong ?
has title: How to use PyTorch multiprocessing?
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48938860
score: 40
tagged with: pytorch
possible better answer: http://stackoverflow.com/a/48824768
has answer: http://stackoverflow.com/a/48824768
tagged with: python
tagged with: computer-vision
upvote count: 40

http://stackoverflow.com/q/48954408
favorite count: 0
has body: I have two lists: a and b. I want to concatenate all of the elements of the b that are between elements of a. All of the elements of a are in b, but b also has some extra elements that are extraneous. I would like to take the first instance of every element of a in b and concatenate it with the extraneous elements that follow it in b until we find another element of a in b. The following example should make it more clear. a = [[11.0, 1.0], [11.0, 2.0], [11.0, 3.0], [11.0, 4.0], [11.0, 5.0], [12.0, 1.0], [12.0, 2.0], [12.0, 3.0], [12.0, 4.0], [12.0, 5.0], [12.0, 6.0], [12.0, 7.0], [12.0, 8.0], [12.0, 9.0], [12.0, 10.0], [12.0, 11.0], [12.0, 12.0], [12.0, 13.0], [12.0, 14.0], [13.0, 1.0], [13.0, 2.0], [13.0, 3.0], [13.0, 4.0], [13.0, 5.0], [13.0, 6.0], [13.0, 7.0], [13.0, 8.0], [13.0, 9.0], [13.0, 10.0]] b = [[11.0, 1.0], [11.0, 1.0], [1281.0, 8.0], [11.0, 2.0], [11.0, 3.0], [11.0, 3.0], [11.0, 4.0], [11.0, 5.0], [12.0, 1.0], [12.0, 2.0], [12.0, 3.0], [12.0, 4.0], [12.0, 5.0], [12.0, 6.0], [12.0, 7.0], [12.0, 5.0], [12.0, 8.0], [12.0, 9.0], [12.0, 10.0], [13.0, 5.0], [12.0, 11.0], [12.0, 8.0], [3.0, 1.0], [13.0, 1.0], [9.0, 7.0], [12.0, 12.0], [12.0, 13.0], [12.0, 14.0], [13.0, 1.0], [13.0, 2.0], [11.0, 3.0], [13.0, 3.0], [13.0, 4.0], [13.0, 5.0], [13.0, 5.0], [13.0, 5.0], [13.0, 6.0], [13.0, 7.0], [13.0, 7.0], [13.0, 8.0], [13.0, 9.0], [13.0, 10.0]] c = [[[11.0, 1.0], [11.0, 1.0], [1281.0, 8.0]], [[11.0, 2.0]], [[11.0, 3.0], [11.0, 3.0]], [[11.0, 4.0]], [[11.0, 5.0]], [[12.0, 1.0]], [[12.0, 2.0]], [[12.0, 3.0]], [[12.0, 4.0]], [[12.0, 5.0]], [[12.0, 6.0]], [[12.0, 7.0], [12.0, 5.0]], [[12.0, 8.0]], [[12.0, 9.0]], [[12.0, 10.0], [13.0, 5.0]], [[12.0, 11.0], [12.0, 8.0], [3.0, 1.0]], [[13.0, 1.0], [9.0, 7.0], [12.0, 12.0], [12.0, 13.0], [12.0, 14.0], [13.0, 1.0]], [[13.0, 2.0]], [[11.0, 3.0], [13.0, 3.0]], [[13.0, 4.0]], [[13.0, 5.0], [13.0, 5.0], [13.0, 5.0]], [[13.0, 6.0]], [[13.0, 7.0], [13.0, 7.0]], [[13.0, 8.0]], [[13.0, 9.0]], [[13.0, 10.0]]] What I have thought …
upvote count: 5
has comment: http://stackoverflow.com/comment/84916411
tagged with: python
has comment: http://stackoverflow.com/comment/84916348
has answer: http://stackoverflow.com/a/48955093
has title: Python concatenating elements of one list that are between elements of another list
type: AnsweredQuestion
tagged with: list
possible better answer: http://stackoverflow.com/a/48955090
has comment: http://stackoverflow.com/comment/84916185
has comment: http://stackoverflow.com/comment/84916142
has comment: http://stackoverflow.com/comment/84916233
downvote count: 1
has comment: http://stackoverflow.com/comment/84916209
type: Question
has comment: http://stackoverflow.com/comment/84916190
score: 4
tagged with: concatenation
answer count: 3
has answer: http://stackoverflow.com/a/48955090
has answer: http://stackoverflow.com/a/48955043
accepted answer: http://stackoverflow.com/a/48955043
has comment: http://stackoverflow.com/comment/84915908

http://stackoverflow.com/q/48861287
has answer: http://stackoverflow.com/a/51372242
downvote count: 0
answer count: 3
has title: Why am I getting this error in scrapy - python3.7 invalid syntax
tagged with: macos
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: scrapy-shell
tagged with: python
has answer: http://stackoverflow.com/a/48876603
score: 11
upvote count: 11
has body: I've had a heck of a time installing scrapy. I have it installed on my mac but I am getting this error when running the tutorial: Virtualenvs/scrapy_env/lib/python3.7/site-packages/twisted/conch/manhole.py", line 154 def write(self, data, async=False): ^ SyntaxError: invalid syntax I'm on the latest versions of everything as far as I can tell. Getting this up and running has been a pain. sheesh. OS High Sierra 10.13.3 python 3.7 installed ipython I've updated about everything I can think of. terminal line is: scrapy shell http://quotes.toscrape.com/random or scrapy shell "http://quotes.toscrape.com/random" even tried single quotes. Any help would be great! Here is the complete log: (scrapy_env) XXX-MacBook-Pro:Virtualenvs ComputerName$ scrapy shell http://quotes.toscrape.com/random 2018-02-19 06:38:53 [scrapy.utils.log] INFO: Scrapy 1.5.0 started (bot: scrapybot) 2018-02-19 06:38:53 [scrapy.utils.log] INFO: Versions: lxml 3.6.2.0, libxml2 2.9.4, cssselect 1.0.3, parsel 1.4.0, w3lib 1.19.0, Twisted 17.9.0, Python 3.7.0a2 (v3.7.0a2:f7ac4fe52a, Oct 16 2017, 21:11:18) - [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)], pyOpenSSL 17.5.0 (OpenSSL 1.0.2n 7 Dec 2017), cryptography 2.1.4, Platform Darwin-17.4.0-x86_64-i386-64bit 2018-02-19 06:38:53 [scrapy.crawler] INFO: Overridden settings: {'DUPEFILTER_CLASS': 'scrapy.dupefilters.BaseDupeFilter', 'LOGSTATS_INTERVAL': 0} Traceback (most recent call last): File "/Users/ComputerName/Virtualenvs/scrapy_env/bin/scrapy", line 11, in &lt;module&gt; load_entry_point('Scrapy==1.5.0', 'console_scripts', 'scrapy')() File "/Users/ComputerName/Virtualenvs/scrapy_env/lib/python3.7/site-packages/Scrapy-1.5.0-py3.7.egg/scrapy/cmdline.py", line 150, in execute _run_print_help(parser, _run_command, cmd, args, opts) File "/Users/ComputerName/Virtualenvs/scrapy_env/lib/python3.7/site-packages/Scrapy-1.5.0-py3.7.egg/scrapy/cmdline.py", line 90, in _run_print_help func(*a, **kw) File "/Users/ComputerName/Virtualenvs/scrapy_env/lib/python3.7/site-pac…
has answer: http://stackoverflow.com/a/51762376
type: Question

http://stackoverflow.com/comment/84794333
has text: @lrakli I understood the question to be "how to print just the one value out of the `dict`. If that is not what you are looking for, then you should reword the question.
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48894154
score: 3

http://stackoverflow.com/comment/84742625
has text: You are 100% right Graham. Even though I didn't install mod_wsgi myself, I didn't realize that the elastic beanstalk python platform runs it itself. Thanks. Source: https://stackoverflow.com/questions/42636073/how-is-deploying-flask-on-aws-elastic-beanstalk-different-from-running-script
comment on: http://stackoverflow.com/q/48833443
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84880508
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48936692
has text: I am new to python but this is the second time I have seen reference to pandas. Is this something that has to be downloaded and imported in or does it come packaged with python 2.7? My ultimate output once I get the latest version of the record is to compare it to the original csv and find out what data has been deleted in previous versions.

http://stackoverflow.com/a/48830780
has comment: http://stackoverflow.com/comment/95852143
has comment: http://stackoverflow.com/comment/125137678
has comment: http://stackoverflow.com/comment/99641479
type: Answer
has comment: http://stackoverflow.com/comment/95459302
has comment: http://stackoverflow.com/comment/95314948
accepted answer of: http://stackoverflow.com/q/48829993
has comment: http://stackoverflow.com/comment/95761543
has comment: http://stackoverflow.com/comment/99751985
has body: You can do this without a udf using a Window. Consider the following example: import pyspark.sql.functions as f data = [ ('a', 5), ('a', 8), ('a', 7), ('b', 1), ('b', 3) ] df = sqlCtx.createDataFrame(data, ["A", "B"]) df.show() #+---+---+ #| A| B| #+---+---+ #| a| 5| #| a| 8| #| a| 7| #| b| 1| #| b| 3| #+---+---+ Create a Window to partition by column A and use this to compute the maximum of each group. Then filter out the rows such that the value in column B is equal to the max. from pyspark.sql import Window w = Window.partitionBy('A') df.withColumn('maxB', f.max('B').over(w))\ .where(f.col('B') == f.col('maxB'))\ .drop('maxB')\ .show() #+---+---+ #| A| B| #+---+---+ #| a| 8| #| b| 3| #+---+---+ Or equivalently using pyspark-sql: df.registerTempTable('table') q = "SELECT A, B FROM (SELECT *, MAX(B) OVER (PARTITION BY A) AS maxB FROM table) M WHERE B = maxB" sqlCtx.sql(q).show() #+---+---+ #| A| B| #+---+---+ #| b| 3| #| a| 8| #+---+---+
answers question: http://stackoverflow.com/q/48829993
upvote count: 81
has comment: http://stackoverflow.com/comment/95314852
has comment: http://stackoverflow.com/comment/99751070
type: AcceptedAnswer
downvote count: 0
score: 81

http://stackoverflow.com/comment/84758967
type: Comment
comment on: http://stackoverflow.com/a/48848685
has text: I have to give you the award of best answer even though it was truly a draw. Your method results in all data types keeping their integrity and that is obviously something that could be a benefit even though I need to turn them all into strings anyways... In fact, this could help allow for pre-processor statements since the variable's rvalues could keep their data types until the moment I need to turn them into a string.
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84846387
has text: I don't understand, I installed the module using pip install pyinsane2, in the python intepreter I ran >>>import pyinsane2 and in my script it says import pyinsane2 (which gives me the ModuleNotFound error)
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48919965

neural-network
tags question: http://stackoverflow.com/q/48879125
tags question: http://stackoverflow.com/q/48828478
tags question: http://stackoverflow.com/q/48878639
tags question: http://stackoverflow.com/q/48922811
tags question: http://stackoverflow.com/q/48844024
tags question: http://stackoverflow.com/q/48846894
tags question: http://stackoverflow.com/q/48862451
tags question: http://stackoverflow.com/q/48938120
tags question: http://stackoverflow.com/q/48804734
tags question: http://stackoverflow.com/q/48830704
tags question: http://stackoverflow.com/q/48835967
tags question: http://stackoverflow.com/q/48894529
tags question: http://stackoverflow.com/q/48920762
tags question: http://stackoverflow.com/q/48846332
tags question: http://stackoverflow.com/q/48831585
tags question: http://stackoverflow.com/q/48898104
type: Tag
tags question: http://stackoverflow.com/q/48819828
tags question: http://stackoverflow.com/q/48848133
tags question: http://stackoverflow.com/q/48952003
tags question: http://stackoverflow.com/q/48811817
tags question: http://stackoverflow.com/q/48941188
tags question: http://stackoverflow.com/q/48960654
tags question: http://stackoverflow.com/q/48913271
tags question: http://stackoverflow.com/q/48843578
tags question: http://stackoverflow.com/q/48840884
tags question: http://stackoverflow.com/q/48873387
tags question: http://stackoverflow.com/q/48812250
tags question: http://stackoverflow.com/q/48963329
tags question: http://stackoverflow.com/q/48880273
tags question: http://stackoverflow.com/q/48958765
tags question: http://stackoverflow.com/q/48946687
tags question: http://stackoverflow.com/q/48861215
tags question: http://stackoverflow.com/q/48829294
tags question: http://stackoverflow.com/q/48856444
tags question: http://stackoverflow.com/q/48883034
tags question: http://stackoverflow.com/q/48815203
tags question: http://stackoverflow.com/q/48805407
tags question: http://stackoverflow.com/q/48870598
tags question: http://stackoverflow.com/q/48849715
tags question: http://stackoverflow.com/q/48900949
tags question: http://stackoverflow.com/q/48814529
tag name: neural-network
tags question: http://stackoverflow.com/q/48852970
tags question: http://stackoverflow.com/q/48955231
tags question: http://stackoverflow.com/q/48934338
tags question: http://stackoverflow.com/q/48859378

http://stackoverflow.com/a/67568828
type: Answer
has body: For me this solved it: mapping the local path to the remote inside the Pycharm run configurations settings. Edit Configurations &gt; Path Mappings &gt; Local path = /&lt;Users/me/pycharm etc.../project root&gt; remote path = / eg.
answers question: http://stackoverflow.com/q/48947494
score: 0

http://stackoverflow.com/a/48872356
has comment: http://stackoverflow.com/comment/84748753
accepted answer of: http://stackoverflow.com/q/48872113
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84748851
has body: This is in general python behaviour and not specific to numpy. If you have an object such as list you will see a similar behaviour. a = [1] b = a b[0] = 7 print a print b will output [7] [7] This happens because variable a is pointing to a memory location where the array [1] is sitting and then you make b point to the same location. So if the value at that location changes, both the variables are still pointing there. If you want to get around this behaviour you'll need to use the .copy() function like this. A = np.zeros((2,2)) B = A.copy() A[0,0] = 2 print A print B which outputs.. [[2. 0.] [0. 0.]] [[0. 0.] [0. 0.]] Using the copy() function will spawn a whole new object instead of pointing to the old one. Caution: This may not be the ideal way to do it since copying a huge numpy array can be computationally expensive EDIT: Removed the word mutable since the behaviour is also applicable to immutables.
score: 3
answers question: http://stackoverflow.com/q/48872113
upvote count: 3

http://stackoverflow.com/a/48935452
score: 1
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84929545
has comment: http://stackoverflow.com/comment/84928679
type: Answer
has body: This would help probably from datetime import datetime formattime = datetime.strptime interval = [] shifts = [['Mon', '01:00', '22:00'], ['Tue', '02:00', '23:00'], ['Wed', '01:15', '23:30'], ['Thu', '01:00', '21:00'], ['Fri', '02:30', '22:00'], ['Sat', '01:00', '21:00'], ['Sun', '03:00', '23:00'] ] This appending here, we can call it a small hacky preprocessing. shifts.append(shifts[0]) Method get_delta returns timedelta of two datetime params. def get_delta(day1, day2): day, start, end, n_day, n_start, n_end = day1 + day2 return formattime(n_day + n_start, '%a%H:%M') - formattime(day + end, '%a%H:%M') Enumerating list provides you with index and the value which are unpacked as i, day1. And further there is a condition for end case. Day2 is taken by next index. for i, day1 in enumerate(shifts): if i+1 == len(shifts): break day2 = shifts[i+1] delta = get_delta(day1, day2).seconds / 60 interval.append(delta) print(interval) Result (in Minutes): [240, 135, 90, 330, 180, 360, 120]
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48934245
answers question: http://stackoverflow.com/q/48934245

http://stackoverflow.com/comment/84767309
comment on: http://stackoverflow.com/a/48881477
score: 0
type: AnswerComment
type: Comment
has text: can you please explain the `'<lambda>':'Values'` part?

http://stackoverflow.com/comment/84748710
comment on: http://stackoverflow.com/a/48867793
type: Comment
has text: `{'href': re.compile("^https?://")}` - really worked as expected. It returns 266 links in total for the URL https://www.jugantor.com/. 1) are these the all exclusive links (without excluding a single one ) from the whole site ? 2) For the second time, when I am extracting new news, do I have to extract all news items again and then find out which ones are new ?
score: 0
type: AnswerComment

http://stackoverflow.com/a/77969438
type: Answer
score: 1
upvote count: 1
has body: Another solution is to number the rows via row_number() using a window partitioned by A in the order of B. This solution is close to the one by @pault, but when there are several rows with the maximum value, it only keeps one of them, which I find better. Given the same example: data = [ ('a', 5), ('a', 8), ('a', 7), ('b', 1), ('b', 3) ] df = spark.createDataFrame(data, ["A", "B"]) df.show() The row_number solution is: w = Window.partitionBy('A').orderBy('B') df_collect = df.withColumn('row_number', F.row_number().over(w)) \ .filter(F.col('row_number') == 1) \ .drop('row_number') \ .show() +---+---+ | A| B| +---+---+ | a| 8| | b| 3| +---+---+ I also extended the benchmark from @Fernando Wittmann, both solutions run in about the same time: The dataframe: N_SAMPLES = 600000 N_PARTITIONS = 1000 MAX_VALUE = 100 data = zip( [random.randint(0, N_PARTITIONS-1) for i in range(N_SAMPLES)], [random.randint(0, MAX_VALUE) for i in range(N_SAMPLES)], list(range(N_SAMPLES)) ) df = spark.createDataFrame(data, ["A", "B", "C"]) row_number approach: %%timeit w = Window.partitionBy('A').orderBy(F.col('B').desc()) df_collect = df.withColumn('row_number', F.row_number().over(w)) \ .filter(F.col('row_number') == 1) \ .drop('row_number') \ .collect() 313 ms ± 19.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) == max approach: %%timeit w = Window.partitionBy('A') df_collect = df.withColumn('maxB', F.max('B').over(w))\ .where(F.col('B') == F.col('maxB'))\ .drop('maxB')\ .collect() 328 ms ± 24.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) leftsemi approach: %%timeit df_collect = df.join(df.groupBy('A').agg(F.max('B').alias('B')),on='B',how='leftsemi').collect() 516 ms ± 19.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
has comment: http://stackoverflow.com/comment/137774794
downvote count: 0
answers question: http://stackoverflow.com/q/48829993
has comment: http://stackoverflow.com/comment/137922096

http://stackoverflow.com/q/48914328
type: Question
has title: Pandas match on multiple columns and get matching values as a single new column
upvote count: 5
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/48914441
has comment: http://stackoverflow.com/comment/84835011
has answer: http://stackoverflow.com/a/48914441
has answer: http://stackoverflow.com/a/48914648
answer count: 3
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48914452
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84835131
has comment: http://stackoverflow.com/comment/84835126
score: 5
has body: I have a dataframe with about 5 columns. The value I am looking to match could be present in either of the last 3 columns. Key | col1 | col2 | col3 | col4 ---------------------------------------- 1 abc 21 22 23 2 cde 22 21 20 3 fgh 20 22 23 4 lmn 20 22 21 I am filtering on value 21 on any of the last three columns as follows: df1 = df[(df['col2']=='21') | (df['col3']=='21') | (df['col4']=='21')] which gives me Key | col1 | col2 | col3 | col4 ---------------------------------------- 1 abc 21 22 23 2 cde 22 21 20 4 lmn 20 22 21 Using this new df1 I want to get this Key | col1 | newCol ------------------------- 1 abc 21 2 cde 21 4 lmn 21 Basically any of the matched column as the new column value. How do I do this using pandas? I appreciate the help. So I was thinking may be I should filter and map it to the new column at the same time but I don't know how?
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48914452

http://stackoverflow.com/comment/84828534
score: 2
comment on: http://stackoverflow.com/q/48911063
has text: @chepner The documentation says it scans in arbitrary order so I don't think that is the case.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84925874
comment on: http://stackoverflow.com/a/48959495
score: 0
type: AnswerComment
has text: `df['DATE'] = pd.DatetimeIndex(df['DATE'])`
type: Comment

http://stackoverflow.com/q/48838778
tagged with: ironpython
type: Question
tagged with: python-imaging-library
has answer: http://stackoverflow.com/a/48853536
linked to: http://stackoverflow.com/q/30384793
score: 0
answer count: 2
type: UnansweredQuestion
tagged with: python
has body: I'm new for both python and ironpython. Can you you help me how to call external python script from ironpython? I have a script file like import sys def sample(): from PIL import Image, ImageEnhance, ImageFilter img = Image.open("C:\\python\\images4.jpg") img.show(img) My ironpython from console application. class Program { static void Main(string[] argsS) { var engine = Python.CreateEngine(); dynamic scope = engine.CreateScope(); engine.ExecuteFile(@"C:\\pythonscripts\\pythonCheckV.py",scope); scope.sample(); Console.Read(); } }
has answer: http://stackoverflow.com/a/48839080
has title: No module name PIL when i call python Script from IronPython

http://stackoverflow.com/q/48916296
tagged with: image
upvote count: 1
has title: Incorrect image orientation when drawing a line with cv2.line
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
tagged with: opencv
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48916534
accepted answer: http://stackoverflow.com/a/48916534
score: 1
has body: I want to draw a line from top left corner to the bottom right corner on an image. The image is horizontal and: print(size) returns: (203, 248) With my code I am expecting a diagonal line from pixel (0,0) to pixel (203, 248). However I am getting diagonal line from pixel (0,0) to pixel (248, 203) which is outside the image boundary (sic!). I suppose the cv2.line method rotates the image somehow, can anyone advise? Here is my code: import cv2 image_1 = cv2.imread('profilowe.jpeg',0) size = image_1.shape print(size) cv2.line(image_1,(0,0),image_1.shape,255,1,16) cv2.imshow('image',image_1) cv2.waitKey(0) cv2.destroyAllWindows()
type: Question
tagged with: rotation

http://stackoverflow.com/a/48878070
has body: No, even the first method does NOT short circuit. Both of the operands must first be evaluated before the result is computed. Meaning, this is computed, i = dfzero["A"] != 0 i 0 False 1 True Name: A, dtype: bool And so is this: j = 1 / dfzero['A'] j 0 inf 1 0.500000 Name: A, dtype: float64 The expression is effectively: pd.DataFrame.where(i, j, 0) It's the same for the second. The behaviour is consistent. Were you expecting a ZeroDivisionError? You won't get that with numpy or pandas, because these libraries assume you know what you're doing when you compute such quantities. Your option here is to precompute the mask, and then compute the result for those rows only. m = df["C"].str.len() == 5 df['D'] = df.loc[m, 'C'].str[-2:].apply(lambda x: int(x, 16)) df A B C D 0 0 9.0 Nonnumeric NaN 1 2 9.0 Num0a 10.0 If you want to fill in the NaNs, use df.loc[~m, 'D'] = fill_value.
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48877958
answers question: http://stackoverflow.com/q/48877958
has comment: http://stackoverflow.com/comment/84763621
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/84706064
type: AnswerComment
score: 0
has text: We should add some sample data.
type: Comment
comment on: http://stackoverflow.com/a/48851258

http://stackoverflow.com/a/48850416
accepted answer of: http://stackoverflow.com/q/48850130
upvote count: 1
has body: Use this: r = requests.get('https://bitbns.com/order/getTickerAll') for item in r.json(): for key, value in item.items(): print(key, value['sellPrice'], value['buyPrice'], value['lastTradePrice']) Output: BTC 705000 704000 704000 XRP 72.3 72.29 72.29 NEO 8452 8450 8452 GAS 3060 3024 3024 ETH 61000 60700 60700 XLM 29.8 29.78 29.78 From the documentation: When looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method.
score: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84704456
answers question: http://stackoverflow.com/q/48850130

http://stackoverflow.com/q/48935514
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48935666
tagged with: beautifulsoup
type: UnansweredQuestion
tagged with: python
has title: BeautifulSoup: Open local and http html files
score: 3
upvote count: 3
type: Question
has body: I cannot get both working, only one or the other: link = open(url) soup = BeautifulSoup(link.read(), "html.parser") ^ Works with local files link = urlopen(url).read() soup = BeautifulSoup(link, "html.parser") ^Works with http:// (internet) links How do I simply get both working?
has comment: http://stackoverflow.com/comment/84877897

http://stackoverflow.com/q/48813320
tagged with: cpython
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/84631437
has comment: http://stackoverflow.com/comment/84631464
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84630839
has answer: http://stackoverflow.com/a/48814213
has comment: http://stackoverflow.com/comment/84631211
has comment: http://stackoverflow.com/comment/84631511
has title: Should importlib.reload restore a deleted attribute in Python 3.6?
downvote count: 1
type: Question
score: 5
linked to: http://stackoverflow.com/q/48808456
has body: I'm looking into these two related questions: here and here. I am seeing a behavior I do not expect in Python 3.6, which differs from behavior using plain reload in Python 2.7 (and 3.4). Namely, it seems that a module attribute that would be populated during module initialization or when re-exec-ing the module during a reload, is not restored after its local name is removed with del ... see below: For Python 3.6: In [1]: import importlib In [2]: import math In [3]: del math.cos In [4]: math.cos --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-4-05b06e378197&gt; in &lt;module&gt;() ----&gt; 1 math.cos AttributeError: module 'math' has no attribute 'cos' In [5]: math = importlib.reload(math) In [6]: math.cos --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-6-05b06e378197&gt; in &lt;module&gt;() ----&gt; 1 math.cos AttributeError: module 'math' has no attribute 'cos' In [7]: importlib.reload(math) Out[7]: &lt;module 'math' from '/home/ely/anaconda/envs/py36-keras/lib/python3.6/lib-dynload/math.cpython-36m-x86_64-linux-gnu.so'&gt; In [8]: math.cos --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-8-05b06e378197&gt; in &lt;module&gt;() ----&gt; 1 math.cos AttributeError: module 'math' has no attribute 'cos' For Python 2.7 (and Python 3.4): In [1]: import math In [2]: del math.cos In [3]: math.cos --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) &lt;ipython-input-3-05b06e378197&gt; in &lt;module&gt;() ----&gt; 1 math.cos AttributeError: 'module' object has no attribute 'cos' In [4]: reload(math) Out[4]: &lt;module 'math' from '/home/ely/anaconda/lib/python2.7/lib-dynload/math.so'&gt; In [5]: math.cos Out[5]: &lt;function …
has comment: http://stackoverflow.com/comment/84630662
accepted answer: http://stackoverflow.com/a/48814213
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python-internals
linked to: http://stackoverflow.com/q/48809458

http://stackoverflow.com/a/48894784
type: Answer
has body: As @CoryKramer said: just use + .. This would seem very (very..) obvious except that I had tried list1 + element1 for another code snippet and that does not work. There is only list1 + *list2*
accepted answer of: http://stackoverflow.com/q/48872239
answers question: http://stackoverflow.com/q/48872239
score: 0
type: AcceptedAnswer

http://stackoverflow.com/a/48875809
has comment: http://stackoverflow.com/comment/84755556
has body: In your react code, fetch('http://localhost:5000/api/get_dashboard_art') You are calling the endpoint (/api/get_dashboard_art) NOT (/) like you have in your flask app. @app.route('/', methods=["GET", "POST"]) change the endpoint to @app.route('/api/get_dashboard_art', methods=["GET", "POST"]) and it should work.
has comment: http://stackoverflow.com/comment/84755653
has comment: http://stackoverflow.com/comment/84755865
has comment: http://stackoverflow.com/comment/84756156
has comment: http://stackoverflow.com/comment/84755781
score: 0
answers question: http://stackoverflow.com/q/48875781
has comment: http://stackoverflow.com/comment/84755709
type: Answer

http://stackoverflow.com/a/48807498
type: Answer
has body: For training, did you try executing the node "l1" is session.run(), it is the one that actually does the computation. It is necessary for training also, your error and loss will depend upon the output of "l1", if you are not executing in the session, then loss will not come correctly. error = tf.square(l1-output,name='error') See in this line you are calculating error with l1-output, output here are the ground truth but "l1" will not have any value unless you compute it through graph under session.run(). Can you try with below command and check the outputs predictions, _,lossNow = sess.run([l1,train,loss],{input: x_train,output: y_train}) Also, instead of using "-" sign while calculating the error (l1-output), please use tensorflow operators like show here
answers question: http://stackoverflow.com/q/48805407
score: 0

http://stackoverflow.com/comment/84747956
has text: That's a different and much deeper question... I believe that if you make some of the standard distributional assumptions then OLS statistics will give you an estimate for x[1]'s variance, but not x[0]. Maybe bootstrapping? You should probably ask that on the stats stackexchange.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48858157
type: AnswerComment

http://stackoverflow.com/comment/84843467
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48917810
has text: Have you tried installing gunicorn in the virtual environment?
score: 0

http://stackoverflow.com/comment/84715328
comment on: http://stackoverflow.com/a/48846276
has text: you have to add it in your question i guess.
score: 0
type: Comment
type: AnswerComment

http://stackoverflow.com/comment/84624584
comment on: http://stackoverflow.com/a/48810561
score: 5
type: AnswerComment
has text: `while True: ...` is a better version of it.
type: Comment

http://stackoverflow.com/comment/124391634
type: Comment
has text: Doesn't it defeat the purpose of using hexbins in the first place? Why not use disks instead?
score: 0
comment on: http://stackoverflow.com/q/48844600
type: QuestionComment

http://stackoverflow.com/q/48948259
has comment: http://stackoverflow.com/comment/98713550
tagged with: python
tagged with: jupyter
has answer: http://stackoverflow.com/a/50256823
upvote count: 11
has comment: http://stackoverflow.com/comment/129783626
type: UnansweredQuestion
has body: I installed Anaconda on my windows 10. and updated all packages. now I am trying to open Jupyter lab by cmd. when I type this command in cmd: jupyter lab it just opens a tab in google chrome that shows: "404 : Not Found You are requesting a page that does not exist!" could you please help me to solve this problem to be able to open jupyter lab thanks
downvote count: 1
type: Question
tagged with: jupyter-lab
tagged with: anaconda
has answer: http://stackoverflow.com/a/48993273
score: 10
linked to: http://stackoverflow.com/q/33031069
has answer: http://stackoverflow.com/a/75169663
tagged with: conda
has comment: http://stackoverflow.com/comment/84904089
has answer: http://stackoverflow.com/a/74649653
has answer: http://stackoverflow.com/a/60606367
has comment: http://stackoverflow.com/comment/84906614
favorite count: 0
answer count: 5
has title: How to solve 404 error of jupyter lab

http://stackoverflow.com/q/48876631
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84796439
linked to: http://stackoverflow.com/q/9942536
has comment: http://stackoverflow.com/comment/84793208
upvote count: 1
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/84793147
has comment: http://stackoverflow.com/comment/84757527
tagged with: object
possible better answer: http://stackoverflow.com/a/48894437
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84795646
has comment: http://stackoverflow.com/comment/84796391
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84786150
has comment: http://stackoverflow.com/comment/84793413
has comment: http://stackoverflow.com/comment/84793352
has title: Changing global variable temporarily when calling object
has answer: http://stackoverflow.com/a/48894437
score: 0
has body: I'm trying to understand how to change an object's attribute temporarily when it is called and have the original value persist when the object is not called. Let me describe the problem with some code: class DateCalc: DEFAULT= "1/1/2001" def __init__(self, day=DEFAULT): self.day= day def __call__(self, day=DEFAULT): self.day= day return self def getday(self): return self.day In the event where a user calls getday method while passing another value i.e 2/2/2002, self.day is set to 2/2/2002. However I want to be able to revert self.day to the original value of 1/1/2001 after the method call: d_obj = DateCalc() d_obj.getday() == "1/1/2001" True d_obj().getday() == "1/1/2001" True another_day_str = "2/2/2002" d_obj(another_day_str).getday() returns "2/2/2002" But when I run the following d_obj.getday() returns "2/2/2002" I was wondering what's the right way to revert the value, without needing to include code at every method call. Secondly, this should also be true when the object is called. For example: d_obj().getday() should return "1/1/2001" I thought a decorator on the call magic method would work here, but I'm not really sure where to start. Any help would be much appreciated
has answer: http://stackoverflow.com/a/48915925
accepted answer: http://stackoverflow.com/a/48915925
has comment: http://stackoverflow.com/comment/84789015
has comment: http://stackoverflow.com/comment/84793327
favorite count: 0

http://stackoverflow.com/q/48815152
has title: Permissions for other user to run script with python package
has comment: http://stackoverflow.com/comment/84635540
has comment: http://stackoverflow.com/comment/84636370
has body: I have installed a lib via pip: sudo pip install adafruit-ws2801 Then, I gave it rights: sudo chmod +x /etc/openhab2/scripts/myscript.py However, when I try to start it as another user, an error appears: sudo su -s /bin/bash -c '/etc/openhab2/scripts/myscript.py' openhab This error: ... File "/usr/local/lib/python3.4/dist-packages/Adafruit_GPIO/SPI.py", line 42, in __init__ self._device.open(port, device) PermissionError: [Errno 13] Permission denied When I start the script as my current user (without sudo), everything is fine. But this user can not access it. Do I need to give more permissions for this user? In the first line of the python file, I wrote #!/usr/bin/env python3
tagged with: openhab
score: 0
answer count: 1
tagged with: python
tagged with: gpio
tagged with: pip
has answer: http://stackoverflow.com/a/48816555
accepted answer: http://stackoverflow.com/a/48816555
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84635471
type: Question
tagged with: raspberry-pi

http://stackoverflow.com/comment/84784127
type: AnswerComment
has text: _"I suppose that, when supplying high or low as a scalar to those numpy functions, they may internally first create a numpy array of the correct shape filled with that scalar."_ I am actually not very sure that `numpy` creates arrays internally: `%timeit np.less(arr, 0.2)` is `6.24 ms` while "pre-creating 0.2 *array*" `lim = 0.2 * np.ones_like(arr)` and then running comparison on this array gives: `%timeit np.less(arr, lim)` is `12.9 ms`. If in the first case `numpy` were creating internal arrays then I would have expected first timing to be no faster than second.
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48888971

http://stackoverflow.com/a/48954338
has comment: http://stackoverflow.com/comment/84915909
has body: you cannot use pyperclip in a webpage ... you are confusing client side and serverside ... you are copying the text on the serverside clipboard, which does nothing for the client(or anyone else) try something like the following (javascript) and then call it like this Test Data that I want to copy
has comment: http://stackoverflow.com/comment/84921021
downvote count: 0
answers question: http://stackoverflow.com/q/48954128
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/comment/84949834
type: Comment
has text: By "more" data I meant more images, spanning multiple poses.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48970626

http://stackoverflow.com/q/48821060
tagged with: autocmd
answer count: 1
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/48823555
accepted answer: http://stackoverflow.com/a/48823555
has title: Autocomplete a python Shebang (in a non .py file) by mapping to an autocmd
score: 2
downvote count: 0
tagged with: vim
type: AnsweredQuestion
has body: I am learning Vim and I have successfully set up my .vimrc file such that whenever I make a new python .py file, the appropriate shebang and header are auto-generated. Yay me! However, when building terminal pipelines I don't always like to include the .py extension for the programs I pipe to. Hence, the shebang won't auto-generate. Sad! Without repeating what I wrote for the autocmd (which took much trial and error to write because that is how I learn), can I map a string like "pyhead" while in INSERT mode, or create a macro tied to the autocmd to easily implement my shebangbang when I choose not to use the .py extension? I feel as though a simple map to a command that already exists should prevent a cluttered .vimrc. I have placed my autocmd in an augroup as follows: augroup Shebang autocmd BufNewFile *.py 0put =\"#!/usr/bin/env python\&lt;nl&gt;... ...# -*-coding: utf-8 -*-\ ...&lt;nl&gt;\&lt;nl&gt;\" ...|put ='#'.expand('%:t') ...|put =\"#&lt;My_NAME&gt;\" ...|put ='#LAST UPDATED: '.strftime('%m-%d-%Y')\|$ augroup end For clarity, the autocmd is all on one line, but I included three dots to indicate continuation (so that you wouldn't need to scroll). If this is a silly request, and there is an easy answer please reprimand. Thanks!
tagged with: shebang
type: Question
upvote count: 2

http://stackoverflow.com/a/48852765
has comment: http://stackoverflow.com/comment/84709092
type: Answer
has comment: http://stackoverflow.com/comment/84709232
answers question: http://stackoverflow.com/q/48852699
upvote count: 1
has comment: http://stackoverflow.com/comment/84709171
has body: The simple answer is No, there is no way.. This is what I mean with: this is what functions are for. (Ofc you could say that this is what variables are for too - but it goes hand in hand). import random func = lambda x: x*10 + x # function alt1 def func(x): # function alt2 return x*10 + x And call it with: func(random.randint(1, 2)) # and this can now in turn be used inside formulas For instance you can now do: def calculate_something(x): return x*x calculate_something(func(random.randint(1, 2)))
downvote count: 0
has comment: http://stackoverflow.com/comment/84708966
score: 1
has comment: http://stackoverflow.com/comment/84708975

http://stackoverflow.com/comment/84855294
has text: `header = csv.reader(f).next()` will not work in python 3, i have edited your answer to correct it, but got rejected. :(
type: AnswerComment
comment on: http://stackoverflow.com/a/48899332
score: 0
type: Comment

http://stackoverflow.com/q/48814098
accepted answer: http://stackoverflow.com/a/48814268
upvote count: 0
score: -3
linked to: http://stackoverflow.com/q/41772054
has comment: http://stackoverflow.com/comment/84631821
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84632141
has comment: http://stackoverflow.com/comment/84631881
has body: I am working on a data set . It's first row looks like this: Column1 Column2 1 [food=3, party=2,....] 2 [ocean=2, fish=3, surf=2,....] . .................. . .................. . .................. (Column1 has serial numbers and Column2 has the list of words with frequencies.) Each row has multiple words with their respective frequencies. I would like to convert the column2 as follows: [food, food, food, party, party.....] and so on. I am finding it difficult and don't know where to start. I tried tokenizing, but don't know how to proceed.
type: Question
has answer: http://stackoverflow.com/a/48814159
favorite count: 0
possible better answer: http://stackoverflow.com/a/48814159
answer count: 3
downvote count: 3
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has comment: http://stackoverflow.com/comment/84631911
tagged with: python
has answer: http://stackoverflow.com/a/48814238
has answer: http://stackoverflow.com/a/48814268
has title: How to repeat a word based on its frequency of occurrence in a row with multiple words in python?

http://stackoverflow.com/comment/84867147
has text: Thank you! I seem to be able to print out everything I need. Now it just gets to where it loops through everything and gives me an error. It doesn't like that I am using append for some reason. I'm sure there is a way that I can combine all of the for tweet in tweets statements, I was trying to go through step by step. It hiccups when it gets to id=[ ] and gives me an error: TypeError: 'builtin_function_or_method' object is not subscriptable.
comment on: http://stackoverflow.com/a/48891697
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48875523
answers question: http://stackoverflow.com/q/48875416
downvote count: 0
score: 2
has body: Assuming that "items,prices,description" all have the same length, you could rewrite the final part of the code in : for item,price,desc in zip(items,prices,description) worksheet.write(row, col, item) worksheet.write(row, col + 1, price) worksheet.write(row, col + 2, desc) row += 1 If the lists can have unequal lengths you should check this for alternatives for the zip method, but I would be worried for the data consistency.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84756773
upvote count: 2
type: Answer
accepted answer of: http://stackoverflow.com/q/48875416
has comment: http://stackoverflow.com/comment/84763799

http://stackoverflow.com/a/48993127
score: 5
upvote count: 5
has body: There are a lot of components to this problem. I'm ignoring the MTA error because that's just about an email notification when your cron job finishes. I'll also assume you have permissions set properly and that your script runs fine when run manually in the shell. The biggest issue is that the CRON command isn't the same as running the command from the terminal "shell". You have to specify that your script get run using bash. Change your cron job from: */5 * * * * /home/group_name/path/to/script/run.sh to: */5 * * * * bash /home/group_name/path/to/script/run.sh This question has more information and additional options for solving the problem.
accepted answer of: http://stackoverflow.com/q/48834638
has comment: http://stackoverflow.com/comment/85164774
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48834638
type: Answer
has comment: http://stackoverflow.com/comment/85164779

http://stackoverflow.com/q/48902763
type: Question
answer count: 2
score: 0
has body: I'm currently learning Python with the book "Learn python the hard way" and I'm getting an error. I have a folder called ex48 where a lexicon.py is located. In this lexicon.py I have 'scan' function, which gets one input, splits it and identifies the words, then returns a list.: def scan(self, input): identifiedWords = [] words = input.split(" ") for i in len(words): # check if it's a number first try: identifiedWords[i] = ('number', int(words[i])) except ValueError: # directions if words[i].lower() == 'north': identifiedWords[i] = ('direction', 'north') elif words[i].lower() == 'east': identifiedWords[i] = ('direction', 'east') ... # error else: identifiedWords[i] = ('error', words[i]) return identifiedWords Outside of my ex48 folder I'm trying to use this function in powershell. I'm doing: &gt;&gt;&gt; from ex48 import lexicon &gt;&gt;&gt; lexicon.scan("north south") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: 'module' object has no attribute 'scan' &gt;&gt;&gt; The function should return [('direction', 'north'), ('direction', 'south') Am I doing something wrong with the import or is the syntax of the scan function wrong?
has answer: http://stackoverflow.com/a/48902821
has answer: http://stackoverflow.com/a/48902864
type: UnansweredQuestion
tagged with: python
tagged with: attributeerror
has title: Python 2: AttributeError: 'module' object has no attribute 'scan'
tagged with: import

http://stackoverflow.com/a/48837142
has body: try this, import pytz from datetime import datetime now = datetime.now(tz=pytz.UTC)
downvote count: 0
answers question: http://stackoverflow.com/q/48836549
type: Answer
score: 3
upvote count: 3

http://stackoverflow.com/comment/84672144
has text: just read in each line, split it up into a list, then grab the paths you need
comment on: http://stackoverflow.com/q/48833839
score: 0
type: Comment
type: QuestionComment

alpha-transparency
type: Tag
tags question: http://stackoverflow.com/q/48877967
tag name: alpha-transparency

http://stackoverflow.com/comment/84844347
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48919005
has text: usa_signup_age.groupby('gender')['age'].mean()?
score: 0

http://stackoverflow.com/comment/84771104
score: 5
comment on: http://stackoverflow.com/q/48883427
type: Comment
type: QuestionComment
has text: What have you attempted or considered so far?

web-services
type: Tag
tags question: http://stackoverflow.com/q/48807995
tags question: http://stackoverflow.com/q/48903395
tag name: web-services

http://stackoverflow.com/comment/136227579
has text: When my data size is large, i.e. 1000 then which graph should be used for better visualization and how?
type: Comment
comment on: http://stackoverflow.com/a/48859319
score: 0
type: AnswerComment

http://stackoverflow.com/a/48828290
has body: You can use the following with set_index, groupby, and resample: #First make sure day_of_reservation is a datetime dtype: df['day_of_reservation'] = pd.to_datetime(df['day_of_reservation']) df.set_index('day_of_reservation')\ .groupby(['location','day_of_drive'], sort=False)['number_of_bookings']\ .resample('D').asfreq().fillna(0)\ .reset_index() Output: location day_of_drive day_of_reservation number_of_bookings 0 foo 01-01-2015 2014-12-24 1.0 1 foo 01-01-2015 2014-12-25 0.0 2 foo 01-01-2015 2014-12-26 1.0 3 foo 01-01-2015 2014-12-27 0.0 4 foo 01-01-2015 2014-12-28 0.0 5 foo 01-01-2015 2014-12-29 3.0 6 foo 01-01-2015 2014-12-30 2.0 7 foo 01-01-2015 2014-12-31 1.0 8 foo 02-01-2015 2014-12-29 2.0 9 foo 02-01-2015 2014-12-30 0.0 10 foo 02-01-2015 2014-12-31 1.0 11 foo 02-01-2015 2015-01-01 1.0 12 bar 25-06-2016 2016-03-07 1.0
type: Answer
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48827580
answers question: http://stackoverflow.com/q/48827580
score: 2
has comment: http://stackoverflow.com/comment/84664788
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/a/49006837
has comment: http://stackoverflow.com/comment/85069875
upvote count: 3
has comment: http://stackoverflow.com/comment/85066692
type: Answer
has body: Outperforming both methods In method one you are accessing the array twice. If it doesn't fit in the cache, the data will be read two times from RAM which lowers the performance. Additionally it is possible that temporary arrays are created as mentioned in the comments. Method two is more cache friendly, since you are accessing a smaller part of the array twice, which is likely to fit in cache. The downsides are slow looping and more function calls, which are also quite slow. To get a good performance here it is recommended to compile the code, which can be done using cython or numba. Since the cython version is some more work (annotating, need of a seperate compiler), I will show how to do this using Numba. import numba as nb @nb.njit(fastmath=True, cache=True) def method3(arr, low, high): out = np.empty(arr.shape, dtype=nb.boolean) for i in range(arr.shape[0]): for j in range(arr.shape[1]): for k in range(arr.shape[2]): out[i,j,k]=arr[i,j,k] &lt; low or arr[i,j,k] &gt; high return out Using arr = np.random.random((10, 1000, 1000)) this outperforms your method_1 by a factor of two and your method_2 by 50 percent on my PC (Core i7-4771, python 3.5, windows) This is only a simple example, on more complex code, where you can make use of SIMD, and parallel processing which is also very easy to use the performance gain can be a lot bigger. On non compiled code vectorization is usualy but not always (as shown) the best you can do, but it will always lead to a bad cache behaiviour which can lead to suboptimal performance if the chunks of data you are acessing don't fit at least in L3 cache. On some other problems there will be also a performance hit if the data can't fit in the much smaller L1 or L2 cache. Another advantage will be automatic inlining of small njited functions in a njited function which calls this functions.
answers question: http://stackoverflow.com/q/48887461
downvote count: 0
score: 3

http://stackoverflow.com/comment/84886277
type: QuestionComment
has text: "But I spent a lot of time on the one above, and although it is very complicated, I wanted to know if I was on the right track." - unfortunately, you weren't. It's not just a matter of fixing "the problem"; your failed attempt is *deeply* wrong, with lots and lots of problems.
score: 0
comment on: http://stackoverflow.com/q/48939473
type: Comment

http://stackoverflow.com/q/48932729
type: Question
has title: Obtain MAC address from IP address
has answer: http://stackoverflow.com/a/48933126
answer count: 1
tagged with: mac-address
score: 0
has comment: http://stackoverflow.com/comment/84872910
has comment: http://stackoverflow.com/comment/84872854
tagged with: python-3.x
tagged with: python
has body: I am just learning python 3.6.4 and I'm trying to get this code to work... I have a list of ip addresses (on my LAN) and I need to obtain the associated mac address for each ip in the list. When I run the code I get this error: ip_addresses_as_bytes = str.encode(ip_addresses) TypeError: descriptor 'encode' requires a 'str' object but received a 'list' I can't figure out how to convert the individual list items to bytes. import subprocess import re def get_mac_addresses(ip_addresses): for ip_address in ip_addresses: subprocess.Popen(["ping", "-c 1", ip_address], stdout=subprocess.PIPE) proc = subprocess.Popen("arp -a", stdout=subprocess.PIPE) data = proc.communicate()[0] results = [] ip_address_as_bytes = str.encode(ip_address) type(ip_address_as_bytes) # ensure it is byte representation ip_addresses_as_bytes = str.encode(ip_addresses) type(ip_addresses_as_bytes) for ip_address_as_bytes in ip_addresses_as_bytes[:]: if ip_address_as_bytes in data: ip_data = data[data.find(ip_address_as_bytes):] mac = re.search(r"(([a-f\d]{1,2}:){5}[a-f\d]{1,2})", ip_data) if mac is None: mac = re.search(r"(([a-f\d]{1,2}-){5}[a-f\d]{1,2})", ip_data) if mac is not None: mac = mac.groups()[0].replace('-', ':').upper() else: mac = '00:00:00:00:00:00' ip_addresses = ip_addresses_as_bytes.decode() type(ip_addresses) # ensure it is string representation ip_address = ip_address_as_bytes.decode() type(ip_address) # ensure it is string representation ip_addresses.remove(ip_address) results += ip_address, mac return results I appreciate any help. Thanks!
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48933126

http://stackoverflow.com/comment/84709439
has text: @JonClements No. The commas do not count as the number of characters. They only simply need to be there to create columns. Only the letters (CCTTGUAA for example) count as characters.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48852382
score: 0

http://stackoverflow.com/a/48955567
score: 1
has body: You could use the following approach: Melt df to get: In [194]: melted = pd.melt(df, var_name='col'); melted Out[194]: col value 0 Z1 A(Z1W1) 1 Z1 A(Z1W3) 2 Z1 B(Z1W1) 3 Z1 B(Z1W2) 4 Z2 A(Z2W1) 5 Z2 B(Z2W1) 6 Z2 7 Z2 8 Z3 A(Z3W1) 9 Z3 A(Z3W2) 10 Z3 A(Z3W4) 11 Z3 12 Z4 B(Z4W2) 13 Z4 B(Z4W3) 14 Z4 B(Z4W4) 15 Z4 Use regex to extract row and value columns: In [195]: melted'row','value' = melted['value'].str.extract(r'(.*)\((.*)\)', expand=True); melted Out[195]: col value row 0 Z1 Z1W1 A 1 Z1 Z1W3 A 2 Z1 Z1W1 B 3 Z1 Z1W2 B 4 Z2 Z2W1 A 5 Z2 Z2W1 B 6 Z2 NaN NaN 7 Z2 NaN NaN 8 Z3 Z3W1 A 9 Z3 Z3W2 A 10 Z3 Z3W4 A 11 Z3 NaN NaN 12 Z4 Z4W2 B 13 Z4 Z4W3 B 14 Z4 Z4W4 B 15 Z4 NaN NaN Group by col and row and join the values together: In [185]: result = melted.groupby(['col', 'row'])['value'].agg(','.join) In [186]: result Out[186]: col row Z1 A Z1W1,Z1W3 B Z1W1,Z1W2 Z2 A Z2W1 B Z2W1 Z3 A Z3W1,Z3W2,Z3W4 Z4 B Z4W2,Z4W3,Z4W4 Name: value, dtype: object Add the row values to the value values: In [188]: result['value'] = result['row'] + '(' + result['value'] + ')' In [189]: result Out[189]: row value col Z1 A A(Z1W1,Z1W3) Z1 B B(Z1W1,Z1W2) Z2 A A(Z2W1) Z2 B B(Z2W1) Z3 A A(Z3W1,Z3W2,Z3W4) Z4 B B(Z4W2,Z4W3,Z4W4) Overwrite the row column values with groupby/cumcount values to setup the upcoming pivot: In [191]: result['row'] = result.groupby(level='col').cumcount() In [192]: result Out[192]: row value col Z1 0 A(Z1W1,Z1W3) Z1 1 B(Z1W1,Z1W2) Z2 0 A(Z2W1) Z2 1 B(Z2W1) Z3 0 A(Z3W1,Z3W2,Z3W4) Z4 0 B(Z4W2,Z4W3,Z4W4) Pivoting produces the desired result: result = result.pivot(index='row', columns='col', values='value') import pandas as pd df = pd.DataFrame({ 'Z1': ['A(Z1W1)', 'A(Z1W3)', 'B(Z1W1)', 'B(Z1W2)'], 'Z2': ['A(Z2W1)', 'B(Z2W1)', '', ''], 'Z3': ['A(Z3W1)', 'A(Z3W2)', 'A(Z3W4)', ''], 'Z4': ['B(Z4W2)', 'B(Z4W3)', 'B(Z4W4)', '']}, index=[0, 1, 2, 3],) melted = pd.melt(df, var_name='col').dropna() melted'row','value' = melted['value'].str.extract(r'(.*)\((.*)\)', expand=True) result…
answers question: http://stackoverflow.com/q/48954723
has comment: http://stackoverflow.com/comment/84918255
type: Answer
upvote count: 1
downvote count: 0

http://stackoverflow.com/comment/84883902
type: Comment
has text: I assumed it was a list (often called array), didn't realize it was `np.array`.
comment on: http://stackoverflow.com/a/48938209
type: AnswerComment
score: 0

http://stackoverflow.com/q/48828633
has comment: http://stackoverflow.com/comment/84661683
tagged with: twitter
has comment: http://stackoverflow.com/comment/84662018
has answer: http://stackoverflow.com/a/48880843
has comment: http://stackoverflow.com/comment/84661550
has comment: http://stackoverflow.com/comment/84662195
has comment: http://stackoverflow.com/comment/84661198
score: 2
answer count: 1
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84662169
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84661886
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/10081327
has title: 401: Authorization Required when retrieving Request Token from Twitter API
upvote count: 2
tagged with: twitter-oauth
has comment: http://stackoverflow.com/comment/84661482
type: Question
has body: I'm working on a Django application which retrieves some data from Twitter, and I need to work with requests manually since it's for an exam whose main focus is for us to learn how to work with network protocols such as HTTP. So please don't suggest me to use a wrapper. My issue is that whenever I try to request the initial request token (with a POST request that is referenced in this doc and also here), I receive a 401: Authorization Required and I have no clue what could be causing it, since I'm including the Authorization header in exactly the format required by the docs I've linked. It may be that while working with urllib I don't manage to make the POST request as I wanted, or perhaps there's something wrongin how I made the signature/where I've placed it in the header, even though in my opinion it should be alright. Here's my code to handle the request to "sign in with Twitter": def sign(request): url = 'https://api.twitter.com/oauth/request_token' #I store consumer key, consumer secret and callback url in a txt dir_path = path.dirname(path.realpath(__file__)) with open(path.join(dir_path, 'credentials.txt'), 'r') as TweetCred: creds = TweetCred.read().split(linesep) oauth_consumer_key = creds[0].split()[1] oauth_callback = creds[1].split()[1] consumer_secret = creds[2].split()[1] oauth_nonce = ''.join(SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(32)) #Desperate to understand what could be causing the error, I tried to use an integer timestamp sinceit was integer in the examples oauth_timestamp = int(time.time()) parameter_string = ( 'oauth_nonce=' + urllib.parse.quote(oauth_nonce, safe='') + '&amp;oauth_callback=' + urllib.parse.quote(oauth_callback, safe='') + '&amp;oauth_signature_method=' + urllib.parse.quote('HMAC-SHA1', safe='') + '&amp;oauth_timestamp=' + urllib.parse.quote(str(oauth_timestamp), safe='') + '&amp;oauth_consumer_key=' + urllib.parse.quote(oauth_consumer_key, safe='') + '&amp;oauth_version=' + urllib.parse.quo…

http://stackoverflow.com/comment/84810030
type: Comment
type: QuestionComment
has text: I don't know. I don't use `AWS` but probably.
comment on: http://stackoverflow.com/q/48901990
score: 0

http://stackoverflow.com/a/48907901
has body: This is certainly possible in numpy alone if you harness the power of broadcasting. You just have to code out the inner distance-norm calculation in a vectorized way: X1 = X[:, np.newaxis, :] X2 = X[np.newaxis, :, :] K = np.exp(-np.sum((X1 - X2)**2, axis=-1))
upvote count: 6
type: Answer
score: 6
downvote count: 0
answers question: http://stackoverflow.com/q/48907216

header
type: Tag
tags question: http://stackoverflow.com/q/48925047
tag name: header

http://stackoverflow.com/comment/84832375
type: Comment
comment on: http://stackoverflow.com/q/48905470
type: QuestionComment
score: 0
has text: Where have you read that `reduceByKey()` is more efficient? Can you provide a link?

http://stackoverflow.com/comment/105376109
has text: @JohnE That doc doesn't mention lower-case `d` like in the example, only `days`. But only `2d` seems to work, while `2days` doesn't (?).
comment on: http://stackoverflow.com/a/48856442
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/q/48954128
tagged with: python
upvote count: 1
has body: I'm building a web app right now that has a couple of text-fields that I would ideally like to be able to copy (individually) using a "copy" button next to each field. Right now I'm attempting to write a Pyperclip function in my main file, and then passing that as an onclick value for a button, but as soon as the page loads, the Pyperclip function executes and my clipboard is updated without pressing anything. So for example: @app.route('/converted.html', methods = ['GET', 'POST']) def converted(): pyperclip_Test = pyperclip.copy("apple") return render_template('converted.html', pyperclip_Test = pyperclip_Test) Then in my template file: Test Data that I want to copy I know the pyperclip function isn't copying that div - I retracted the original data that I can pass - but the problem still remains that the script executes without me pressing the button. Any idea on how to get this working?
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48954338
score: 0
tagged with: pyperclip
answer count: 1
tagged with: flask
favorite count: 0
has title: Making A Pyperclip Button in Flask
type: UnansweredQuestion

http://stackoverflow.com/a/48929999
answers question: http://stackoverflow.com/q/48929281
has comment: http://stackoverflow.com/comment/84867586
type: Answer
has comment: http://stackoverflow.com/comment/84867949
score: 0
has body: use math to reduce the problem complexity: The sum of an arithmetic progression is given by (m+n)*(m-n+1)*0.5 use np.vectorize to speed up the array operation: ten_m = 10000000 def sum10m_py(n): return (1+n)*(ten_m-n*ten_m+1)*0.5 sum_np = np.vectorize(sum_py) pick the elements you want, and then apply the vectorized function on it. mask = np.random.randint(0,ten_m,2500) sums = sum_np(ten_million[mask])

http://stackoverflow.com/comment/107855568
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48925086
has text: If you had a representative smaller sample of points you, and others could investigate algorithms...

http://stackoverflow.com/comment/84924129
has text: Your float-cast worsen things: you will use 4 times as much memory as needed. So the original memory is someling like 5.8GB; reshaping when lists are involved probably need the same temp-memory as numpy will allocate a new array (that's a guess; not sure what reshape does with lists). Do you know what you are doing? This float-cast is critical (at least a factor in terms of memory-usage). How much memory is available?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48958509
score: 0

http://stackoverflow.com/comment/84673855
type: QuestionComment
has text: By analysis logs I mean what's output to ... console, or jenkins log, or ...?, when you analyze
comment on: http://stackoverflow.com/q/48833707
score: 0
type: Comment

http://stackoverflow.com/comment/84837717
type: Comment
type: QuestionComment
has text: Does the error occur on the line where you search for the `sysparm_search` or on the line where you switch to `gsft_main`?
comment on: http://stackoverflow.com/q/48915307
score: 0

http://stackoverflow.com/q/48856683
has body: In a regular jupyter notebook, running, for example, the following: from IPython.display import display, Math, Latex display(Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')) produces an equation rendered in LaTeX (via Mathjax). Even though LaTeX works fine in markdown cells, LaTeX equations produced as above do not seem to render in Google Colaboratory. The same happens to the output of functions for example from qutip, which would normally render in latex (for example, qutip.basis(2, 0) would normally render in latex, but doesn't in Colaboratory). Why does this happen? Is there a way to have this work?
linked to: http://stackoverflow.com/q/49573644
has answer: http://stackoverflow.com/a/63714906
answer count: 7
has answer: http://stackoverflow.com/a/69432433
favorite count: 0
tagged with: latex
has answer: http://stackoverflow.com/a/79407136
type: UnansweredQuestion
has title: LaTeX equations do not render in google Colaboratory when using IPython.display.Latex
tagged with: python
upvote count: 15
has answer: http://stackoverflow.com/a/63080695
tagged with: mathjax
downvote count: 0
has answer: http://stackoverflow.com/a/50748163
has answer: http://stackoverflow.com/a/49070276
type: Question
tagged with: google-colaboratory
score: 15
has answer: http://stackoverflow.com/a/57315035

http://stackoverflow.com/comment/84729730
comment on: http://stackoverflow.com/a/48861955
type: AnswerComment
score: 0
type: Comment
has text: Did so, was just looking for a text link like “correct answer“, not expecting the hook.

http://stackoverflow.com/a/61790659
upvote count: 3
has comment: http://stackoverflow.com/comment/140157231
type: Answer
answers question: http://stackoverflow.com/q/48820375
downvote count: 1
score: 2
has body: msvcrt provides access to some useful capabilities on Windows platforms. import msvcrt str = &quot;&quot; while True: c = msvcrt.getch() # reads one byte at a time, similar to getchar() if c == ' ': break str += c print(str) msvcrt is a built-in module, you can read more about in the official documentation.

http://stackoverflow.com/comment/84762486
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48879108
score: 0
has text: also, is `wmic path win32_quickfixengineering get KB2999226` working?

http://stackoverflow.com/q/48856981
type: AnsweredQuestion
score: 3
downvote count: 0
has comment: http://stackoverflow.com/comment/84718844
favorite count: 0
has comment: http://stackoverflow.com/comment/84718130
has comment: http://stackoverflow.com/comment/84718185
type: Question
tagged with: h5py
has body: This is a question about working with multiple HDF5 datasets simultaneously while treating them as one dataset as far as possible. I have multiple .h5 files, each of which contains tens of thousands of images. Let's call the files file01.h5 file02.h5 file03.h5 I now want to create a list or array that contains "pointers" to all images of all three files, without actually loading the images. Here is what I have so far: I first open all files: file01 = h5py.File('file01.h5', 'r') file02 = h5py.File('file02.h5', 'r') file03 = h5py.File('file03.h5', 'r') and add their image datasets to a list: images = [] images.append(file01['images']) images.append(file02['images']) images.append(file03['images']) where file01['images'] is an HDF5 dataset of shape e.g. (52722, 3, 160, 320), i.e. 52722 images. All good so far, none of the content has been loaded into memory yet. Now I want to make these three separate image lists into one so that I can work with it as if it were one large dataset. I tried to do this: images = np.concatenate(images) This is where it breaks. As soon as I concatenate the three HDF5 datasets, it actually loads the images as Numpy arrays and I run out of memory. What would be the best way to solve this? I need a solution that allows me to Numpy-slice and index into the three datasets as if it were one. For example, assume each dataset contained 50,000 images and I wanted to load the third image of each dataset, I need a list images that allows me to index those images as batch = images[[2, 50002, 100002]]
has comment: http://stackoverflow.com/comment/84780014
linked to: http://stackoverflow.com/q/41572696
tagged with: python
has answer: http://stackoverflow.com/a/52726024
upvote count: 3
has comment: http://stackoverflow.com/comment/84718445
answer count: 1
has comment: http://stackoverflow.com/comment/84718315
has title: h5py: How to index over multiple large HDF5 files without loading all their content into memory
accepted answer: http://stackoverflow.com/a/52726024
has comment: http://stackoverflow.com/comment/84718587

http://stackoverflow.com/q/48932612
type: AnsweredQuestion
downvote count: 0
tagged with: qt-signals
accepted answer: http://stackoverflow.com/a/48933615
type: Question
score: 1
has title: Cant assign a variable through connect method in pyqt
has answer: http://stackoverflow.com/a/48933615
tagged with: pyqt
upvote count: 1
answer count: 1
favorite count: 0
tagged with: qt-slot
has body: When trying to connect a button press to the assignment of a variable, PyCharm refuses to accept the syntax, stating Can't assign to function call with red syntax underlining. Here is the following code: self.button.clicked.connect(lambda : outside_object.username = self.username) How can I assign a variable without calling something similar to a setter method such as self.button.clicked.connect(lambda: outside_object.assign_username(self.username))?
tagged with: python

http://stackoverflow.com/comment/84684596
comment on: http://stackoverflow.com/a/48840205
score: 0
type: AnswerComment
has text: the same kind of error in this line of code as well coming ,anything to be modified stockdata['kama'] = stockdata['kama'](-1) if stockdata['kama'][-1] !=0 else stockdata['close'] + stockdata['smooth']*(stockdata['close'] - stockdata['kama'](-1) if stockdata['kama'](-1) !=0 else stockdata['close'])
type: Comment

http://stackoverflow.com/q/48815110
linked to: http://stackoverflow.com/q/25735134
has body: I have connected to a FTP and the connection is successful. import ftplib ftp = ftplib.FTP('***', '****','****') listoffiles = ftp.dir() print (listoffiles) I have a few CSV files in this FTP and a few folders which contain some more CSV's. I need to identify the list of folders in this location (home) and need to navigate into the folders. I think cwd command should work. I also read the CSV stored in this FTP. How can I do that? Is there a way to directly load the CSV's here into Pandas?
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
favorite count: 0
tagged with: ftp
linked to: http://stackoverflow.com/q/46436896
tagged with: ftplib
type: UnansweredQuestion
has title: Read a CSV file stored in a FTP in Python
score: 6
upvote count: 6
has answer: http://stackoverflow.com/a/62362835
has answer: http://stackoverflow.com/a/48817105
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84635413
downvote count: 0

http://stackoverflow.com/comment/84910138
type: QuestionComment
has text: @thesilkworm, I am looking for a value in row 1 in column A anywhere in column B, also where row 1 column C equals "Missing"
score: 0
comment on: http://stackoverflow.com/q/48951380
type: Comment

http://stackoverflow.com/comment/84836496
has text: I am currently looking into the simplest case, to have a working design with a single thread, no caching and no authentication/authorization. It's on an abstract level
score: 0
comment on: http://stackoverflow.com/q/48912845
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48880557
has title: Print the decision path of a specific sample in a random forest classifier
accepted answer: http://stackoverflow.com/a/48884917
tagged with: pandas
has body: How to print the decision path of a randomforest rather than the path of individual trees in a randomforest for a specific sample. import numpy as np import pandas as pd from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier X, y = make_classification(n_samples=1000, n_features=6, n_informative=3, n_classes=2, random_state=0, shuffle=False) # Creating a dataFrame df = pd.DataFrame({'Feature 1':X[:,0], 'Feature 2':X[:,1], 'Feature 3':X[:,2], 'Feature 4':X[:,3], 'Feature 5':X[:,4], 'Feature 6':X[:,5], 'Class':y}) y_train = df['Class'] X_train = df.drop('Class',axis = 1) rf = RandomForestClassifier(n_estimators=10, random_state=0) rf.fit(X_train, y_train) decision_path for random forest was introduced in v0.18. (http://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html) However, it outputs a sparse matrix which I'm not certain how to make sense of. Can anyone advise on how best to print the decision path of that specific sample and then visualize it? #Extracting the decision path for instance i = 12 i_data = X_train.iloc[12].values.reshape(1,-1) d_path = rf.decision_path(i_data) print(d_path) Output: (&lt;1x1432 sparse matrix of type '' with 96 stored elements in Compressed Sparse Row format>, array([ 0, 133, >282, 415, 588, 761, 910, 1041, 1182, 1309, 1432], dtype=int32))
favorite count: 0
tagged with: machine-learning
tagged with: python
upvote count: 6
type: AnsweredQuestion
downvote count: 1
type: Question
score: 5
tagged with: random-forest
answer count: 1
tagged with: scikit-learn
has answer: http://stackoverflow.com/a/48884917

http://stackoverflow.com/q/48864668
has comment: http://stackoverflow.com/comment/84906321
answer count: 1
has comment: http://stackoverflow.com/comment/84732521
favorite count: 0
tagged with: python
has body: So I have data that looks like Manufacturer Mean 0 DAF 57.036199 1 Fiat 42.296814 2 Ford 54.546769 3 Iveco 41.678711 4 MAN 50.764308 5 Mercedes Benz 49.093340 6 Renault 47.384080 7 Scania 46.317282 8 Volkswagen 50.938158 9 Volvo 43.382830 I am trying to plot a bar graph using the above data. I want the values above 48 to be coloured differently and the bottom 3 to be coloured differently. I tried using the code below but it gives me the following error: TypeError: unsupported operand type(s) for -: 'str' and 'float' The code I have written to make the graph: plt.figure() plt.bar(meansOfRoadGoingVehicles_sort['Manufacturer'], meansOfRoadGoingVehicles_sort['Mean']) plt[0:7].set_color('b') plt[6].set_color('grey') plt[8:11].set_color('r') plt.show()
duplicate of: http://stackoverflow.com/q/18903750
type: AnsweredQuestion
downvote count: 0
has answer: http://stackoverflow.com/a/48866563
accepted answer: http://stackoverflow.com/a/48866563
score: 1
type: Question
has title: Colouring the bars of a bar graph differently using pandas and matplotlib
tagged with: matplotlib
linked to: http://stackoverflow.com/q/18903750
tagged with: graph-coloring
tagged with: pandas
upvote count: 1

http://stackoverflow.com/a/48919217
answers question: http://stackoverflow.com/q/48842812
accepted answer of: http://stackoverflow.com/q/48842812
has body: The problem was within my settings.py - I wasn't pointing the project to the correct database settings - username and password. I changed the settings to reflect those of my pythonanywhere details, and then I could operate manage.py properly from there.
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48842500
has title: How to fill numpy array by row and column
tagged with: multidimensional-array
type: UnansweredQuestion
tagged with: python
type: Question
tagged with: numpy
tagged with: arrays
has answer: http://stackoverflow.com/a/48842533
score: 0
has body: I want to fill the first and the last row and the first and the last column of a grid with 4. Input: grid = np.zeros((5, 5)) [[ 0. 0. 0. 0. 0. ] [ 0. 0. 0. 0. 0. ] [ 0. 0. 0. 0. 0. ] [ 0. 0. 0. 0. 0. ] [ 0. 0. 0. 0. 0. ]] output: [[ 4. 4. 4. 4. 4. ] [ 4. 0. 0. 0. 4. ] [ 4. 0. 0. 0. 4. ] [ 4. 0. 0. 0. 4. ] [ 4. 4. 4. 4. 4. ]] I tried to do this with a for loop but is there a better option than that?
answer count: 1

http://stackoverflow.com/comment/84871290
type: AnswerComment
comment on: http://stackoverflow.com/a/48931758
score: 0
type: Comment
has text: @FedericoOlivieri I did provide an example. See the other answer to your question, and compare the two lines I wrote with the relevant lines you originally wrote.

snappy
type: Tag
tag name: snappy
tags question: http://stackoverflow.com/q/48919925

http://stackoverflow.com/comment/84776375
comment on: http://stackoverflow.com/a/48882591
has text: "C:\Users\OB_User\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas\core\groupby.py", line 2934, in _get_grouper raise KeyError(gpr) KeyError: 'Switch Label/ID'
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48838641
upvote count: 1
has body: Not always there are distributed modules packaged as one package in python. It cannot be done.
score: -1
type: Answer
answers question: http://stackoverflow.com/q/48838613
downvote count: 2

http://stackoverflow.com/comment/84887399
comment on: http://stackoverflow.com/q/48940039
score: 1
has text: the cleanest would probably be `np.linspace(0, 1, overlap+1)`
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84616378
has text: incredible! Thank you
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48805720
type: AnswerComment

http://stackoverflow.com/q/48858223
accepted answer: http://stackoverflow.com/a/48914751
score: 2
tagged with: selenium-chromedriver
type: AnsweredQuestion
tagged with: selenium
tagged with: web-scraping
has body: I'm using chromedriver with selenium for python. I would like to save some settings for an extention, so that the settings come back everytime I load chromedriver with that extention. See below, I would like to save username and password I'm currently loading extentions as below. def __init__(self): capa = DesiredCapabilities.CHROME capa["pageLoadStrategy"] = "none" chrome_options = Options() chrome_options.add_extension('/home/simonsays/PycharmProjects/lbc_piscine_spider/chrome_extentions/Cookie-AutoDelete_v2.1.2.crx') chrome_options.add_extension('/home/simonsays/PycharmProjects/lbc_piscine_spider/chrome_extentions/Random-User-Agent_v2.1.10.crx') chrome_options.add_extension('/home/simonsays/PycharmProjects/lbc_piscine_spider/chrome_extentions/Proxy-Auto-Auth_v2.0.crx') self.driver1 = webdriver.Chrome("/var/chromedriver/chromedriver", desired_capabilities=capa,chrome_options=chrome_options)
type: Question
answer count: 1
downvote count: 0
has title: Save settings for extentions in Chromedriver using selenium with python
linked to: http://stackoverflow.com/q/31062789
has answer: http://stackoverflow.com/a/48914751
favorite count: 0
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84799331

http://stackoverflow.com/comment/84843853
score: 1
comment on: http://stackoverflow.com/a/48918733
type: AnswerComment
has text: Nice! Didn't think of using `linspace` like this.
type: Comment

http://stackoverflow.com/comment/84918767
type: AnswerComment
comment on: http://stackoverflow.com/a/48955930
type: Comment
score: 0
has text: @wim Not true. It was in the title the whole time. (At least as far as I can tell, looking at the edit history)

http://stackoverflow.com/q/48904574
accepted answer: http://stackoverflow.com/a/48904673
linked to: http://stackoverflow.com/q/43214305
has answer: http://stackoverflow.com/a/48904732
has comment: http://stackoverflow.com/comment/84814822
possible better answer: http://stackoverflow.com/a/48904709
has comment: http://stackoverflow.com/comment/84814884
has answer: http://stackoverflow.com/a/48904709
has comment: http://stackoverflow.com/comment/84814768
type: Question
has answer: http://stackoverflow.com/a/48904673
has comment: http://stackoverflow.com/comment/84814948
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84815335
score: -1
has comment: http://stackoverflow.com/comment/84815165
has comment: http://stackoverflow.com/comment/84815465
has comment: http://stackoverflow.com/comment/84815188
has title: Is there any bug in Python strip() function?
duplicate of: http://stackoverflow.com/q/43214305
has comment: http://stackoverflow.com/comment/84814983
has body: Creating two strings: s1 = "sha1:abcd" s2 = "sha1:wxyz" Applying .strip() function on both strings: s1.strip("sha1:") &gt;&gt;&gt; 'bcd' s2.strip("sha1:") &gt;&gt;&gt; 'wxyz' I expected the following output: s1.strip("sha1:") &gt;&gt;&gt; 'abcd' s2.strip("sha1:") &gt;&gt;&gt; 'wxyz' I am aware that strip() function is deprecated. I am just curious to know the issue. I went through official docs, but found no special mentions about ":a" or anything like that. And also I am aware of other alternatives, we can use split("sha1:") or strip("sha1") followed by strip(":"), gives the desired output.
upvote count: 3
answer count: 3
tagged with: python
downvote count: 4
favorite count: 0

http://stackoverflow.com/q/48808460
has comment: http://stackoverflow.com/comment/84620466
answer count: 1
has comment: http://stackoverflow.com/comment/84620514
has body: I am having trouble getting the second argument I am sending to a Python script? I am unsure of how to fix it and changing the second argument to a value or putting a %1 in front of the arguments has not worked. Here is my current code does anyone know what the error might be? Batch File Code: `@echo off` set /p UserInputPath=Enter the location of your development unit? set /p ScriptPath =Enter script path? python part2.py %UserInputPath% %ScriptPath% Python File Code: unitPath = sys.argv[1] scriptLocation = sys.argv[2] scriptLocation = sys.argv[2] IndexError: list index out of range
has title: Invalid Index Error
accepted answer: http://stackoverflow.com/a/48808840
has comment: http://stackoverflow.com/comment/84624961
tagged with: python
has comment: http://stackoverflow.com/comment/84620614
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48808840
linked to: http://stackoverflow.com/q/10552812
has comment: http://stackoverflow.com/comment/84620278
type: Question
score: 0
tagged with: batch-file

selenium-chromedriver
tags question: http://stackoverflow.com/q/48915307
tags question: http://stackoverflow.com/q/48916783
tags question: http://stackoverflow.com/q/48960059
tags question: http://stackoverflow.com/q/48860738
tags question: http://stackoverflow.com/q/48954842
tags question: http://stackoverflow.com/q/48956802
tags question: http://stackoverflow.com/q/48861378
tags question: http://stackoverflow.com/q/48930590
tag name: selenium-chromedriver
tags question: http://stackoverflow.com/q/48825633
tags question: http://stackoverflow.com/q/48937090
tags question: http://stackoverflow.com/q/48858223
tags question: http://stackoverflow.com/q/48843826
tags question: http://stackoverflow.com/q/48957851
type: Tag
tags question: http://stackoverflow.com/q/48901728

http://stackoverflow.com/a/48942908
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48942801
score: 1
has body: If you load the json, and then feed the Dataframe the part of the json needed, then you can get it like: Code: def json_csv(filename): with open(filename) as data_file: data = json.load(data_file) return pd.DataFrame(data['profile_set']) Test Code: print(json_csv('file1')) ResultsL created_datetime doc_type first_name key last_name \ 0 2018-01-06T12:52:09 PROFILE Robert 123 John 1 2018-01-07T11:32:07 PROFILE Lily 456 Hubert mem_list middle_name 0 {'mem_num': '10001', 'current_flag': 'Y', 'mem... [] 1 {'mem_num': '10002', 'current_flag': 'Y', 'mem... []
downvote count: 0
has comment: http://stackoverflow.com/comment/84895819

http://stackoverflow.com/a/48821937
has body: Yes. Immediately, you should be using a for loop. Recursion is generally not Pythonic. Second, use built in tools: from itertools import dropwhile def remove_leading_items(l, item): return list(dropwhile (lambda x: x == item, l)) Or return list(dropwhile(item.__eq__, l)) Edit Out of curiosity, I did some experiments with different approaches to this problem: from itertools import dropwhile from functools import partial from operator import eq def _eq_drop(l, e): return dropwhile(e.__eq__, l) def lam_drop(l, e): return dropwhile(lambda x:x==e, l) def partial_drop(l, e): return dropwhile(partial(eq, e), l) First, with a list that is entirely dropped: i.e. (1, 1, 1, ...) In [64]: %%timeit n = 10000; t0 = (1,)*n; t1 = (1,) + (0,)*(n-1); t2 = (1,)*(n//2) + (0,)*(n//2); ...: list(_eq_drop(t0, 1)) ...: 1000 loops, best of 3: 389 µs per loop In [65]: %%timeit n = 10000; t0 = (1,)*n; t1 = (1,) + (0,)*(n-1); t2 = (1,)*(n//2) + (0,)*(n//2); ...: list(lam_drop(t0, 1)) ...: 1000 loops, best of 3: 1.19 ms per loop In [66]: %%timeit n = 10000; t0 = (1,)*n; t1 = (1,) + (0,)*(n-1); t2 = (1,)*(n//2) + (0,)*(n//2); ...: list(partial_drop(t0, 1)) ...: 1000 loops, best of 3: 893 µs per loop So __eq__ is clearly the fastest in this situation. I like it, but it makes use of a dunder-method directly, which is sometimes frowned upon. The dropwhile(partial(eq... approach (wordy, yet explicit) is somewhere inbetween that and the sluggish, clumsy lambda approach comes last. Not surprising. Now, when half is dropped, i.e (1, 1, 1, ..., 0, 0, 0): In [52]: %%timeit n = 10000; t0 = (1,)*n; t1 = (1,) + (0,)*(n-1); t2 = (1,)*(n//2) + (0,)*(n//2); ...: list(_eq_drop(t2, 1)) ...: 1000 loops, best of 3: 245 µs per loop In [53]: %%timeit n = 10000; t0 = (1,)*n; t1 = (1,) + (0,)*(n-1); t2 = (1,)*(n//2) + (0,)*(n//2); ...: list(lam_drop(t2, 1)) ...: 1000 loops, best of 3: 652 µs per loop In [54]: %%timeit n = 10000; t0 = (1,)*n; t1 = (1,) + (0,)*(n-1); t2 = (1,)*(n//2) + (0,)*(n//2); ...: list(partial_dro…
has comment: http://stackoverflow.com/comment/84649266
has comment: http://stackoverflow.com/comment/84647611
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48821856
has comment: http://stackoverflow.com/comment/84649145
type: Answer
accepted answer of: http://stackoverflow.com/q/48821856
score: 8
upvote count: 8
has comment: http://stackoverflow.com/comment/84647456
has comment: http://stackoverflow.com/comment/84649334
has comment: http://stackoverflow.com/comment/84675615

http://stackoverflow.com/a/48901463
score: 0
has comment: http://stackoverflow.com/comment/84808371
has comment: http://stackoverflow.com/comment/84819012
type: Answer
answers question: http://stackoverflow.com/q/48900647
has body: Can we see the full code of how you implemented the API call, but also try converting it into a collection first. try from collection import Counter Counter(data)
has comment: http://stackoverflow.com/comment/84817177

http://stackoverflow.com/comment/84661865
has text: Do you need this to be in pure python? Because you could use `pandas.dataframe.to_latex()` and then use [pandoc](https://pandoc.org/). E: Obviously, you can call `pandoc` from python, but maybe you can't use pandoc.
score: 0
comment on: http://stackoverflow.com/q/48828954
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84856728
comment on: http://stackoverflow.com/q/48925255
score: 0
type: Comment
type: QuestionComment
has text: The error/traceback seems incomplete. Also the code is incomplete, no chance of reproducing your issue.

http://stackoverflow.com/q/48958267
has answer: http://stackoverflow.com/a/48995778
accepted answer: http://stackoverflow.com/a/48995778
score: 1
has title: How can I use CoreBluetooth for Python without giving up the main thread
upvote count: 1
type: Question
tagged with: core-bluetooth
tagged with: event-loop
has body: I am trying to implement a generic BLE interface that will run on OS/X and talk to a BLE peripheral device. The peripheral is very complex: It can be queried, sent hundreds of different commands, offers notifications, etc. I need to be able to connect to it, send it commands, read responses, get updates, etc. I have all of the code I need but am being frustrated by one thing: From the limited information I can find online, it looks like the only way to make CoreBluetooth's delegate callbacks get called is by running: from PyObjCTools import AppHelper # [functional CoreBluetooth code that scans for peripherals] AppHelper.runConsoleEventLoop() The problem is that AppHelper.runConsoleEventLoop blocks the main thread from continuing, so I cannot execute code to interact with the peripheral. I have tried running the event loop: From a different thread ---> Delegate callbacks not called From a subprocess ---> Delegate callbacks not called From a forked child ---> Python crashes with error message: The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec(). From multiprocessing.Pool(1).apply_async(f) ---> Python crashes with error message: The process has forked and you cannot use this CoreFoundation functionality safely. You MUST exec(). all without success. I do not understand the nature of AppHelper.runConsoleEventLoop. Why does it need to be run in order for the CoreBluetooth delegate callbacks to be called? Is there some other version that can be called that doesn't have to be run on the main thread? I read something on the web about it being GUI related and therefore had to be run on the main thread but my python application does not have any GUI elements. Is there a flag or API that is less concerned with GUI that I could use? Any help would be enormously appreciated. Thanks for your time! Update: I spoke with an iOS/CoreBluetooth expert at work and found out that Dispatch Queues are probably the solution. I dug further and f…
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python
type: AnsweredQuestion

textinput
tags question: http://stackoverflow.com/q/48840912
type: Tag
tag name: textinput
tags question: http://stackoverflow.com/q/48808172

http://stackoverflow.com/comment/84831279
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48912403
has text: That's a lot of code, not an [mcve]. But Warren only takes one or two arguments on initialisation, what were you expecting the third one to do?

http://stackoverflow.com/a/48886746
score: 2
has body: pip3 is a separate command from pip. What you want to do is: pip3 install --upgrade --user pip This will install an updated pip3 in your home folder; on my machine it is ~/.local/lib/python3.5/site-packages. By not using sudo and installing globally, you avoid messing with the version that your package manager provides. Hence the --user option. The wording of the warning from pip3 is because pip always assumes it is the only installed version, which is rarely the case on a linux box. Also, you cannot install pip3 for your python2 installation. It really just is pip for python3.
answers question: http://stackoverflow.com/q/48886551
downvote count: 0
type: Answer
upvote count: 2

http://stackoverflow.com/comment/106281945
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48858449
type: Comment
has text: check this https://stackoverflow.com/questions/6297404/multi-threaded-use-of-sqlalchemy

http://stackoverflow.com/q/48921044
type: UnansweredQuestion
tagged with: python
has body: I made a program that reads pixels from a camera. I have used a while loop. But I can't close the program from terminal without pressing 'Cltrl + C'. I want to close the program using ESC button ( ASCII 27). I tried the following code, which is not working. Any help would be appreciated import cv2 as cv import numpy as np cap = cv2.VideoCapture(0) while True: _, frame = cap.read() redimage = frame[:,:,2] print(redimage) k = cv.waitKey(1) &amp; 0xFF if k == 27: break
duplicate of: http://stackoverflow.com/q/5137238
tagged with: opencv3.0
has title: terminating a python loop
has answer: http://stackoverflow.com/a/48921371
upvote count: 1
has comment: http://stackoverflow.com/comment/84848425
downvote count: 1
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48921841
score: 0
favorite count: 0
linked to: http://stackoverflow.com/q/5137238

http://stackoverflow.com/comment/84871087
type: AnswerComment
score: 0
type: Comment
has text: I tried this too.. $ conda update anaconda-navigator $ conda update navigator-updater Still showing that error
comment on: http://stackoverflow.com/a/48931956

http://stackoverflow.com/comment/84659993
has text: The `render_table` just render theses columns in `column_default_show` but i just put `select` field. I just want after init my table add new columns from a list of string (string are the names of the future columns) next to this last columns (`select`)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48806554
type: QuestionComment

http://stackoverflow.com/comment/84769375
type: QuestionComment
has text: problem solved: its the python versioning. python 2.x gives bad output for datetime.now - datetime.now but python 3.x is fine
comment on: http://stackoverflow.com/q/48882468
score: 0
type: Comment

http://stackoverflow.com/q/48919024
has title: python: how to access variable name from list of variable
tagged with: python
has comment: http://stackoverflow.com/comment/84844928
type: UnansweredQuestion
has body: I want to access the variables from the list of variables to update it. I wonder if there is any way to do this with list rather than accessing variable as string described here dWaa, dWax, dWya, db, dby = gradients['dWaa'], gradients['dWax'], gradients['dWya'], gradients['db'], gradients['dby'] for gradient in [dWax, dWaa, dWya, db, dby]: gradient = np.clip(gradient, -10, 10) # I need to update the value of variables(eg. dwaa) here gradients = {"dWaa": dWaa, "dWax": dWax, "dWya": dWya, "db": db, "dby": dby} How can I update the value of variable(eg. dwaa) inside the loop
linked to: http://stackoverflow.com/q/2553354
has comment: http://stackoverflow.com/comment/84844492
type: Question
score: 0
has answer: http://stackoverflow.com/a/48919205
answer count: 1
tagged with: variables

pyperclip
tags question: http://stackoverflow.com/q/48954128
type: Tag
tag name: pyperclip

http://stackoverflow.com/comment/84636922
type: Comment
comment on: http://stackoverflow.com/q/48816433
has text: Is it not normal to ask questions like this here?
score: 0
type: QuestionComment

http://stackoverflow.com/q/48818653
favorite count: 0
has title: Pandas dataframe: omit weekends and days near holidays
accepted answer: http://stackoverflow.com/a/48819829
tagged with: python
type: AnsweredQuestion
downvote count: 0
has body: I have a Pandas dataframe with a DataTimeIndex and some other columns, similar to this: import pandas as pd import numpy as np range = pd.date_range('2017-12-01', '2018-01-05', freq='6H') df = pd.DataFrame(index = range) # Average speed in miles per hour df['value'] = np.random.randint(low=0, high=60, size=len(df.index)) df.info() # DatetimeIndex: 141 entries, 2017-12-01 00:00:00 to 2018-01-05 00:00:00 # Freq: 6H # Data columns (total 1 columns): # value 141 non-null int64 # dtypes: int64(1) # memory usage: 2.2 KB df.head(10) # value # 2017-12-01 00:00:00 15 # 2017-12-01 06:00:00 54 # 2017-12-01 12:00:00 19 # 2017-12-01 18:00:00 13 # 2017-12-02 00:00:00 35 # 2017-12-02 06:00:00 31 # 2017-12-02 12:00:00 58 # 2017-12-02 18:00:00 6 # 2017-12-03 00:00:00 8 # 2017-12-03 06:00:00 30 How can I select or filter the entries that are: Weekdays only (that is, not weekend days Saturday or Sunday) Not within N days of the dates in a list (e.g. U.S. holidays like '12-25' or '01-01')? I was hoping for something like: df = exclude_Sat_and_Sun(df) omit_days = ['12-25', '01-01'] N = 3 # days near the holidays df = exclude_days_near_omit_days(N, omit_days) I was thinking of creating a new column to break out the month and day and then comparing them to the criteria for 1 and 2 above. However, I was hoping for something more Pythonic using the DateTimeIndex. Thanks for any help.
score: 7
has answer: http://stackoverflow.com/a/48819829
has comment: http://stackoverflow.com/comment/84641269
type: Question
possible better answer: http://stackoverflow.com/a/48847025
linked to: http://stackoverflow.com/q/29384696
has answer: http://stackoverflow.com/a/48847025
answer count: 2
tagged with: pandas
upvote count: 7

http://stackoverflow.com/comment/84798292
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48874455
has text: The real issue is that `indentedBlock` uses the `indentStack` list to keep state of what the current column is. After running the parser once, `indentStack` contains `[1, 5]`. If you add another line to your sample that goes back to column 1, or explicitly reset `indentStack` back to [1] your second `parseString` call will succeed.

http://stackoverflow.com/comment/84772094
has text: very nice answer. You will need a second pass to further combine sequences 19 and 25
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48881655
type: Comment

http://stackoverflow.com/comment/84822495
type: QuestionComment
type: Comment
score: 1
comment on: http://stackoverflow.com/q/48852607
has text: sounds to me like it would be helpful to do that in a for loop and put each box in a separate subplot - then you can in the first run easy fix the axis formatting (just format each properly and use `sharex=True` while creating subplots).

http://stackoverflow.com/a/48862904
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48862824
has body: You should probably use numpy and its loadtxt function. If you don't want to rely on numpy, here's what you should know: open returns a file object. To access the file's data, you need to use some methods of file objects, usually read, readline, readlines. Let's say myfile.txt looks like this: 4 5 8 9 5 6 4 7 4 2 3 1 Using numpy, you can have your matrix read in a one-liner: matrix = np.loadtxt("myfile.txt"), given that you propertly imported the numpy module using import numpy as np Using only built-ins, this would look something like: matrix = [] with open("/tmp/myfile.txt", 'r') as file_handler: for line in file_handler: if line.strip(): matrix += [line.strip().split(" ")] and you end up with a list of lists, which is probably less useful than a numpy array if you're working with matrices. In either case you can then split and show the parts you are interested using print(matrix[:y,:x]).
upvote count: 1

http://stackoverflow.com/a/48907389
type: Answer
has body: Alternatively to the hash table solution, you can sort the array (time O(N Log N)), maintain two indexes i, j such that num[i] + num[j] &lt;= sum &lt; num[i] + num[j+1]; every time you increase i, you decrease j by 0 or more to adjust. i starts from 0 and j from the end. At worse you increase i N times and decrease j N times for a total of O(N) operations. In case of equality, you are done. This can be done in-place.
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48904661

http://stackoverflow.com/comment/84684365
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48840042
has text: Not much information but `stockdata['noise'] != 0` returns more than 1 value, so it will be always true... Then, you are dividing by `stockdata['noise']` so probably you have a division by 0
score: 0

http://stackoverflow.com/comment/84699844
score: 0
type: Comment
type: QuestionComment
has text: Why do you have two `i`'s? You should change the 2nd `i` variable to something else to avoid code confusion.
comment on: http://stackoverflow.com/q/48847939

nameerror
tags question: http://stackoverflow.com/q/48834860
tags question: http://stackoverflow.com/q/48937219
tag name: nameerror
tags question: http://stackoverflow.com/q/48899123
tags question: http://stackoverflow.com/q/48901412
tags question: http://stackoverflow.com/q/48960087
tags question: http://stackoverflow.com/q/48894195
type: Tag
tags question: http://stackoverflow.com/q/48935271

http://stackoverflow.com/q/48961076
favorite count: 0
has title: Python - Accepting input parameter when installing package
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
linked to: http://stackoverflow.com/q/18725137
tagged with: setuptools
type: Question
has comment: http://stackoverflow.com/comment/84929648
downvote count: 0
has comment: http://stackoverflow.com/comment/84929248
score: 1
has body: I've written a python module which when imported, assumes the importing file has a predefined folder name at some level up in the folder hierarchy. My module then proceeds to add the predefined folder to sys.path. I want to upload this package to PyPI, but I want to somehow enable the user to input the pre-defined folder name on install. I've looked at: How to obtain arguments passed to setup.py from pip with '--install-option'? which seems closest to what I"m trying to achieve, but the proposed solution doesn't enable a default (user defined) configuration to the packaged module itself. Any ideas?

http://stackoverflow.com/comment/139472730
comment on: http://stackoverflow.com/a/48993273
has text: great! very useful!
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84881271
comment on: http://stackoverflow.com/a/48928535
type: AnswerComment
score: 0
has text: It works now, thank a lot for your help. Just another question: the script takes several minutes to complete. The proposed code store the date/time when the task starts. Is there any chance to get the date/time at the end? Thank you.
type: Comment

http://stackoverflow.com/comment/84654706
has text: Install using [Link 1](https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html) instead of trying to install it manually.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48825487

http://stackoverflow.com/comment/84801748
score: 0
has text: I'd tried flgs = 0 instead of re.M and nothing changed. Docstring says nth about re.M. Could you let me know what the re.M is briefly about?
comment on: http://stackoverflow.com/a/48879038
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84908859
comment on: http://stackoverflow.com/q/48898104
type: Comment
type: QuestionComment
has text: I'm confused by how, inside the loop, your model makes predictions with 4 states as input, but outside the loop only takes a single state as input? And what does the index `0` mean in `target_f[0][action] = target`?
score: 0

http://stackoverflow.com/comment/84748395
type: QuestionComment
comment on: http://stackoverflow.com/q/48872234
has text: Have you looked at [pd.cut](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html) or [categories](https://pandas.pydata.org/pandas-docs/stable/categorical.html)?
score: 0
type: Comment

http://stackoverflow.com/q/48857725
answer count: 1
has comment: http://stackoverflow.com/comment/87006351
has comment: http://stackoverflow.com/comment/84719398
has body: i am trying to recreate a picture. I take a picture edging it and save it. after i made it grayscale and save it. Found the common pixels of the two images and I am trying to recreate again the picture and i get this error. It is a picture of a road and i am trying to keep only the white lanes. so after i compare the edged picture with the first picture most common pixels are the white ones that represent the lanes of the road. The error is thrown in line marked &lt;———-- near the end of the code listing TypeError: too many data entries newpic is the list in that form `[1,1,1,1,...,1] here is my code and explaining every part. if you have any other suggestion how to achieve the result i want please say it #LIBRARIES import cv2 import numpy as np import matplotlib as mpl from matplotlib import pyplot as plt #read and display the image img = cv2.imread("road.jpg") #original picture show cv2.imshow("Window Name",img) # edging the image edges = cv2.Canny(img,255,255) #show the canny picture cv2.imshow("Window Name",edges) #save the canny picture First argument is the file name, second argument is the image you want to save. cv2.imwrite('canny.png',edges) #making the image an array from PIL import Image #read the pciture img = Image.open('road.jpg').convert('LA') #save it img.save('greyscale.png') #open the edited im=Image.open("greyscale.png") #make it an array pix_val = list(im.getdata()) pix_val_flat = [x for sets in pix_val for x in sets] # pix_val_flat has the pixels for out first image without edging #print the array #print (pix_val_flat[125]); #get the lenght of the array lenght=len(pix_val_flat) #print the array #print(lenght); #take the canny picture and make it grayscale edge = Image.open('canny.png').convert('LA') #make it array pix_val1 = list(edge.getdata()) pix_val_flat1 = [x for sets in pix_val for x in sets] #get the lenght of the array #lenght1=len(pix_val_flat1) #prnt the array #print(lenght); #print the array #print (pix_val_flat1[125]); print(lenght) …
type: UnansweredQuestion
tagged with: python
has title: TypeError: too many data entries
type: Question
has answer: http://stackoverflow.com/a/56402155
has comment: http://stackoverflow.com/comment/84719102
tagged with: image
tagged with: recreate
score: 0

http://stackoverflow.com/comment/84879171
type: QuestionComment
has text: hope train_iter is a iterable and not None. Try checking train_iter data and its type.
score: 1
comment on: http://stackoverflow.com/q/48935907
type: Comment

http://stackoverflow.com/comment/84701348
comment on: http://stackoverflow.com/q/48848815
type: Comment
type: QuestionComment
has text: This smells like homework...
score: 5

http://stackoverflow.com/comment/84856106
has text: mabye because of the typo? `find_module('openpyx')`
score: 0
comment on: http://stackoverflow.com/q/48924490
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84857741
has text: I need the mean for a specific day of the first 5 years . e.g. the mean of day 53 for the years 2012-2017
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48924775
type: Comment

http://stackoverflow.com/comment/84644604
comment on: http://stackoverflow.com/q/48820494
has text: In the base case, `return` means `return None`, and this returned value is propagated to the original caller.
type: QuestionComment
type: Comment
score: 2

http://stackoverflow.com/comment/84852481
type: QuestionComment
has text: @JasonYe-MSFT with the command: [az vm create......--attach-os-disk], a NEW VM is created. How to resolve the issue of username and password if azure does not support adding username and password.
comment on: http://stackoverflow.com/q/48911885
score: 0
type: Comment

http://stackoverflow.com/q/48823289
has body: sample data X_test.head() Alarm_First_Notify_Delay Duration_Difference Customer_Same Site_Same SameDevice 100746 701 631 1 0 0 87012 0 35 1 1 1 167585 0 0 1 1 1 178924 0 35 1 1 1 76793 0 0 1 1 1 column features for DNNCLassifier feature_spec2 = { 'Alarm_First_Notify_Delay': tf.FixedLenFeature([X_test.Alarm_First_Notify_Delay.count()],tf.float32), 'Customer_Same':tf.FixedLenFeature([X_test.Customer_Same.count()],tf.float32), 'Duration_Difference':tf.FixedLenFeature([X_test.Duration_Difference.count()],tf.float32), 'SameDevice':tf.FixedLenFeature([X_test.SameDevice.count()],tf.float32), 'Site_Same':tf.FixedLenFeature([X_test.Site_Same.count()],tf.float32) } value of feature_spec2 is as follows :- {'Alarm_First_Notify_Delay': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None), 'Customer_Same': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None), 'Duration_Difference': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None), 'SameDevice': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None), 'Site_Same': FixedLenFeature(shape=[66849], dtype=tf.float32, default_value=None)} Restore the DNNCLASSIFIER Model saved using the .export_savedmodel() import tensorflow as tf exported_path = 'D:\\dnnclassifier\\1518769534' res_pred =[] import time from datetime import datetime start = time.time() start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(start)) print('start time : ',start_time) with tf.Session() as sess: #load the saved model tf.saved_model.loader.load(sess, [tf.saved_model.tag_constants.SERVING], exported_path) #Prepare model input, the model expects a float array to be passed to x # check line 28 serving_input_receiver_fn model_input= tf.train.Example(features= feature_spec2) #get the predictor , refer tf.contrib.predicdtor predictor= tf.contrib.predictor.from_saved_model(exported_path) #get the input_tensor tensor from the model graph # name is input_tensor defined in input_receiver function re…
favorite count: 0
type: UnansweredQuestion
tagged with: machine-learning
tagged with: tensorflow
upvote count: 0
has answer: http://stackoverflow.com/a/48837635
score: -1
has title: Error encountered while trying to get predictions from a .export_savedmmodel()
type: Question
answer count: 1
downvote count: 1
tagged with: python

http://stackoverflow.com/a/48994566
has body: Or oneShot = [x[::-1] for x in myList][::-1]
answers question: http://stackoverflow.com/q/48952467
score: 0
type: Answer

http://stackoverflow.com/comment/84625922
type: QuestionComment
has text: That depends a lot on the encoding
score: 1
comment on: http://stackoverflow.com/q/48811203
type: Comment

http://stackoverflow.com/comment/84708401
has text: Can you sum up your _Manual Steps_ which you are trying to _Automate_?
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48846700
type: QuestionComment

http://stackoverflow.com/q/48905470
tagged with: apache-spark-sql
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84842566
favorite count: 0
linked to: http://stackoverflow.com/q/48870399
has comment: http://stackoverflow.com/comment/84986232
tagged with: python
has comment: http://stackoverflow.com/comment/84832375
has title: Convert Group By to Reduce by Key
upvote count: 3
type: UnansweredQuestion
score: 3
tagged with: group-by
tagged with: pyspark
has answer: http://stackoverflow.com/a/48909759
has body: I have a massive pyspark dataframe. I have to perform a group by however I am getting serious performance issues. I need to optimise the code so I have been reading that a Reduce by Key is much more efficient. This an example of the data frame. a = [('Bob', 562,"Food", "12 May 2018"), ('Bob',880,"Food","01 June 2018"), ('Bob',380,'Household'," 16 June 2018"), ('Sue',85,'Household'," 16 July 2018"), ('Sue',963,'Household'," 16 Sept 2018")] df = spark.createDataFrame(a, ["Person", "Amount","Budget", "Date"]) Output: +------+------+---------+-------------+ |Person|Amount| Budget| Date| +------+------+---------+-------------+ | Bob| 562| Food| 12 May 2018| | Bob| 880| Food| 01 June 2018| | Bob| 380|Household| 16 June 2018| | Sue| 85|Household| 16 July 2018| | Sue| 963|Household| 16 Sept 2018| +------+------+---------+-------------+ I have implemented the following code, however as mentioned before, the actual data frame is massive. df_grouped = df.groupby('person').agg(F.collect_list(F.struct("Amount", "Budget", "Date")).alias("data")) Ouput: +------+--------------------------------------------------------------------------------+ |person|data | +------+--------------------------------------------------------------------------------+ |Sue |[[85,Household, 16 July 2018], [963,Household, 16 Sept 2018]] | |Bob |[[562,Food,12 May 2018], [880,Food,01 June 2018], [380,Household, 16 June 2018]]| +------+--------------------------------------------------------------------------------+ With the schema being: root |-- person: string (nullable = true) |-- data: array (nullable = true) | |-- element: struct (containsNull = true) | | |-- Amount: long (nullable = true) | | |-- Budget: string (nullable = true) | | |-- Date: string (nullable = true) I need to convert the group by into a reduce by key such that I can create the same schema as above.
type: Question

http://stackoverflow.com/comment/84908976
comment on: http://stackoverflow.com/q/48937722
has text: not sure... should it has any effect? Initialy I only had one module, so both, name and pymodule were called as foo, but now I must add two new modules (foo1 and foo2) trying not to modify foo because it is already being used as a package installed via pip, so I should not modify it
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/comment/84956565
comment on: http://stackoverflow.com/q/48912485
type: Comment
type: QuestionComment
score: 0
has text: Yes I think that would be the best approach since the existing compression data is lost.

http://stackoverflow.com/a/48807555
answers question: http://stackoverflow.com/q/48807504
downvote count: 0
has comment: http://stackoverflow.com/comment/84618201
score: 4
upvote count: 4
has body: What you're looking for is called the "symmetric difference". set(new_Items) ^ set(old_Items) Or, set(new_Items).symmetric_difference(old_Items) This gives you items that belong to either set, but not both. You are currently computing only those items that belong to new_Items, but not the other way round, hence the discrepancy. Refer to the set.symmetric_difference docs.
has comment: http://stackoverflow.com/comment/84618402
type: Answer

http://stackoverflow.com/comment/84879927
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48911016
type: Comment
has text: It is impossible to get other values than the ones listed there, I'll never get "dummie" for example

http://stackoverflow.com/comment/84684728
score: 0
type: Comment
type: QuestionComment
has text: Python is very picky about indentation. Please indent your code correctly.
comment on: http://stackoverflow.com/q/48840102

http://stackoverflow.com/a/48853873
score: 0
has body: I think I found the issue: I saved the customNMF trained from the python notebook. I had to slightly modify the classes in the dask version not not call some unnecessary packages (cross validation and metrics from sklearn) for the website version. I assume those minor modifications are the source of the problem. Now the CustomNMF is trained and pickled for later usage by the website server. Not sure it's the best approach, but it's working! If anyone as good lecture about packages structure and how to articulate them (simplified version ;-) just for me), I would really appreciate. Thanks
answers question: http://stackoverflow.com/q/48849281
type: Answer

http://stackoverflow.com/a/49083796
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48852607
type: Answer
has comment: http://stackoverflow.com/comment/85174738
accepted answer of: http://stackoverflow.com/q/48852607
score: 3
has comment: http://stackoverflow.com/comment/85175020
upvote count: 3
has body: I don't see how pivoting helps here, since at the end you need to divide your data twice, once for the days of the week, which shall be put into several subplots, and again for the cities, which shall have their own colored line. At this point we're at the limit of what pandas can do with its plotting wrapper. Matplotlib Using matplotlib one can loop through the two categories, days and cities and just plot the data. import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates df = pd.DataFrame({ 'CITY' : np.random.choice(['PHOENIX','ATLANTA','CHICAGO', 'MIAMI', 'DENVER'], 10000), 'DAY': np.random.choice(['Monday','Tuesday','Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], 10000), 'TIME_BIN': np.random.randint(1, 86400, size=10000), 'COUNT': np.random.randint(1, 700, size=10000)}) df['TIME_BIN'] = pd.to_datetime(df['TIME_BIN'], unit='s').dt.round('10min') days = ['Monday','Tuesday','Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] cities = np.unique(df["CITY"]) fig, axes = plt.subplots(nrows=len(days), figsize=(13,8), sharex=True) # loop over days (one could use groupby here, but that would lead to days unsorted) for i, day in enumerate(days): ddf = df[df["DAY"] == day].sort_values("TIME_BIN") # loop over cities for city in cities: dddf = ddf[ddf["CITY"] == city] axes[i].plot(dddf["TIME_BIN"], dddf["COUNT"], label=city) axes[i].margins(x=0) axes[i].set_title(day) fmt = matplotlib.dates.DateFormatter("%H:%M") axes[-1].xaxis.set_major_formatter(fmt) axes[0].legend(bbox_to_anchor=(1.02,1)) fig.subplots_adjust(left=0.05,bottom=0.05, top=0.95,right=0.85, hspace=0.8) plt.show() Seaborn Roughly the same can be achived with a seaborn FacetGrid. import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates import seaborn as sns df = pd.DataFrame({ 'CITY' : np.random.choice(['PHOENIX','ATLANTA','CHICAGO', 'MIAMI', 'DENVER'], 10000), 'DAY': np.random.choice(['Monday','Tuesday','Wednesday', 'Thurs…
has comment: http://stackoverflow.com/comment/85174866
has comment: http://stackoverflow.com/comment/85174955

http://stackoverflow.com/comment/84751276
type: AnswerComment
comment on: http://stackoverflow.com/a/48873681
type: Comment
score: 0
has text: How would I develop the print statement

http://stackoverflow.com/comment/84645788
score: 0
has text: replace has a occurance parameter with that you can control how many times it will replace. If you google it you will find it
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48821140

http://stackoverflow.com/comment/84682721
has text: Output is following: (venv) $ pip freeze certifi==2017.7.27.1 chardet==3.0.4 decorator==4.1.2 idna==2.5 . . . requests==2.18.3 tqdm==4.15.0 urllib3==1.22 visdom==0.1.5 wcwidth==0.1.7 (venv) $ pip -V pip 9.0.1 from /home/balloch/software/synth-seg/venv/lib/python3.6/site-packages (python 3.6) (venv) $ python -V Python 3.6.3 :: Anaconda custom (64-bit) (venv) $ which python python: aliased to /home/balloch/anaconda3/bin/python3.6 (venv) $ which pip /home/balloch/software/synth-seg/venv/bin/pip This was revealing. didn't realize anaconda was aliased. thoughts?
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48839069
score: 0

http://stackoverflow.com/a/48938156
downvote count: 0
has body: I suspect this is because the setting should be a tuple, which requires a comma. BAKERY_VIEWS = ( 'polls.views.HomePageView', )
upvote count: 2
type: Answer
score: 2
accepted answer of: http://stackoverflow.com/q/48935673
answers question: http://stackoverflow.com/q/48935673
type: AcceptedAnswer

http://stackoverflow.com/comment/84781325
score: 1
has text: @SvenMarnach I was thinking that too, but continue observing similar performance differences after increasing second and third dimensions of arr's shape to 5K and 10K instead of 1K and 1K. Wouldn't that cause the ''smaller'' chunks in method2 to also no longer fit in cache?
comment on: http://stackoverflow.com/q/48887461
type: Comment
type: QuestionComment

http-status-code-302
tags question: http://stackoverflow.com/q/48885836
type: Tag
tag name: http-status-code-302

http://stackoverflow.com/q/48876238
score: 0
tagged with: pandas
has body: I'm using Pandas and Sklearn for a Kaggle competition. I'm using TfidfVectorizer to get a feature for the top 100 most important features from each of the Title and FullDescription columns. I'm prepending "TITLE_" before words that occur in the Title and "DESC_" before words that occur in the FullDescription. Unfortunately, one of my rows (the 10,000th one) is valid before I modify anything in my DataFrame: df.iloc[9999] Gives me: Id 66190737 Title Experienced RHAD Job Lincoln FullDescription We provide a community hearing service to thos... LocationRaw Lincoln, Lincolnshire LocationNormalized Lincoln ContractType full_time ContractTime NaN Company NaN Category Healthcare &amp; Nursing Jobs SalaryRaw 18,000 to 40,000 per year SalaryNormalized 29000 SourceName careworx.co.uk Name: 9999, dtype: object Once I use TfidfVectorizer, all of the features in the 10,000th row from Title or FullDescription (the ones prepended with "TITLE_" or "DESC_") are NaN. Here's what I'm doing: STEMMER = nltk.stem.porter.PorterStemmer() tokenizer = RegexpTokenizer(r'\w+') def stem_tokens(tokens, stemmer=STEMMER): return [stemmer.stem(item) for item in tokens] def tokenize(text, tokenizer=tokenizer): tokens = tokenizer.tokenize(text) return stem_tokens(tokens) def get_tfidf_df(df, col, max_features, prefix, tokenize): vec = TfidfVectorizer(tokenizer=tokenize, stop_words="english", max_features=max_features) tfidf = vec.fit_transform(df[col]) tfidf_array = tfidf.toarray() tfidf_df = pd.DataFrame(tfidf_array, columns=vec.get_feature_names()) tfidf_df.columns = [prefix + "_" + str(col) for col in tfidf_df.columns] return tfidf_df def group_rare_entries(df, col, threshold): mask = df[col].groupby(df[col]).transform("count").lt(threshold) df[col][mask] = "RARE" def address_rare_entries(df, cols, threshold): for col in cols: group_rare_entries(df, col, threshold) def get_processed_df(df, rare_cols, threshold=10): address_rare_entries(df, rare_cols, threshold) df = df[pd.notnull(df["FullDescripti…
has comment: http://stackoverflow.com/comment/84882945
answer count: 0
type: UnansweredQuestion
tagged with: python
type: Question
has comment: http://stackoverflow.com/comment/84761416
has comment: http://stackoverflow.com/comment/84882958
tagged with: scikit-learn
has title: Sklearn: Surprising Behavior with TfidfVectorizer

sphinx-apidoc
tag name: sphinx-apidoc
tags question: http://stackoverflow.com/q/48864826
type: Tag

http://stackoverflow.com/q/48929526
downvote count: 0
answer count: 1
favorite count: 0
upvote count: 2
tagged with: django
tagged with: python
tagged with: pdf-generation
type: AnsweredQuestion
has title: Position absolute for when using xhtml2pdf (Django)?
has answer: http://stackoverflow.com/a/48961006
type: Question
tagged with: xhtml2pdf
has body: Can I generate PDF with CSS position: absolute; for &lt;img src="..."/&gt; html tag? I need to place handwritten signature and company stamp (PNG files) to bottom of order voucher at non standard place, that they run a little on the goods table. Position absolute will save my time for that, but it's don't working. EDIT: I have an answer from xhtml2pdf GitHub repo: Well absolute position is not supported right now, but if you are looking for how to set images in specific part of page in all pages, see frames. So, my question is still actual. Real usage example with xhtml2pdf frames for images will be great.
accepted answer: http://stackoverflow.com/a/48961006
score: 2
tagged with: http://stackoverflow.com/tag/pdf

http://stackoverflow.com/comment/84858239
score: 1
has text: I had a solution but couldn't find it. Yours looks way more xomplicated. But if it works why not!
comment on: http://stackoverflow.com/a/48923439
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48919034
has answer: http://stackoverflow.com/a/48919756
type: Question
answer count: 1
has title: How to generate a list of lists with random numbers of the same length
score: 0
tagged with: random
has body: How do you generate a random list of lists? I can generate a random list using the following [random.sample(range(80), 20)]. You can use the * function to make it list of lists but the numbers aren't random for each list. I can find answers relating to the creation of random list of lists that produce variable lengths but I can't find anything that will produce random numbers with the same length.
favorite count: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48919756
type: AnsweredQuestion
tagged with: list
upvote count: 3
has comment: http://stackoverflow.com/comment/84844434
downvote count: 3

http://stackoverflow.com/comment/84618292
has text: yeah I know But doing by the way in your code will add only one element. You have to also change that `while` to `if` with the above change. with that when i tried its working. But I don't understand what you mean by *"find top N contestants"*
comment on: http://stackoverflow.com/q/48806910
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48995544
answers question: http://stackoverflow.com/q/48812379
type: Answer
upvote count: 0
has body: You can use count(). Here is a working code: import peewee from peewee import * db = SqliteDatabase('/tmp/a.db') class Products(Model): sku = CharField() class Meta: database = db db.connect() db.drop_tables(models=[Products], safe=True) db.create_tables([Products]) count = Products.select().count() print(count) #=&gt; 0 if not count: Products.create(sku="abc") print(Products.select().count()) #=&gt; 1 print(peewee.__version__) #=&gt; 3.0.18
has comment: http://stackoverflow.com/comment/85035059
has comment: http://stackoverflow.com/comment/85070869
score: -1
has comment: http://stackoverflow.com/comment/85045125
downvote count: 1

http://stackoverflow.com/comment/84802222
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48898368
has text: d[key.strip()]= value is that right?
score: 0

http://stackoverflow.com/comment/84715742
score: 0
type: QuestionComment
type: Comment
has text: @DeliriousLettuce sorry, I have changed it. The above code gives the right result, just my writing was wrong. Just edited.
comment on: http://stackoverflow.com/q/48855492

http://stackoverflow.com/q/48929153
has answer: http://stackoverflow.com/a/48929505
has comment: http://stackoverflow.com/comment/84864976
has comment: http://stackoverflow.com/comment/84865035
type: Question
upvote count: 0
score: -3
favorite count: 0
has answer: http://stackoverflow.com/a/48929988
has comment: http://stackoverflow.com/comment/84865182
answer count: 3
has comment: http://stackoverflow.com/comment/84864898
has body: I want to start a new django project. This will just be a relatively simple website to test django itself. So the way all tutorials structure their project is this: mysite mysite some_app ... For me it's not very clear what does what. I don't really need any app right now. Could I implement my website without using any app? Should I use an app? What would it be called for a simple website?
has title: Django single website structure
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84866489
tagged with: django
tagged with: python
tagged with: structure
has answer: http://stackoverflow.com/a/48929248
downvote count: 3

http://stackoverflow.com/a/48940730
has comment: http://stackoverflow.com/comment/84888497
downvote count: 0
has body: The code does take the absolute value: if isinstance(step, complex): size.append(int(abs(step))) but this is not a documented guarantee. The docs only guarantee behavior for imaginary numbers, not arbitrary complex numbers: if step is an imaginary number (i.e. 100j) then its integer portion is interpreted as a number-of-points desired and the start and stop are inclusive You should not rely on the behavior for not-purely-imaginary complex inputs, as it is not a documented guarantee. That said, it is possible that it was intended to be a guarantee. The furthest back I've been able to trace numpy.r_'s code is this commit. (That's not where it originated - I can find references to scipy.r_ dating back even further - but despite finding references to scipy.r_, I have not been able to locate the code for scipy.r_, and I suspect neither the SciPy nor NumPy GitHub repositories contain the original code. It seems like this would be the right commit, except that GitHub seems to only have a fragment of the original non-Git commit.) r_ was not documented in the earliest commit I can trace it to, but mgrid was also present in that commit, and mgrid's similar behavior for complex numbers was documented in that commit as However, if the step length is a COMPLEX NUMBER (e.g. 5j), then the integer part of it's magnitude is interpreted as specifying the number of points to create between the start and stop values, where the stop value IS INCLUSIVE. The furthest I've been able to trace numpy.r_'s documentation is this commit 7 years later, labelled "Merge from doc wiki". I believe the doc wiki is now gone, and I have been unable to determine who originally contributed those docs, but it seems likely that those docs were not based on the original intent of numpy.r_'s author.
has comment: http://stackoverflow.com/comment/84888632
type: AcceptedAnswer
score: 4
has comment: http://stackoverflow.com/comment/84888657
accepted answer of: http://stackoverflow.com/q/48940544
type: Answer
upvote count: 4
answers question: http://stackoverflow.com/q/48940544

http://stackoverflow.com/q/48855492
type: Question
has title: Compare each pair of list in multiple lists to create an order list
answer count: 2
score: -2
has answer: http://stackoverflow.com/a/48855548
has comment: http://stackoverflow.com/comment/84714635
has comment: http://stackoverflow.com/comment/84715742
upvote count: 1
has comment: http://stackoverflow.com/comment/84714474
tagged with: compare
has comment: http://stackoverflow.com/comment/84714504
favorite count: 0
has comment: http://stackoverflow.com/comment/84714705
has comment: http://stackoverflow.com/comment/84714530
tagged with: python
possible better answer: http://stackoverflow.com/a/48855548
has comment: http://stackoverflow.com/comment/84714465
has comment: http://stackoverflow.com/comment/84714543
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84714758
has body: a_list = [[70,62],[31,62],[62,71],[70,31],[70,71],[31,71]] I have a list above. Each list above has two elements, the first element is always less than the second element(e.x: 30 &lt; 62 for first list) - I don't compare the numbers themselves (of course 30 &lt;62 but if the list is (62,30) so it should be 62 &lt;30). So based on the list I have, how can I make a whole list of order in efficient way? I try to write manually but my code runs so wrongly with many if statements The result should be: [70,31,62,71] after comparing each pair of each list. I tried with 3 pairs of list as belows: sort = [] list = [[48, 33], [56, 33], [56, 48]] for i in list[:-1]: for j in list[1:]: if i[0] == j[1]: sort.extend([i[0],i[1],j[0]]) break print(sort) The result is [56,48,33] But for larger numbers, I am still checking.
downvote count: 3
has answer: http://stackoverflow.com/a/48856010
accepted answer: http://stackoverflow.com/a/48856010
has comment: http://stackoverflow.com/comment/84715690

http://stackoverflow.com/a/48907717
has comment: http://stackoverflow.com/comment/84857758
has comment: http://stackoverflow.com/comment/84821486
has comment: http://stackoverflow.com/comment/84821253
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: I'm not sure that you can due this using only numpy. I would use the method cdist from the scipy library, something like this: import numpy as np from scipy.spatial.distance import cdist B=5 X=np.random.rand(B*B).reshape((B,B)) dist = cdist(X, X, metric='euclidean') K = np.exp(dist) dist array([[ 0. , 1.2659804 , 0.98231231, 0.80089176, 1.19326493], [ 1.2659804 , 0. , 0.72658078, 0.80618767, 0.3776364 ], [ 0.98231231, 0.72658078, 0. , 0.70205336, 0.81352455], [ 0.80089176, 0.80618767, 0.70205336, 0. , 0.60025858], [ 1.19326493, 0.3776364 , 0.81352455, 0.60025858, 0. ]]) K array([[ 1. , 3.5465681 , 2.67062441, 2.22752646, 3.29783084], [ 3.5465681 , 1. , 2.06799756, 2.23935453, 1.45883242], [ 2.67062441, 2.06799756, 1. , 2.01789192, 2.25584482], [ 2.22752646, 2.23935453, 2.01789192, 1. , 1.82259002], [ 3.29783084, 1.45883242, 2.25584482, 1.82259002, 1. ]]) Hoping this can help you. Good work EDIT You can also use only numpy array, for a theano implementaion: dist = (X ** 2).sum(1).reshape((X.shape[0], 1)) + (X ** 2).sum(1).reshape((1, X.shape[0])) - 2 * X.dot(X.T) It should be work!
accepted answer of: http://stackoverflow.com/q/48907216
upvote count: 3
answers question: http://stackoverflow.com/q/48907216
has comment: http://stackoverflow.com/comment/84860813
score: 3

http://stackoverflow.com/comment/84649904
comment on: http://stackoverflow.com/a/48822773
score: 0
type: Comment
has text: Feel free to extend yours if you're happy to do so and explain it :)
type: AnswerComment

http://stackoverflow.com/a/48959780
has comment: http://stackoverflow.com/comment/84926241
accepted answer of: http://stackoverflow.com/q/48959698
answers question: http://stackoverflow.com/q/48959698
has comment: http://stackoverflow.com/comment/84926489
has comment: http://stackoverflow.com/comment/84926526
type: AcceptedAnswer
downvote count: 0
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/84926390
has body: probs[range(num_examples), y] seems to be a 1D slice, where: range(num_examples) is a vector spanning the length of your samples y is a 1D vector, length N*K
upvote count: 3

http://stackoverflow.com/comment/84729046
score: 0
type: Comment
type: QuestionComment
has text: Are you getting this error on your example? I am not.
comment on: http://stackoverflow.com/q/48856584

http://stackoverflow.com/comment/84628422
score: 0
type: QuestionComment
type: Comment
has text: I put this query in try: `except peewee.DoesNotExist:`
comment on: http://stackoverflow.com/q/48812379

http://stackoverflow.com/comment/84970455
type: Comment
comment on: http://stackoverflow.com/a/48957532
has text: @gented this is the type of `tfidf` : `<class 'scipy.sparse.csr.csr_matrix'> `
score: 0
type: AnswerComment

http://stackoverflow.com/q/48847491
accepted answer: http://stackoverflow.com/a/48847566
type: Question
has title: Python - Deleting a line from a file (To-Do List program that uses entries, different from other posts)
linked to: http://stackoverflow.com/q/1637807
downvote count: 0
answer count: 1
favorite count: 0
tagged with: python-2.7
linked to: http://stackoverflow.com/q/23103100
has answer: http://stackoverflow.com/a/48847566
tagged with: tkinter-entry
tagged with: python-3.x
tagged with: tkinter
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
has body: I have a problem with my code. I am trying to delete a specific line from a file. I am making a To-Do List program in Tkinter, and I am using a Label as the to-do list. I have two buttons, 'Add Item' and 'Delete Item'. I also have an entry box, and the buttons take the string from the entry using the .get() method. The delete button is not working because I cannot find a way to delete a line from a file that the program is using to store the list. I have looked over many other posts about the same problem, but mine is different. Whenever I run the program, and I click delete item after I fill out the text box, it deletes ALL items from the file, but I only want it to delete one item. The problem is NOT the one that @JetMashKangaroo had in this post: How to delete a line from a file in Python. Here is the snippet of code: def dele(): global ItemName global Display global List ToDoDel = ItemName.get() new_f = List.readlines() List.seek(0) for line in new_f: if ToDoDel not in line: List.write(line) List.truncate() Display['text'] = List.readlines() ItemName is the entry box. Display is the label that displays the To-Do list. List is the variable below: List = open('***/***/To-Do_List.txt','r+') The program works perfectly, but I cannot add this delete function because it deletes all the text from the file. the function dele is called when the button 'Delete Item' is pressed. Help would be greatly appreciated.

http://stackoverflow.com/a/48933230
answers question: http://stackoverflow.com/q/48932611
type: Answer
has body: Create a zero initialized array and assign your items according their indices: In [24]: nonzero_ind = np.nonzero(seam) In [25]: x, y = input.shape In [26]: arr = np.zeros((x, y+1)) In [27]: arr[nonzero_ind] = seam[nonzero_ind] In [28]: arr[np.where(arr==0)] = input.ravel() In [29]: arr Out[29]: array([[ 1., 2., 1., 1., 1.], [ 1., 1., 3., 1., 1.], [ 1., 1., 1., 4., 1.]])
score: 2
downvote count: 0
upvote count: 2

http://stackoverflow.com/q/48881901
has answer: http://stackoverflow.com/a/48882514
answer count: 1
has title: Dataframe to Time Series when minutes are repeated
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84768451
has body: I'm working with clinical data and want to make predictions of patients' waiting time at every minute, and the data (simplified) looks something like this: Time(minutes) PatientSerial RemainingTime(minutes) 420 1 5 420 2 10 420 3 8 421 1 4 421 2 9 421 3 7 Where 420 is the number of minutes since midnight (420 = 7:00am), where my output is RemainingTime (historical data). In general, the machine learning algorithm should generate waiting time of every patient in each minute, given that the input is clinical data that is generated every minute. But I'm confused as to how to convert this dataframe into Time Series when the same minutes are repeated?
has comment: http://stackoverflow.com/comment/84768148
tagged with: machine-learning
type: Question
has comment: http://stackoverflow.com/comment/84768301
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84768521
has comment: http://stackoverflow.com/comment/84769149
score: 0

http://stackoverflow.com/comment/84753437
score: 0
comment on: http://stackoverflow.com/q/48860223
type: QuestionComment
type: Comment
has text: Hi @tash. I have added a full response below. This is quite common in flask and the solution is to move the line importing user into main to the bottom.

http://stackoverflow.com/comment/84621184
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48808904
score: 0
has text: I wrapped it in list() and it works. thank you @Jim Fasarakis Hilliard

http://stackoverflow.com/a/48822657
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48819387
answers question: http://stackoverflow.com/q/48819387
type: Answer
downvote count: 0
score: 1
has body: This doesn't have anything to do with posting data at all. The issue is that your view is an update, which passes the existing instance to the form so that Django knows how to update it. Your test doesn't do that. (Your test isn't really testing your code; you should really be calling the view, either with the request factory or the test client, v and passing your data in there.)
upvote count: 1

http://stackoverflow.com/comment/84796872
score: 0
type: AnswerComment
has text: check the power shell commend. The problem is with your power shell command not with python code. First manually execute the power shell and check whether work or not.
type: Comment
comment on: http://stackoverflow.com/a/48895453

amazon-elastic-beanstalk
tag name: amazon-elastic-beanstalk
type: Tag
tags question: http://stackoverflow.com/q/48905936
tags question: http://stackoverflow.com/q/48862256

http://stackoverflow.com/comment/84639021
type: AnswerComment
score: 0
type: Comment
has text: the problem is that the second eight is being compared to the 8 in 5805
comment on: http://stackoverflow.com/a/48817109

http://stackoverflow.com/comment/84681587
comment on: http://stackoverflow.com/q/48836484
type: QuestionComment
has text: Can you show us a snapshot of what exactly you mean by `prompt alert save js file`?
score: 0
type: Comment

http://stackoverflow.com/a/48838370
answers question: http://stackoverflow.com/q/48838247
score: 4
upvote count: 4
downvote count: 0
type: Answer
has body: You can use nunique pd.Series([1, 2, 3]).nunique()==len(pd.Series([1, 2, 3])) Out[62]: True

nested
tags question: http://stackoverflow.com/q/48941023
tag name: nested
type: Tag
tags question: http://stackoverflow.com/q/48915207
tags question: http://stackoverflow.com/q/48940049
tags question: http://stackoverflow.com/q/48831066
tags question: http://stackoverflow.com/q/48919566
tags question: http://stackoverflow.com/q/48936869
tags question: http://stackoverflow.com/q/48946896
tags question: http://stackoverflow.com/q/48896856
tags question: http://stackoverflow.com/q/48856740
tags question: http://stackoverflow.com/q/48875455

http://stackoverflow.com/a/48916339
has body: Try stack with dropnaparameter set to False: df.set_index('ID').stack(dropna=False) @PaulH is correct in his observations from the comments below. To move that column index to row index converting from a wide dataframe to a long dataframe.
has comment: http://stackoverflow.com/comment/84839940
has comment: http://stackoverflow.com/comment/84839704
answers question: http://stackoverflow.com/q/48916311
has comment: http://stackoverflow.com/comment/84840329
has comment: http://stackoverflow.com/comment/84839885
has comment: http://stackoverflow.com/comment/84840309
upvote count: 1
has comment: http://stackoverflow.com/comment/84839909
has comment: http://stackoverflow.com/comment/84839922
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84839948
type: Answer
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84839899
accepted answer of: http://stackoverflow.com/q/48916311

http://stackoverflow.com/a/48807700
type: Answer
answers question: http://stackoverflow.com/q/48807103
has body: Just want to add that if the file is large (really large) you may read it line by line. Try this code. It treats multiple whitespaces as one while splitting, and allows you to ignore case. from collections import defaultdict import re def read_string_column(csv_file,delimiter=','): """ Read the file line by line """ line = '1' while line: line = csv_file.readline() if len(line.split(delimiter))&lt;2: continue yield line.split(delimiter)[1] def add_word_counts(word_dict,new_words): """ Add word counts to a defaultdict """ for word in new_words: if word: word_dict[word]+=1 def count_words(csv_file,delimiter=',',ignore_case=True): """ Count words. delimiter - csv file delimiter ignore_case - if True, the text will be read in a lower case """ result_dict = defaultdict(int) if ignore_case: for words in read_string_column(csv_file,delimiter): add_word_counts(result_dict,re.split('\s+',words.lower().strip())) else: for words in read_string_column(csv_file,delimiter): add_word_counts(result_dict,re.split('\s+',words.strip())) return result_dict if __name__=='__main__': f = open('1.csv','r') print(count_words(f,ignore_case=True))
score: 0

code-generation
tag name: code-generation
tags question: http://stackoverflow.com/q/48812380
type: Tag

http://stackoverflow.com/q/48824696
type: AnsweredQuestion
score: 1
has answer: http://stackoverflow.com/a/48824765
tagged with: matplotlib
has body: Plotted a graph in Matplotlib ,but as you can see from the below image img the points(ticks) are too close to each other.Is there a way to increase distance between the ticks without affecting anything,I have searched a lot but didn't find anything good ,My code is below: import MySQLdb import sys import matplotlib.pyplot as plt from collections import Counter, OrderedDict # open a database connection connection = MySQLdb.connect() # prepare a cursor object using cursor() method cursor = connection.cursor () # execute the SQL query using execute() method. cursor.execute () #fetch all of the rows from the query data = cursor.fetchall() ddt = sorted(set(data)) #Shows the Count values coll = Counter(data) orddict = OrderedDict(sorted(coll.items()))# Sorts the dates in order y = orddict.values() temp = 0 a= [] i = 1 j = 0 for x in y: temp = temp + x if i % 7 == 0: a.insert(j,temp) temp = 0 j = j + 1 i = i + 1 b = 0 dist = [b] + a x = range(len(y)) plt.plot(dist ,color='green', linewidth = 2,marker='o', markerfacecolor='blue', markersize=8) plt.ylabel('Number of Bookings') plt.xlabel('Date') plt.xticks( x,ddt[::7],fontsize = 5, rotation = 90) plt.show() #close the cursor object cursor.close () #close the connection connection.close () #exit the program sys.exit() Edit 1 :Did as per suggested in the comments ,but now the graph looks like image
type: Question
has title: Matplotib Graph Display Error
accepted answer: http://stackoverflow.com/a/48824765
answer count: 1
downvote count: 0
favorite count: 0
upvote count: 1
tagged with: python

http://stackoverflow.com/a/48925360
has body: I haven't found a better way to construct an iterator over changes in a file. But this is how you would stage an in-memory version of the file: new_version = '........'.encode('utf-8') # Or whatever encoding you use istream = repo.odb.store(gitdb.IStream(git.Blob.type, len(new_version), BytesIO(new_version))) file_mode = ... # eg os.stat(file_path).st_mode entry = git.BaseIndexEntry((file_mode, istream.binsha, 0, file_path)) repo.index.add([entry]) The repo.odb.store call stores the version in the git database, but at this point it's not linked to anything. Creating the BaseIndexEntry object and adding it to the index then links that stored version into the index - the link is by the file path and the binsha hash. It seems that this won't work on bare repositories.
answers question: http://stackoverflow.com/q/48884127
type: Answer
score: 0

http://stackoverflow.com/q/48933932
has body: I have a df where I want to show the number of people randomly added to a sports team a year where the inverse of rank is used as a normalizing weight. The code has 10 individuals to assign to a team each year. I have code for this that works fine. My problem is how can I drop teams and their weights out over time once they hit their max number of team members assigned, without dropping them from the df? I know this would require readjusting the weights and choices each year something dropped out but I'm not sure how to implement that. Edited to add dict df_dict = {'Rank1': {0: 1, 1: 2, 2: 3, 3: 3}, 'Team': {0: 'Foo', 1: 'Bar', 2: 'Baz', 3: 'Cat'}, 'current_num': {0: 6, 1: 5, 2: 9, 3: 10}, 'max_num': {0: 15, 1: 16, 2: 14, 3: 18}} df_input Rank1 Team max_num current_num 1 Foo 15 6 2 Bar 16 5 3 Baz 14 9 3 Cat 18 10 df_output Rank1 Rank2 Team max_num current_num Y1 Y2 Y3 Final_total 1 3 Foo 15 6 4 5 4 19 2 2 Bar 16 5 4 3 2 14 3 1 Baz 14 9 1 2 2 14 3 1 Cat 18 10 1 0 2 13 Current code : def Team_picker(df): new_weight = {1:3,3:1} df['Rank2'] = df.Rank1.map(new_weight) All_Teams = df['Team'].tolist() weights = df['Rank2'].tolist() norm = [float(i)/sum(weights) for i in weights] for x in range(1,4): year = 'Y %d'% x T = [choice(All_Teams, p=norm) for _ in range(10)] Player_counts = Counter(T) df[year] = df['Team'].map(Player_counts) T_Years = [col for col in df.columns if col.startswith('Y')] df['Final_Total']= df['current_num'] + (df[T_Years].sum(axis=1)) return df However, the df I'm aiming for would look more like this: df_output2 Rank1 Rank2 Team max_num current_num Y1 Y2 Y3 Final_total 1 3 Foo 15 6 4 5 0 15 2 2 Bar 16 5 4 3 4 16 3 1 Baz 14 9 1 2 2 14 3 1 Cat 18 10 1 0 4 15 Basically I am trying to accomplish two things 1.)stop a team from being selected or allocated a person during the draw year if they hit the ‘max_num’ so in the example Team Foo hits the max during year 2 so in year 3 they would be left out of the draw and everything would be re-weighted to accommod…
has comment: http://stackoverflow.com/comment/84874804
score: 0
tagged with: random
tagged with: pandas
has title: np.random choice weighted dropout over time?
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84875095
tagged with: python
answer count: 0
type: Question
tagged with: numpy

http://stackoverflow.com/comment/84806162
type: QuestionComment
has text: The brackets here are mismatched so this code won't run at all (I simply removed the `,...`. But I got it to successfully add `[['629', '245', '8'], ['245', '245', '8']]`.
score: 0
comment on: http://stackoverflow.com/q/48899123
type: Comment

http://stackoverflow.com/q/48854439
upvote count: 2
type: UnansweredQuestion
tagged with: python
score: 2
tagged with: anaconda
type: Question
downvote count: 0
answer count: 1
favorite count: 0
has title: Error while importing localization
has answer: http://stackoverflow.com/a/48854928
has body: I downloaded the localization package in Anaconda. But when I try to import it I get the following error: Traceback (most recent call last): File "&lt;pyshell#0&gt;", line 1, in &lt;module&gt; import localization File "~\Python\Python36-32\lib\site-packages\localization\__init__.py", line 1, in &lt;module&gt; from geoProject import * ModuleNotFoundError: No module named 'geoProject' I do not know what to do, can someone please help me out?
tagged with: python-3.x

http://stackoverflow.com/comment/84746492
has text: As a general rule of thumb you should: **1.** post all relevant data to reproduce your problem and **2** show the code you tried and lastly **3** expected output. We're lacking input from 1 and 3.
comment on: http://stackoverflow.com/q/48871043
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84681561
comment on: http://stackoverflow.com/a/48838373
has text: the code is exactly this: try: start = 20184001100076 end = 201840017800000 step = 10 for i in range(start, end,step): url = 'https://teste.com/Fatura/Pdf?nrFatura='+str(i).zfill(len(str(end))) print(url) q.put(url) q.join() , but I keep getting the zero in the begin of the number..
type: AnswerComment
score: 0
type: Comment

lemmatization
type: Tag
tag name: lemmatization
tags question: http://stackoverflow.com/q/48875501

http://stackoverflow.com/q/48845663
has comment: http://stackoverflow.com/comment/84695557
tagged with: optimization
score: 0
has comment: http://stackoverflow.com/comment/84695846
answer count: 1
has answer: http://stackoverflow.com/a/48845868
accepted answer: http://stackoverflow.com/a/48845868
tagged with: python
has body: What declarations should I be incorporating with a logic function / index operation so that Cython does the heavy lifting? I have two large rasters in the form of numpy arrays of equal size. The first array contains vegetation index values and the second array contains field IDs. The goal is to average vegetation index values by field. Both arrays have pesky nodata values (-9999) that I would like to ignore. Currently the function takes over 60 seconds to execute, which normally I wouldn’t mind so much but I'll be processing potentially hundreds of images. Even a 30 second improvement would be significant. So I’ve been exploring Cython as a way to help speed things up. I’ve been using the Cython numpy tutorial as a guide. Example data test_cy.pyx code: import numpy as np cimport numpy as np cimport cython @cython.boundscheck(False) # turn off bounds-checking for entire function @cython.wraparound(False) # turn off negative index wrapping for entire function cpdef test(): cdef np.ndarray[np.int16_t, ndim=2] ndvi_array = np.load("Z:cython_test/data/ndvi.npy") cdef np.ndarray[np.int16_t, ndim=2] field_array = np.load("Z:cython_test/data/field_array.npy") cdef np.ndarray[np.int16_t, ndim=1] unique_field = np.unique(field_array) unique_field = unique_field[unique_field != -9999] cdef int field_id cdef np.ndarray[np.int16_t, ndim=1] f_ndvi_values cdef double f_avg for field_id in unique_field : f_ndvi_values = ndvi_array[np.logical_and(field_array == field_id, ndvi_array != -9999)] f_avg = np.mean(f_ndvi_values) Setup.py code: try: from setuptools import setup from setuptools import Extension except ImportError: from distutils.core import setup from distutils.extension import Extension from Cython.Build import cythonize import numpy setup(ext_modules = cythonize('test_cy.pyx'), include_dirs=[numpy.get_include()]) After some researching and running: cython -a test_cy.pyx It seems the index operation ndvi_array[np.logical_and(field_array == field_id, ndvi_array != -9999)] i…
has title: How to pass numpy logic functions to Cython correctly?
has comment: http://stackoverflow.com/comment/84725503
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84715324
tagged with: cython
type: Question
tagged with: numpy

http://stackoverflow.com/comment/84784209
comment on: http://stackoverflow.com/a/48888579
type: AnswerComment
score: 0
type: Comment
has text: @karan Then `[sum(ord(ch)-96 for ch in s) for s in strList]` should do it. But be aware it's a one-way conversion: information is lost. If `strList` is `['abc', 'cba', 'acb``']` the result will be `[6, 6, 6]`.

http://stackoverflow.com/q/48952220
has comment: http://stackoverflow.com/comment/84911307
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I have this code to open an Inventor File Dialog. It was working a OK yesterday and does not work today. import win32com.client def TestFileDialog(): ThisApp = win32com.client.Dispatch("Inventor.Application") oFileDlg = ThisApp.CreateFileDialog() oFileDlg.Filter = "Inventor Files (*.iam;*.ipt) #|*.iam;*.ipt|All Files (*.*)|*.*" oFileDlg.FilterIndex = 1 oFileDlg.DialogTitle = "Open File Test" oFileDlg.InitialDirectory = "C:\\Users\\logig\\MoldTools" oFileDlg.ShowOpen() TestFileDialog() Running the code on the interactive window of VS 2017 I get the following exception: --------------------------------------------------------------------------- com_error Traceback (most recent call last) &lt;ipython-input-1-b46d3a85376d&gt; in &lt;module&gt;() 11 oFileDlg.ShowOpen() 12 ---&gt; 13 TestFileDialog() 14 &lt;ipython-input-1-b46d3a85376d&gt; in TestFileDialog() 9 oFileDlg.DialogTitle = "Open File Test" 10 oFileDlg.InitialDirectory = "C:\\Users\\logig\\MoldTools" ---&gt; 11 oFileDlg.ShowOpen() 12 13 TestFileDialog() C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python36_64\lib\site-packages\win32com\client\dynamic.py in ShowOpen(self) com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None) Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 6.2.1 -- An enhanced Interactive Python. Type '?' for help. The same code was running no problem yesterday. The directory exists, there are files with those extensions... I am totally lost about what could have changed. Will appreciate your help.
answer count: 0
has comment: http://stackoverflow.com/comment/84911246
upvote count: 3
has comment: http://stackoverflow.com/comment/84920910
type: Question
has title: python win32 com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147467259), None)
tagged with: autodesk-inventor
score: 3
tagged with: pywin32
downvote count: 0
has comment: http://stackoverflow.com/comment/84920033

http://stackoverflow.com/comment/84787459
score: 0
type: Comment
type: QuestionComment
has text: `F` is, according to the error message, an empty string. So, there is nothing left once you have removed the special characters.
comment on: http://stackoverflow.com/q/48890152

http://stackoverflow.com/comment/84764925
has text: `MethodSchema` doesn't exist until you've finished defining it, but the inner `MethodParamsSchema` is already complete; did using `fields.Nested(MethodParamsSchema)` in your second stricture not work?
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48880342
score: 0

http://stackoverflow.com/a/48891942
type: Answer
has body: Hope this solves your problem. PS-without numpy as you asked. import re from functools import reduce def median(lst): n = len(lst) if n &lt; 1: return None if n % 2 == 1: return sorted(lst)[n//2] else: return sum(sorted(lst)[n//2-1:n//2+1])/2.0 def main(): file = open("grades.txt","r") i = file.readlines() num=[] for element in i: num.extend((re.findall('\d+',element))) results = list(map(int, num)) print(results) print (reduce(lambda x, y: x + y, results) / len(results)) print(median(results)) main()
has comment: http://stackoverflow.com/comment/84789854
has comment: http://stackoverflow.com/comment/84790193
has comment: http://stackoverflow.com/comment/84789295
has comment: http://stackoverflow.com/comment/84789793
has comment: http://stackoverflow.com/comment/84790587
accepted answer of: http://stackoverflow.com/q/48891613
score: 0
has comment: http://stackoverflow.com/comment/84790777
answers question: http://stackoverflow.com/q/48891613
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84790761

http://stackoverflow.com/a/48895999
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84798196
has body: If you have a tuple array like this tupleArray = [(2222,23),(2222,23)...] You can build another frecuency array and check if the value before is the same to increase the value tupleArray = [(2222,23),(2222,23),(2222,24),(2222,23),(3333,24),(3333,24),(3333,24)] frecuencyArray = [] tempValue = 1 for x in range(len(tupleArray)): if (x-1&gt;=0 and tupleArray[x][1]==tupleArray[x-1][1]): tempValue += 1 else: tempValue=1 frecuencyArray.append(tempValue) print(frecuencyArray) Test the code: https://repl.it/repls/WavyLostDatamining
type: Answer
accepted answer of: http://stackoverflow.com/q/48895851
score: 1
upvote count: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48895851

http://stackoverflow.com/q/48887664
answer count: 1
has comment: http://stackoverflow.com/comment/84781024
favorite count: 0
has comment: http://stackoverflow.com/comment/84781954
has comment: http://stackoverflow.com/comment/84782166
has body: Here is the original code I copied from Make Games with Python.2-Raspberry Pi, page 33: import pygame, sys import pygame.locals as GAME_GLOBALS import pygame.event as GAME_EVENTS # pygame variables pygame.init() windowWidth = 800 windowHeight = 800 surface = pygame.display.set_mode((windowWidth, windowHeight)) pygame.display.set_caption('Pygame Keyboard!') # square variables playerSize = 20 playerX = (windowWidth / 2) - (playSize / 2) playerY = windowHeight - playerSize playerVX = 1.0 playerVY = 0.0 jumpHeight = 25.0 moveSpeed = 1.0 maxSpeed = 10.0 gravity = 1.0 #keybpard variables leftDown = False rightDown = False haveJumped = False def move(): global playerX, playerY, playerVX, playerVY, haveJumped, gravity #move left if leftDown: # if we are already moving to the right,reset #the moving speed and invert the direction if playerVX &gt; 0.0: playerVX = moveSpeed playerVX = -playerVX # make sure our square does not leave our #window to the left if playerX &gt; 0: playerX += playerVX #move right if rightDown: #if we are already moving to the left,reset #the moving speed again if playerVX &lt; 0.0: playerVX = moveSpeed #make sure our square does not leave our #window to the right if playerX + playerSize &lt; windowWidth: playerX += playerVX if playerVY &gt; 1.0: playerVY = player * 0.9 else: playerVY = 0.0 haveJumped - False # is our square in the air? # better add some gravity to bring it back down if playerY &lt; windowHeight - playerSize: playerY += gravity gravity = gravity * 1.1 else: playerY = windowHeight - playerSize gravity = 1.0 playerY -= playerVY if (playerVX &gt; 0.0 and playerVX &lt; maxSpeed) or (playerVX &lt; 0.0 and playerVX &gt; -maxSpeed): if not haveJumped and (leftDown or rightDown) playerVX = playerVX * 1.1 # how to quit our program def quitGame(): pygame.quit() sys.exit() while True: surface.fill((0,0,0)) pygame.draw.rect(surface, (255,0,0), (playerX, playerY, playerSize, playerSize)) #get a list of all enets that happened since #the last redraw…
tagged with: python
tagged with: pygame
has comment: http://stackoverflow.com/comment/84784225
has comment: http://stackoverflow.com/comment/84781506
has answer: http://stackoverflow.com/a/48889601
has comment: http://stackoverflow.com/comment/84784149
has comment: http://stackoverflow.com/comment/84780955
has comment: http://stackoverflow.com/comment/84782246
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84783651
score: -5
has comment: http://stackoverflow.com/comment/84780625
has comment: http://stackoverflow.com/comment/84780694
has comment: http://stackoverflow.com/comment/84780286
downvote count: 5
has comment: http://stackoverflow.com/comment/84783286
type: Question
accepted answer: http://stackoverflow.com/a/48889601
has title: Is there anything wrong with the Python code itself?
upvote count: 0

http://stackoverflow.com/comment/84764106
score: 2
comment on: http://stackoverflow.com/q/48880009
has text: the largest key of dictionary a & b is 7 . please clear the objective of the question
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48932445
possible better answer: http://stackoverflow.com/a/49024343
type: Question
has answer: http://stackoverflow.com/a/49024343
upvote count: 35
has answer: http://stackoverflow.com/a/48932528
has answer: http://stackoverflow.com/a/48932604
favorite count: 0
has answer: http://stackoverflow.com/a/52615977
answer count: 5
tagged with: django
accepted answer: http://stackoverflow.com/a/48932604
tagged with: python
score: 34
downvote count: 1
has answer: http://stackoverflow.com/a/48932517
has title: Can't install Django 2.0 by pip
has body: I am building new Django app with a new version of Django. I found Django 2.0 is available (2.0.2) https://www.djangoproject.com/download/, and now trying to install it with pip. pip install Django==2.0.2 But it's not working for me. Could not find a version that satisfies the requirement Django==2.0 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10) No matching distribution found for Django==2.0 I am using python 2.7.14 and pip 9.0.1. What's wrong here?
type: AnsweredQuestion

http://stackoverflow.com/q/48871169
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48871506
tagged with: python
has comment: http://stackoverflow.com/comment/84746207
type: AnsweredQuestion
score: 1
has comment: http://stackoverflow.com/comment/84746836
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84746395
has body: I have two DataFrames. The first, df1, has historical time series data for a variety of tickers with a DateTime index that looks like this: ABC DEF XYZ 2011-06-06 10.00 10.00 10.0000 2011-06-17 10.00 10.00 10.0000 2011-06-21 10.00 10.00 10.0000 2011-06-22 10.00 10.00 10.0000 2011-06-23 10.00 10.00 10.0000 2011-06-24 10.00 10.00 10.0000 2011-06-30 10.00 10.00 10.0000 2011-07-11 10.00 10.00 10.0000 The second, df2, has three columns; a Start_Date, End_Date, and Ticker. Both the Start_Date and End_Date are in datetime format: End_Date Start_Date Ticker 0 2011-06-27 2011-06-22 ABC 1 2011-06-30 2011-06-17 DEF 2 2011-06-25 2011-06-18 XYZ I want to create a third DataFrame, df3, using the following code df4 = df.copy() df4.lock[:] = np.nan Between df2['Start_Date'] and df2['End_Date'] I want to populate df3 rows with 1.00 and leave the other rows as np.nan. I've tried to create a function and also to iterate over df2. def pos(): position = 1 for i in df2['Ticker']: df3.at[df2['Start_Date'], i] = position return pos or def pos(): position = 1 for index, row in df2.iterrows: df3.at[index, row['Start_Date']] = position return pos The resulting df3 would look like this: ABC DEF XYZ 2011-06-06 NaN NaN NaN 2011-06-17 NaN 1.0 NaN 2011-06-21 NaN 1.0 1.0 2011-06-22 1.0 1.0 1.0 2011-06-23 1.0 1.0 1.0 2011-06-24 1.0 1.0 1.0 2011-06-30 NaN 1.0 NaN 2011-07-11 NaN NaN NaN 2011-07-13 NaN NaN NaN 2011-07-14 NaN NaN NaN I am not having much luck with either. What is the best way to do this? Thanks in advance
tagged with: pandas
has title: Creating a Pandas DataFrame conditional on another DataFrame
has answer: http://stackoverflow.com/a/48871506
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48820375
has answer: http://stackoverflow.com/a/74264677
has comment: http://stackoverflow.com/comment/84645174
has comment: http://stackoverflow.com/comment/84644843
has answer: http://stackoverflow.com/a/61790659
has answer: http://stackoverflow.com/a/79473116
has comment: http://stackoverflow.com/comment/84644980
type: Question
tagged with: getchar
has answer: http://stackoverflow.com/a/67243385
has comment: http://stackoverflow.com/comment/84644987
answer count: 6
score: 15
has comment: http://stackoverflow.com/comment/84644895
has answer: http://stackoverflow.com/a/48820491
has title: Is there a built-in function in Python 3 like getchar() in C++?
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/510357
has body: I want to do user input in python which is similar to getchar() function used in c++. c++ code: #include&lt;bits/stdc++.h&gt; using namespace std; int main() { char ch; while(1){ ch=getchar(); if(ch==' ') break; cout&lt;&lt;ch; } return 0; } Input: stack overflow Output: stack In the above code, when a space input from the user than the loop breaks. I want to do this in python using getchar() type function as I used in c++ code.
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48820501
tagged with: input
tagged with: python
has comment: http://stackoverflow.com/comment/84644538
upvote count: 15
tagged with: c++
has comment: http://stackoverflow.com/comment/84644898

http://stackoverflow.com/q/48856215
tagged with: python
score: 2
downvote count: 0
type: UnansweredQuestion
has title: get the power number from scientific notated number of a pandas Dataframe string
type: Question
has comment: http://stackoverflow.com/comment/84716316
upvote count: 2
answer count: 1
has comment: http://stackoverflow.com/comment/84716889
has body: By reading a tab-delimited file with pandas I get a dataframe with strings that could be converted to a number using to_numeric(), BUT most of the numbers are so small that even float64 precision is insuffcient (e.g. 1,234e-4500) Setting them to 0 is not an option (calculating, plotting &amp; differentiate). Therefore mantissa and exponent should find their way to the dataframe separately. How can I most easily transform the string and keep both values together as numbers? Thanks in advance for your help!
favorite count: 0
tagged with: precision
has answer: http://stackoverflow.com/a/48856413
tagged with: pandas

http://stackoverflow.com/comment/84792657
comment on: http://stackoverflow.com/q/48893474
has text: possible duplicate with: https://stackoverflow.com/questions/18689823/pandas-dataframe-replace-nan-values-with-average-of-columns
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84836979
type: QuestionComment
has text: Try: df['genres'] = df['genres'].str.lstrip(). Or wait.. is it a list?
comment on: http://stackoverflow.com/q/48915233
score: 0
type: Comment

http://stackoverflow.com/a/48930593
has comment: http://stackoverflow.com/comment/84869048
has comment: http://stackoverflow.com/comment/84869229
score: 0
answers question: http://stackoverflow.com/q/48929787
has comment: http://stackoverflow.com/comment/84932178
has body: You can use a list comprehension structure, (the code below has been tested using Python3.6): # Given your JSON has successfully been parsed into a dictionary &gt; input={'Time1': {'A':'Value1A', 'B':'Value1B'}, 'Time2': {'A','Value2A', 'B', 'Value2B'}} # Iterate over the dictionary and build a new item out of each key/value couple &gt; transformed=[(v.update({'Time': k}) or v) for (k, v) in input.items()] &gt; print(transformed) [ { 'A' : 'Value1A' 'B' : 'Value1B' 'Time': 'Time1' },{ 'A' : 'Value2A' 'B' : 'Value2B' 'Time': 'Time2' }, … ] What happens with (v.update({'Time': k}) or v) ? Given v is a dictionary, v.update(...) will add a new entry to the instance (in other words, it mutates the instance). This method doesn't return the instance though but None, fortunately wrapping the call between parenthesis gives the opportunity to build an expression that will ultimately return the v instance. v being a dict object (given it is not empty) it will be evaluated truthfully in a Boolean context, hence the (… or v) construct.
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48929787
type: Answer

http://stackoverflow.com/comment/84780213
type: Comment
comment on: http://stackoverflow.com/q/48887603
score: 0
has text: @DavidG i could only see file level template not function level :(. i'm new to pycharm
type: QuestionComment

http://stackoverflow.com/q/48834317
has comment: http://stackoverflow.com/comment/84723061
has title: Using a bash script to execute python script with arguments
downvote count: 1
type: Question
score: -1
has answer: http://stackoverflow.com/a/48834454
has comment: http://stackoverflow.com/comment/84674987
has comment: http://stackoverflow.com/comment/84675194
tagged with: bash
has body: I have been searching for an answer to no avail. I have a python script that I would like to run that has quite a few arguments. It works just fine when I run the command from the terminal, but as soon as I try to put it in a bash script it no longer works. script.py --arg1 --arg2 --arg3 --arg4 --arg5 This works. #!/bin/bash script.py --arg1 --arg2 --arg3 --arg4 --arg5 This does not. I get no error message or output.
has comment: http://stackoverflow.com/comment/84673188
upvote count: 0
has comment: http://stackoverflow.com/comment/84675175
answer count: 1
linked to: http://stackoverflow.com/q/14155669
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84673385
has comment: http://stackoverflow.com/comment/84673157
has comment: http://stackoverflow.com/comment/84673244

http://stackoverflow.com/a/48811549
type: AcceptedAnswer
upvote count: 5
type: Answer
has body: How about using numpy broadcasting? mx1 = np.matrix([[2,9,9],[2,5,8],[7,2,9]]) mx2 = np.matrix([[7,1,3],[5,8,2],[6,9,5]]) res = np.sum(mx1, axis = 1) + np.sum(mx2, axis = 0)
downvote count: 0
answers question: http://stackoverflow.com/q/48811196
score: 5
accepted answer of: http://stackoverflow.com/q/48811196

http://stackoverflow.com/q/48951047
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84909922
tagged with: for-loop
tagged with: pandas
has answer: http://stackoverflow.com/a/53915121
has body: Say I have a dataframe that looks like: d = {'option1': ['1', '0', '1', '1'], 'option2': ['0', '0', '1', '0'], 'option3': ['1', '1', '0', '0'], 'views': ['6', '10', '5', '2'] df = pd.DataFrame(data=d) print(df) option1 option2 option3 views 0 1 0 1 6 1 0 0 1 10 2 1 1 0 5 3 1 0 0 2 I'm trying to build a for loop that iterates over each column (except the column "views") and each row. If the value of a cell is not 0, I want to replace it with the corresponding value of the column "views" from the same row. The following output is required (should be easier to understand): option1 option2 option3 views 0 6 0 6 6 1 0 0 10 10 2 5 5 0 5 3 2 0 0 2 I tried something like: df_range = len(df) for column in df: for i in range(df_range): if column != 0: column = df.views[i] But I know I'm missing something, it does not work. Also please note that in my real dataframe, I have dozens of columns, so I need something that iterates over each column automatically. Thanks!! I saw this thread Update a dataframe in pandas while iterating row by row but it doesn't exactly apply to my problem, because I'm not only going row by row, I also need to go column by column.
has comment: http://stackoverflow.com/comment/84910140
has comment: http://stackoverflow.com/comment/84912332
favorite count: 0
has answer: http://stackoverflow.com/a/48953782
tagged with: python
has comment: http://stackoverflow.com/comment/84909611
has answer: http://stackoverflow.com/a/48952395
answer count: 4
score: 8
linked to: http://stackoverflow.com/q/23330654
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48952856
has comment: http://stackoverflow.com/comment/84908975
has comment: http://stackoverflow.com/comment/84909463
has comment: http://stackoverflow.com/comment/84909739
upvote count: 8
type: Question
has title: Iteration over columns and rows in Pandas Dataframe
possible better answer: http://stackoverflow.com/a/48953782
has answer: http://stackoverflow.com/a/48952856

http://stackoverflow.com/a/48832649
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84671566
accepted answer of: http://stackoverflow.com/q/48832303
has comment: http://stackoverflow.com/comment/84669673
has comment: http://stackoverflow.com/comment/84669586
has comment: http://stackoverflow.com/comment/84669774
has body: You are reading from msg, not sys.argv. if "&gt;senddata".lower() in msg: print("Command Accepted!") ip = msg.split(" ")[1] datasize = msg.split(" ")[2]
has comment: http://stackoverflow.com/comment/84670048
has comment: http://stackoverflow.com/comment/84671702
has comment: http://stackoverflow.com/comment/84669650
has comment: http://stackoverflow.com/comment/84669989
has comment: http://stackoverflow.com/comment/84669538
has comment: http://stackoverflow.com/comment/84671882
answers question: http://stackoverflow.com/q/48832303
type: AcceptedAnswer

http://stackoverflow.com/comment/84760127
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48878059
has text: Please see this, it is almost what you're looking for: https://stackoverflow.com/questions/3042757/downloading-a-picture-via-urllib-and-python

http://stackoverflow.com/comment/84656149
comment on: http://stackoverflow.com/q/48824880
score: 0
has text: Have tested this myself with different Pandas and created an issue on GitHub. Pandas 19 is working fine but Pandas 22 has problems.
type: Comment
type: QuestionComment

nolearn
type: Tag
tag name: nolearn
tags question: http://stackoverflow.com/q/48832093

http://stackoverflow.com/comment/84735691
has text: That looks like an artifact caused by wrapping of large values. Why do you convert to `uint8`?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48865868

http://stackoverflow.com/comment/84913489
comment on: http://stackoverflow.com/q/48951648
type: QuestionComment
has text: It's a diferent question.. Anyway, I did this: https://pastebin.com/4cHcHFm9 but no courses are shown..
score: 0
type: Comment

http://stackoverflow.com/comment/84836570
has text: @juanpa.arrivillaga thanks for your response as all the others. i agree line.replace would be the better function. Unfortunately within my python 2.6 environment it just removes the back slash and leave the additional pipe in the line.
comment on: http://stackoverflow.com/q/48914705
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48942835
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48942762
has body: When you add a value to the set via set.add() method, The return value of the function is None which gets assigned to the dictionary. Instead first add the values to the set and then assign the value of set to the dictionary.

http://stackoverflow.com/q/48940407
has comment: http://stackoverflow.com/comment/84905029
answer count: 0
type: UnansweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84888500
has body: So I am working on a project for school and at a complete facedesking loss here. My dictionaries are in order and I am converting the numerical values to a float as I should, but when Mapplot renders it the numbers come out in a an alphabetical order (ie: 1111, 1112, 133333, 20) on the graph. I cannot for the life of me figure out how to fix it and it's got me frustrated. I am wanting to have the values displayed in a proper numeric order (descending) and cannot get it to work. import sqlite3 import re import requests from math import pi from itertools import chain from collections import namedtuple from bokeh.io import show, output_notebook from bokeh.plotting import figure, output_file, show from bokeh.models import HoverTool, FuncTickFormatter, FixedTicker, ColumnDataSource import pandas as pd import numpy as np import matplotlib.pyplot as plt from collections import OrderedDict from pandas import DataFrame from collections import Counter from operator import itemgetter token = '' header = headers = {'Authorization': f'Bearer {token}','Content-type': 'application/json'} steam_hours = requests.get('https://query.data.world/s/5cOVc-nvDK4DkUJ2MFZuAqCcAqTJrN', headers=headers) raw_data = steam_hours.text steam_list = raw_data.split('\r\n') #print(steam_list) steam_list[2] game_hours = [r.split('|')[-1] for r in steam_list[1:]] game_name = [r.split('|')[0] for r in steam_list[1:]] game_hours_edit = [i.replace('"', '') for i in game_hours] def remove_comma(s): return s[1:] def remove_comma_name(s): return s[:-1] game_hours_edit = [remove_comma(s) for s in game_hours_edit] game_hours = game_hours_edit game_name_edit = [remove_comma_name(s) for s in game_name] game_name = game_name_edit games_dict = OrderedDict(zip(game_name, game_hours)) print(games_dict) #key, value = ('asd', 1) print('\n') for key, value in games_dict.items(): print('\n') print(key, value) print('\n') scrubbed = [re.sub(r'[^\x00-\x7F]+',' ', game_hours) for game_hours in game_hours] #print(f"Game Name…
type: Question
has title: Mapplotlib Output Issue
has comment: http://stackoverflow.com/comment/84887918
tagged with: python

http://stackoverflow.com/comment/84886323
score: 0
comment on: http://stackoverflow.com/q/48939280
type: Comment
type: QuestionComment
has text: So you want to store the id/symbol mapping entirely in memory, and you want the cache populated at import time. When you delete a row in the database, how is your run-time cache going to be invalidated?

http://stackoverflow.com/a/48808229
has body: As @Coldspeed mentions in his comment, the variable x which you delete is not the same as the element in the list object. Similar behaviour will be seen if you try to assign to x: for x in my_list: x='bla' #does not modify anything in my_list However, as the items are references to the same memory block, the comparison x is my_list[0] will equate to True in the first loop iteration. As such, it is possible to perform operations on the list through usage of the shared reference, for example: for x in my_list[:]: my_list.remove(x) #results in an empty list Care has to be taken to first create a copy of the list and iterate over these items though, as was done in the previous lines. If you are hasty and loop over the items of a dynamically changing list, you will run into some more python magic. for x in my_list: my_list.remove(x) #the first element gets deleted, then the second element in the list, which now has length 2, is deleted. #Final result is the list [2] remaining
upvote count: 2
downvote count: 1
answers question: http://stackoverflow.com/q/48807953
score: 1
type: Answer

http://stackoverflow.com/comment/85107818
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48954080
has text: Thanks a million for tracking this down @MRocklin! I can replicate the github example leak you have, but it looks like it is a little different from mine - the code used there fixes my leak! I guess the best way to proceed will be to make a repro example of my exact issue, and file an issue on the dask github. If you post your example from github, that will be accepted for the answer and bounty.

http://stackoverflow.com/a/48903741
score: 4
type: Answer
has body: You could use: [Python]: itertools.groupby(iterable, key=None) - to group (outer) list elements based on their 1st 2 values (e.g. ("fruit", "banana")) [Python]: max(iterable, *[, key, default]) - to get the maximum value of one such group, based on their 3rd element (the 1st letter("v") + the number that comes after it (fixed it, to work with numbers with more than one digit)) [Python]: Lambda Expressions - to specify the grouping criteria &gt;&gt;&gt; import itertools &gt;&gt;&gt; &gt;&gt;&gt; data = [['fruit', 'apple', 'v1', 'some data'], ... ['fruit', 'apple', 'v2', 'some data'], ... ['fruit', 'apple', 'v3', 'some data'], ... ['fruit', 'banana', 'v1', 'some data'], ... ['fruit', 'banana', 'v2', 'some data'], ... ['animal', 'dog', 'v1', 'some data']] &gt;&gt;&gt; &gt;&gt;&gt; [max(item[1], key=lambda x: (x[2][0], int(x[2][1:]))) for item in itertools.groupby(data, key=lambda x: (x[0], x[1]))] [['fruit', 'apple', 'v3', 'some data'], ['fruit', 'banana', 'v2', 'some data'], ['animal', 'dog', 'v1', 'some data']] Or you could go the (old fashioned) manual way (e.g. using a helper dictionary): &gt;&gt;&gt; helper_dict = dict() &gt;&gt;&gt; for item in data: ... item_v = helper_dict.get((item[0], item[1]), (None, None, "v0"))[2] ... if (item_v[0], int(item_v[1:])) &lt; (item[2][0], int(item[2][1:])): ... helper_dict[(item[0], item[1])] = item ... &gt;&gt;&gt; print(list(helper_dict.values())) [['fruit', 'apple', 'v3', 'some data'], ['animal', 'dog', 'v1', 'some data'], ['fruit', 'banana', 'v2', 'some data']]
upvote count: 4
answers question: http://stackoverflow.com/q/48903434
downvote count: 0

http://stackoverflow.com/q/48857273
downvote count: 0
has body: I am new to Python. After finishing the tutorials I am trying to build small apps to improve myself. I am making little console diary program as you can see. import os def greetings(): name = input("Who is using program : ") return "Hello "+name+" welcome to the diary." def what_todo(): print("What would you like to do today ?") print("Taking notes (1) \nReading notes (2)") choice = int(input()) return choice def do(): if what_todo() == 1: file_name = input("Please name today's diary : ") f = open(file_name,"w") f.write(input()) f.close() elif what_todo() == 2: file_name = input("Which diary you want to read : ") if os.path.isfile(file_name): f = open(file_name,"r") for x in f: print(x) else: print("file does not exist") def main(): print(greetings()) do() if __name__ == "__main__": main() I have three things to ask : When i call if what_todo() == 1: it runs the what_todo() function but I only want the return of the what_todo() function and of course print's are repeating itself in the second call for elif statement. Is there a way to do it or I am going all wrong? Like unnecessary functions or anything else. I am getting user input for file name it is okay but I want to create file as a ".txt" or maybe ".data". How do I do that? One last thing. As a newbie, if you would like to share I want your opinion about the code I wrote or advice about it. Thank you for your answers. Output : This is the output : hilal@crescent:~/Diary$ python diary.py Who is using program : L Hello L welcome to the diary. What would you like to do today ? Taking notes (1) Reading notes (2) 1 Please name today's diary : a aaa hilal@crescent:~/Diary$ python diary.py Who is using program : L Hello L welcome to the diary. What would you like to do today ? Taking notes (1) Reading notes (2) 2 What would you like to do today ? Taking notes (1) Reading notes (2) 2 Which diary you want to read : a aaa
has comment: http://stackoverflow.com/comment/84718089
type: Question
has answer: http://stackoverflow.com/a/48857322
score: 1
has comment: http://stackoverflow.com/comment/84718180
has comment: http://stackoverflow.com/comment/84718109
has comment: http://stackoverflow.com/comment/84718134
has title: Function call and user input file name with extentions in Python
upvote count: 1
has answer: http://stackoverflow.com/a/48857324
favorite count: 0
has comment: http://stackoverflow.com/comment/84718216
possible better answer: http://stackoverflow.com/a/48857324
answer count: 3
tagged with: python
accepted answer: http://stackoverflow.com/a/48857322
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48857328

http://stackoverflow.com/comment/84769980
type: AnswerComment
comment on: http://stackoverflow.com/a/48824641
type: Comment
has text: Also, if this solves your problem could you mark the answer as complete?
score: 0

http://stackoverflow.com/comment/84799235
has text: It is a console application. Basically I want the program to continue running, forever, which it does now, unless I give it an optional input. I envision the input will basically set a variable that will no longer allow any more buys. The issue is I don't know how to make the input optional.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48896701
score: 0

http://stackoverflow.com/comment/84903430
score: 0
type: AnswerComment
type: Comment
has text: I have been researching @MalloyDelacroix but I cannot seem to get it to work. I have look at numerous examples of how to implement this and it has not worked.
comment on: http://stackoverflow.com/a/48948513

http://stackoverflow.com/q/48844055
has comment: http://stackoverflow.com/comment/84692598
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84692567
type: AnsweredQuestion
has body: I am fairly new to programming and Python and I am struggling with setting up a loop to continue this basic name generator when user input is incorrect. I tried researching this issue but usually find answers using integers and the like and am having difficulty translating examples to execute what I need the program to do. I am not quite sure if my using of the IF, ELSE, and ELIF, statements is even being used correctly. Thanks to anyone who can lend guidance on this topic. import random def orcName(): # This is where the program will ask for male or female input from user. sex = input("What's your sex? ") # If user chooses Male the program will execute. if sex == 'Male': # This is where the list of male first names are stored. firstNameMale = ['Ughash', 'Spoguk', 'Truigig', 'Wudhagh', 'Wumkbanok', 'Hogug', 'Karrhig', 'Pargu', 'Xokuk', 'Furbog'] # This is where the list of male last names are stored. lastNameMale = ['Opkagut', 'Zombilge', 'Grushnag', 'Gujarek', 'Igmut', 'Gorgo', 'Filge', 'XorokuShamob', 'Zurgha'] # This is where the random function calls on the lists to assemble the name. firstName = random.choice(firstNameMale) lastName = random.choice(lastNameMale) print('Your name is', firstName, lastName) break # If user chooses Female the program will execute. elif sex == "Female": # This is where the list of female first names are stored. firstNameFemale = ['Ughash', 'Spoguk', 'Truigig', 'Wudhagh', 'Wumkbanok', 'Hogug', 'Karrhig', 'Pargu', 'Xokuk', 'Furbog'] # This is where the list of female last names are stored. lastNameFemale = ['Opkagut', 'Zombilge', 'Grushnag', 'Gujarek', 'Igmut', 'Gorgo', 'Filge', 'XorokuShamob', 'Zurgha'] # This is where the random function calls on the lists to assemble the name. firstName = random.choice(firstNameFemale) lastName = random.choice(lastNameFemale) print('Your name is', firstName, lastName) break # If user did not choose Male of Female program will execute. else: print('Please choose from Male or Female. Remember capital…
has title: Having difficulty setting up a loop to continue program when wrong user input is entered
has comment: http://stackoverflow.com/comment/84692511
has answer: http://stackoverflow.com/a/48844158
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84692487
has comment: http://stackoverflow.com/comment/84692636
answer count: 1
linked to: http://stackoverflow.com/q/2988017
linked to: http://stackoverflow.com/q/23294658
has comment: http://stackoverflow.com/comment/84692637
has comment: http://stackoverflow.com/comment/84692613
accepted answer: http://stackoverflow.com/a/48844158
score: 1
favorite count: 0

http://stackoverflow.com/comment/84644230
type: Comment
score: 0
type: AnswerComment
has text: @juanpa.arrivillaga See the linked duplicate. I'm not saying there is anything wrong with argument passing necessarily. But it seems that OP would prefer it to be a globally available in both files.
comment on: http://stackoverflow.com/a/48820135

http://stackoverflow.com/comment/84658233
type: Comment
comment on: http://stackoverflow.com/q/48827155
score: 2
type: QuestionComment
has text: It might be worth noting that it is not necessary to have calls to `plt.subplot()` _and_ `fig, ax = plt.subplots(nrows=2, ncols=2)`

http://stackoverflow.com/comment/84866987
type: Comment
has text: I am not sure this returns valid answer `cumm_sum(0.0, 1.0, 10000000, ten_million[5000]) = 4999999.250249749` but `sum(ten_million[5000:]) = 4999998.750249899`
comment on: http://stackoverflow.com/a/48929722
score: 0
type: AnswerComment

http://stackoverflow.com/comment/113062110
has text: Hi @Mike, seems there is no solution directly comparable to the R workflow but see Koen's answer below as a starting point for creating your own
type: Comment
comment on: http://stackoverflow.com/q/48944296
score: 0
type: QuestionComment

http://stackoverflow.com/a/48811542
has comment: http://stackoverflow.com/comment/84638461
upvote count: 11
has comment: http://stackoverflow.com/comment/84626603
has comment: http://stackoverflow.com/comment/84627529
has body: You can simply use next for a no-import solution: list1 = ['Dog', 'Cat', 'Monkey', 'Parakeet', 'Zebra'] list_1 = iter(list1) list2 = [[True, True], [False], [True], [False]] new_list2 = [[next(list_1) for _ in i] for i in list2] Output: [['Dog', 'Cat'], ['Monkey'], ['Parakeet'], ['Zebra']] However, for input n levels deep, you can use recursion: list1 = ['Dog', 'Cat', 'Monkey', 'Parakeet', 'Zebra'] list_1 = iter(list1) list2 = [[True, [True, False]], [False], True] def place_data(current): return [next(list_1) if isinstance(i, int) else place_data(i) for i in current] print(place_data(list2)) Output: [['Dog', ['Cat', 'Monkey']], ['Parakeet'], 'Zebra']
has comment: http://stackoverflow.com/comment/84639511
has comment: http://stackoverflow.com/comment/84639814
type: Answer
answers question: http://stackoverflow.com/q/48811213
score: 11
has comment: http://stackoverflow.com/comment/84671252
downvote count: 0

http://stackoverflow.com/comment/84631067
type: Comment
has text: Ah..! Had another allowed_hosts below. how dumb of me. Thanks anyways.
comment on: http://stackoverflow.com/q/48813593
score: 2
type: QuestionComment

http://stackoverflow.com/comment/84804356
type: Comment
type: QuestionComment
has text: I also was bugged by having only one scalar value for the cost as the "spacial" information of the word2vec would be lost. I've tried using MSE as well but I couldn't manage to make it work. I am gonna try your suggestions and see If I can get MSE to work
score: 1
comment on: http://stackoverflow.com/q/48843521

http://stackoverflow.com/comment/84761306
type: QuestionComment
has text: PIL version 1.1.7 fails on my system with a different error `_TIFFVSetField: tst.tiff: Invalid tag "TileOffsets" (not supported by codec)`. Consider using `gdal` instead of `PIL` for this image. Also there is a similar [post on GIS.SE](https://gis.stackexchange.com/q/267989/7086) regarding PIL support for advanced TIFF features that remains unanswered for more than a month.
score: 1
comment on: http://stackoverflow.com/q/48877673
type: Comment

http://stackoverflow.com/q/48832320
has answer: http://stackoverflow.com/a/48835673
score: 0
type: Question
tagged with: graph
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84671367
tagged with: matplotlib
accepted answer: http://stackoverflow.com/a/48835673
has comment: http://stackoverflow.com/comment/84669543
answer count: 1
linked to: http://stackoverflow.com/q/4700614
has body: I am trying to inset a graph inside the parent graph following the accepted answer here. However, the plotting framework I am using is quite different: 1) First of all, the Legend is located outside the graph, for which I have followed the second answer posted here, i.e. via shrinking the parent graph: plt.figure() # Shrink current axis by 20% box = ax1.get_position() ax1.set_position([box.x0, box.y0, box.width * 0.8, box.height]) 2) For the labeling, I am using the ax1.legend((p1, p2, p3), ("label for p1", "label for p2", "label for p3")) procedure. If I ran the code with plt.show() and sys.exit() commented, the entire graph is produced: However when implementing the inset answer, and trying to inset to the area of the pink and blue data: (1) Replace plt.figure() by fig, ax1 = plt.subplots(), (2) Using a ax2 for the inset, since a ax1 has already been used for placing the legend outside the graph, (3) Uncommentplt.show() and sys.exit(), no data is plotted both in the parent and inset graphs: import numpy as np import matplotlib.pyplot as plt from matplotlib.font_manager import FontProperties import sys x_1 = np.array([ 2.56480648, 2.56635664, 2.57565757, 2.59425943, 2.61906191, 2.64463946, 2.66711671, 2.69966997, 2.72292229, 2.75392539, 2.79422942, 2.81360636, 2.84460946, 2.88026303, 2.91746675, 2.94846985, 2.99187419, 3.01822682, 3.06085609, 3.08565857, 3.12286229, 3.18331833, 3.24067407, 3.25772577, 3.36158616, 3.35616062, 3.43056806, 3.45847085, 3.61574815, 3.65387259, 3.89764927, 9.1 ]) x_2 = np.array([ 5.77982798, 5.77827783, 5.79067907, 5.81083108, 5.82788279, 5.85113511, 5.87438744, 5.89763976, 5.92011701, 5.94414441, 5.96584658, 5.98987399, 6.01467647, 6.03637864, 6.06118112, 6.08443344, 6.11543654, 6.13248825, 6.16194119, 6.18751875, 6.21077108, 6.23479848, 6.26192619, 6.29137914, 6.32083208, 6.35028503, 6.38128813, 6.41306631, 6.45569557, 6.47894789, 6.50530053, 6.55645565, 6.5959846 , 6.62853785, 6.67349235, 6.71612161, 6.76417642, 6.80293029, 6.86726173…
linked to: http://stackoverflow.com/q/21001088
has title: Inset graph, when using a legend placed outside the parent graph
tagged with: python

http://stackoverflow.com/comment/84790662
comment on: http://stackoverflow.com/a/48892488
type: Comment
has text: This is the link to image you can view it ... --> https://ibb.co/jdtXNc
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84818718
score: 0
comment on: http://stackoverflow.com/a/48845789
type: AnswerComment
has text: If it answers your question, can I please request that you mark the post as answer? Thanks.
type: Comment

http://stackoverflow.com/comment/84621321
type: QuestionComment
has text: The real question is, though: why do you use 6 QSpinBox widgets? All you really care for is a text field that accepts a valid MAC, right? Why split it into 6 widgets? With separate widgets, it becomes very awkward to copy and paste data. Basically, you will need to make those widgets act like a text field: when you type, cursor jumps between them, when you copy - the entire MAC is copied, when you paste - the MAC elements are pasted into spinboxes. It's hard because you shouldn't be doing it. Use a `QTextEdit` with a validator, and provide visual feedback (red/yellow/green) for validity.
score: 0
comment on: http://stackoverflow.com/q/48808940
type: Comment

http://stackoverflow.com/q/48922811
has title: How to save Keras model with best parameters using GridSearch
linked to: http://stackoverflow.com/q/42492824
answer count: 1
tagged with: keras
has body: Is there any way I can save the full Keras model with best parameters obtained using Gridsearch. I have the following Keras model: def create_model(init_mode='uniform'): n_x_new=train_selected_x.shape[1] model = Sequential() model.add(Dense(n_x_new, input_dim=n_x_new, kernel_initializer=init_mode, activation='sigmoid')) model.add(Dense(10, kernel_initializer=init_mode, activation='sigmoid')) model.add(Dropout(0.8)) model.add(Dense(1, kernel_initializer=init_mode, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) return model seed = 7 np.random.seed(seed) model = KerasClassifier(build_fn=create_model, epochs=30, batch_size=400, verbose=1) init_mode = ['uniform', 'lecun_uniform', 'normal', 'zero', 'glorot_normal', 'glorot_uniform', 'he_normal', 'he_uniform'] param_grid = dict(init_mode=init_mode) #cv = PredefinedSplit(test_fold=my_test_fold) grid = GridSearchCV(estimator=model, param_grid=param_grid,scoring='roc_auc',cv = PredefinedSplit(test_fold=my_test_fold), n_jobs=1) grid_result = grid.fit(np.concatenate((train_selected_x, test_selected_x), axis=0), np.concatenate((train_selected_y, test_selected_y), axis=0)) print("Best: %f using %s" % (grid_result.best_score_, grid_result.best_params_)) means = grid_result.cv_results_['mean_test_score'] stds = grid_result.cv_results_['std_test_score'] params = grid_result.cv_results_['params'] for mean, stdev, param in zip(means, stds, params): print("%f (%f) with: %r" % (mean, stdev, param)) I came to know that I can use callback and checkpoint method, but I don't know where to put the required code for this method in my original code. The code I came across while researching is as follows. filepath="weights.best.hdf5" checkpoint = ModelCheckpoint(filepath, monitor='val_acc', verbose=1, save_best_only=True, mode='max') callbacks_list = [checkpoint]
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has answer: http://stackoverflow.com/a/48924203
type: Question
tagged with: neural-network
score: 0

http://stackoverflow.com/a/48828574
has body: In python, the syntax array[x:y] slices the array from the index x to y-1. So instead of array[x] which return a value of the array, it return the array with only the elems from x to y-1.
upvote count: 2
score: 2
answers question: http://stackoverflow.com/q/48828475
downvote count: 0
type: Answer

http://stackoverflow.com/a/58491770
accepted answer of: http://stackoverflow.com/q/48944296
has body: Since the 2019 version of MS office you can add svg files as images and then ungroup them to make them editable. See 'Convert an SVG image to an Office shape' on this MS page. In my personal experience, this is however neither very stable nor complete. Another way, which is more stable and complete although still not perfect, is importing it in powerpoint as emf file, which is also a vector-format. Old version of matplotlib could export to this format. For newer version, I export as svg and then use inkscape --file "input.svg" --export-emf "output.emf" to convert to emf, which I then load in powerpoint. Ungrouping the object again allows you to edit, if everything works well.
answers question: http://stackoverflow.com/q/48944296
upvote count: 1
type: AcceptedAnswer
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/84681913
score: 0
comment on: http://stackoverflow.com/a/48838775
type: Comment
has text: Please read the [how to ask](https://stackoverflow.com/help/how-to-ask) help page. Include code, what you have tried, the original (if any), the result you got or didn't get, and what you expected to get.
type: AnswerComment

http://stackoverflow.com/comment/85081633
type: AnswerComment
type: Comment
has text: Thank you, everything works now. I went with your advice on creating a separate label for output instead of trying to display it in the TextInput as it seems to be much harder to manipulate in general because every single line of input has to be processed separately.
comment on: http://stackoverflow.com/a/48841328
score: 0

http://stackoverflow.com/q/48821140
score: 2
has body: How can I replace a single character in a string in python? For example: If I have a string abcccc and I want to replace the c at the third position, if I use .replace() it will replace every single c in the string.
downvote count: 0
type: Question
upvote count: 2
answer count: 1
has title: How to replace a single character from a string
has comment: http://stackoverflow.com/comment/84645788
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
tagged with: python
has answer: http://stackoverflow.com/a/48821286

http://stackoverflow.com/comment/84811629
type: QuestionComment
has text: Can you add a sample your csv file and target conditions ?
score: 0
comment on: http://stackoverflow.com/q/48903079
type: Comment

http://stackoverflow.com/q/48913757
has answer: http://stackoverflow.com/a/48916718
type: Question
has answer: http://stackoverflow.com/a/48916148
has comment: http://stackoverflow.com/comment/84838602
accepted answer: http://stackoverflow.com/a/48916148
has comment: http://stackoverflow.com/comment/84838103
tagged with: sorting
has comment: http://stackoverflow.com/comment/84837749
answer count: 2
has comment: http://stackoverflow.com/comment/84835535
tagged with: pandas
has comment: http://stackoverflow.com/comment/84837812
has comment: http://stackoverflow.com/comment/84836790
has comment: http://stackoverflow.com/comment/84836538
downvote count: 0
tagged with: reindex
favorite count: 0
possible better answer: http://stackoverflow.com/a/48916718
has title: Sorting in a Pandas pivot_table
tagged with: pivot-table
has comment: http://stackoverflow.com/comment/84837827
score: 6
tagged with: python
upvote count: 6
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84834454
has body: I have been looking all over trying to figure out how to sort my pivot table correctly and I haven't had any luck. client unit task hours month 0 A DVADA Account Management 6.50 January 1 A DVADA Buying 1.25 January 2 A DVADA Meeting / Call 0.50 January 3 A DVADA Account Management 3.00 January 4 A DVADA Billing 2.50 February 5 A DVADA Account Management 6.50 February 6 A DVADA Buying 1.25 February 7 A DVADA Meeting / Call 0.50 February 8 A DVADA Account Management 3.00 February 9 A DVADA Billing 2.50 February 10 A DVADA Billing 2.50 December 11 A DVADA Account Management 6.50 December 12 A DVADA Buying 1.25 December 13 A DVADA Meeting / Call 0.50 December 14 A DVADA Account Management 3.00 December 15 A DVADA Billing 2.50 December 16 A DVADA Account Management 6.50 August 17 A DVADA Buying 1.25 August 18 A DVADA Meeting / Call 0.50 August 19 A DVADA Account Management 3.00 August 20 A DVADA Account Management 6.50 April 21 A DVADA Buying 1.25 April 22 A DVADA Meeting / Call 0.50 April 23 A DVADA Account Management 3.00 April 24 B DVADA Account Management 6.50 January 25 B DVADA Buying 1.25 January 26 B DVADA Meeting / Call 0.50 January 27 B DVADA Account Management 3.00 January 28 B DVADA Billing 2.50 February 29 B DVADA Account Management 6.50 February 30 B DVADA Buying 1.25 February 31 B DVADA Meeting / Call 0.50 February 32 B DVADA Account Management 3.00 February 33 B DVADA Billing 2.50 February 34 B DVADA Billing 2.50 December 35 B DVADA Account Management 6.50 December 36 B DVADA Buying 1.25 December 37 B DVADA Meeting / Call 0.50 December 38 B DVADA Account Management 3.00 December 39 B DVADA Billing 2.50 December 40 B DVADA Account Management 6.50 August 41 B DVADA Buying 1.25 August 42 B DVADA Meeting / Call 0.50 August 43 B DVADA Account Management 3.00 August 44 B DVADA Account Management 6.50 April 45 B DVADA Buying 1.25 April 46 B DVADA Meeting / Call 0.50 April 47 C DVADA Account Management 3.00 April 48 C DVADA Account Management 6.50 January 49 C DV…

http://stackoverflow.com/a/48815718
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48815365
has body: Can do like this too: def func(d, l): while l: d = d[l.pop(0)] return d print(func(myDict,["main","foo","xyz"])) Returns: 'lorem' Or like above: def func(d, l): for k in l: d = d[k] return d
upvote count: 1

http://stackoverflow.com/q/48808904
type: UnansweredQuestion
tagged with: python
has title: Can I use dict.pop in map function. python 3.6
duplicate of: http://stackoverflow.com/q/47722712
type: Question
has comment: http://stackoverflow.com/comment/84621270
has comment: http://stackoverflow.com/comment/84620916
tagged with: python-3.6
score: 0
has comment: http://stackoverflow.com/comment/84621031
has body: I want to exclude keys from dict. I have script like this: #! .env/bin/pythoin3.6 d = {1:"a", 2: "b", 3: "c", 4: "d", 5: "v"} exclude = [1, 3] map(d.pop, exclude) print("Map result {}".format(d)) d = {1:"a", 2: "b", 3: "c", 4: "d", 5: "v"} exclude = [1, 3] for k in exclude: d.pop(k) print("Result of 'for k in ...' {}".format(d)) It returns this: Map result {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'v'} Result of 'for k in ...' {2: 'b', 4: 'd', 5: 'v'} As you can see second result is correct.But first is not. Can I use dict.pop in map function?
has comment: http://stackoverflow.com/comment/84621184
answer count: 0

http://stackoverflow.com/comment/84861423
has text: @RameshMaharjan just added some more info. thanks for the help
comment on: http://stackoverflow.com/q/48927271
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48846276
answers question: http://stackoverflow.com/q/48845796
has comment: http://stackoverflow.com/comment/84715788
has comment: http://stackoverflow.com/comment/84716327
type: Answer
score: 2
upvote count: 2
has body: Hmmm... have you tried THIS already? Also, how exactly did you install spyder? Maybe you didn't install it in the right environemnt(in your case probably the default root/base environment) I'd recommend installing it via conda in the terminal! Also make sure you have installed it in the right environment: get a list of all your environments: $ conda env list install it in a specific environment: $ conda install --name "your env" spyder and of course make sure you got the latest anaconda version: $ conda update -n base conda EDIT ok now we know you only have your base environment. since chardet is a dependency of spyder let's update those two packages first to be sure... $ conda update chardet $ conda update urllib3 Let's go on and check your spyder. Does it work now? if not try this: $ conda info spyder what do you get? you should get a very long list, but only the last entry is of importance, something like that: spyder 3.2.5 py27_0 ------------------- file name : spyder-3.2.5-py27_0.tar.bz2 name : spyder version : 3.2.5 build string: py27_0 build number: 0 channel : https://repo.continuum.io/pkgs/main/osx-64 size : 2.5 MB arch : None constrains : () license : MIT md5 : 5ec8ffcda103c23c81005a5aed0c91e7 platform : None subdir : osx-64 timestamp : 1514270782022 url : https://repo.continuum.io/pkgs/main/osx-64/spyder-3.2.5-py27_0.tar.bz2 dependencies: chardet &gt;=2.0 cloudpickle jedi &gt;=0.9 nbconvert numpydoc pickleshare psutil pycodestyle pyflakes pygments &gt;=2.0 pylint pyqt python &gt;=2.7,&lt;2.8.0a0 python.app pyzmq qtawesome &gt;=0.4.1 qtconsole &gt;=4.2 qtpy &gt;=1.2.0 rope &gt;=0.9.4 sphinx if you don't get anything back you have installed spyder in the wrong environment and you can skip step 1: STEP 1: uninstall spyder again. $ conda uninstall spyder STEP 2: reinstall it $ conda install spyder EDIT II Have you had a look at the link I posted? the only other thing that comes is in my mind is trying a different environment (for example called "myEnv"). $ co…
has comment: http://stackoverflow.com/comment/84715328
downvote count: 0

http://stackoverflow.com/q/48892305
score: -1
has title: Using beautiful soup - to extract string in a tag?
upvote count: 0
answer count: 1
favorite count: 0
tagged with: beautifulsoup
tagged with: linux
has answer: http://stackoverflow.com/a/48892528
tagged with: python
type: AnsweredQuestion
tagged with: xpath
tagged with: wordpress
has body: i am fairly new to bs4for that matter, but im trying to scrape a little chunk of information from a site: but it keeps printing "None" as if the title, or any tag if i replace it, doesn't exists. The project consits of two parts: the looping-part: (which seems to be pretty straightforward). the parser-part: where i have some issues - see below. I'm trying to loop through an array of URLs and scrape the data below from a list of wordpress-plugins. See my loop below- from bs4 import BeautifulSoup import requests #array of URLs to loop through, will be larger once I get the loop working correctly plugins = ['https://wordpress.org/plugins/wp-job-manager', 'https://wordpress.org/plugins/ninja-forms'] The project: for a list of status-data of wordpress-plugins: - approx 50 plugins are of interest! https://wordpress.org/plugins/wp-job-manager https://wordpress.org/plugins/ninja-forms https://wordpress.org/plugins/participants-database ....and so on and so forth. The parser-part: So this is my approach with beautiful soup - to extract string in a tag ? import bs4 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup my_url = "https://wordpress.org/plugins/participants-database/" uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") ttt = page_soup.find("div", {"class":#post-15991 > div.entry-meta > div.widget.plugin-meta"}) item = ttt.a.text print(item) Background: want to fetch the following data from this page: https://wordpress.org/plugins/participants-database/ i need the data of the following three lines - in the above mentioned example Version: 1.29.3 Active installations: 100,000+ Tested up to: 4.9.4 see the xpaths that i have found here: //*[@id="post-15991"]/div[4]/div[1] //*[@id="post-15991"]/div[4]/div[1]/ul/li[1] //*[@id="post-15991"]/div[4]/div[1]/ul/li[2] //*[@id="post-15991"]/div[4]/div[1]/ul/li[3] //*[@id="post-15991"]/div[4]/div[1]/ul/li[4] //*[@id="post-15991"]/div[4]/div[1]/…
downvote count: 1
type: Question
accepted answer: http://stackoverflow.com/a/48892528

http://stackoverflow.com/q/48839482
score: 7
favorite count: 0
has answer: http://stackoverflow.com/a/48839743
has comment: http://stackoverflow.com/comment/84697124
type: Question
linked to: http://stackoverflow.com/q/2128505
tagged with: python
accepted answer: http://stackoverflow.com/a/48839743
has comment: http://stackoverflow.com/comment/98316253
has body: I'm trying to delete a list of items from using Flask and SQLAchlemy in an elegant way. In my case, I want to delete old items (items that are less than a certain time are considered old) from my database. Here is my python model object: class ItemModel(db.Model): __tablename__ = 'items' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(80)) time = db.Column(db.Integer) Now, I tried to delete the items using the following filter_by query: def delete_from_db(self): db.session.query('items').filter_by(self.time &lt;= epoch_time).delete() db.session.commit() It just ends up giving me the error: filter_by() takes 1 positional argument but 2 were given If I try this using the filter function, instead of filter_by, I also receive an error: def delete_from_db(self): db.session.query('items').filter(self.time &lt;= epoch_time).delete() db.session.commit() sqlalchemy.exc.InvalidRequestError: This operation requires only one Table or entity be specified as the target. Finally, I decide to go back to the basics and use sql code and this works but I don't think it is very elegant: def delete_from_db(self): from sqlalchemy.sql import text cmd = 'delete from items where time &lt;= :time' db.engine.execute(text(cmd), time = epoch_time) db.session.commit() Is there a more elegant way to do this with Flask and SQLAchlemy?
upvote count: 7
answer count: 1
tagged with: sqlalchemy
has title: Deleting list of items in SQLAlchemy Flask
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/19243964
downvote count: 0
has comment: http://stackoverflow.com/comment/84697238

http://stackoverflow.com/comment/84931686
type: QuestionComment
comment on: http://stackoverflow.com/q/48962205
has text: Iterate through data once, carrying out all the `sub` and `replace` actions. Also have a look at `re.compile` and use these in `sub` for a potential performance boost.
score: 0
type: Comment

http://stackoverflow.com/comment/84760464
comment on: http://stackoverflow.com/q/48878188
has text: See i got to know about scaling from this video. https://www.youtube.com/watch?v=gV5fD8Xbwgk
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48841889
has comment: http://stackoverflow.com/comment/84687751
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/36484184
upvote count: 3
tagged with: urllib
type: Question
score: 3
has answer: http://stackoverflow.com/a/48842130
has comment: http://stackoverflow.com/comment/84687811
has title: How do I add a parameter to a POST request's body with urllib?
answer count: 1
has body: I need to send a POST request with this format using urllib: POST /oauth/access_token HTTP/1.1 User-Agent: themattharris' HTTP Client Host: api.twitter.com Accept: */* Authorization: OAuth oauth_consumer_key="cChZNFj6T5R0TigYB9yd1w", oauth_nonce="a9900fe68e2573b27a37f10fbad6a755", oauth_signature="39cipBtIOHEEnybAR4sATQTpl2I%3D", oauth_signature_method="HMAC-SHA1", oauth_timestamp="1318467427", oauth_token="NPcudxy0yU5T3tBzho7iCotZ3cnetKwcTIRlX0iwRl0", oauth_version="1.0" Content-Length: 57 Content-Type: application/x-www-form-urlencoded oauth_verifier=uw7NjWHT6OJ1MpJOXsHfNxoAhPKpgI8BlYDhxEjIBY While for the header I add it this way: AccessRequest = urllib.request.Request('https://api.twitter.com/oauth/access_token') AccessRequest.add_header('Authorization', oauth_header) What is the correct way to add the parameter which should stay in the body? Right now I'm doing: values = { 'oauth_verifier': verifier } data = urllib.parse.urlencode(values).encode('ascii') resp = urllib.request.urlopen(AccessRequest, data=data) but there must be something wrong since the server returns a HTTP Error 401: Authorization Required. What am I doing wrong?
downvote count: 0
has comment: http://stackoverflow.com/comment/84687791
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48842130
tagged with: python
has comment: http://stackoverflow.com/comment/84687892

http://stackoverflow.com/comment/84754256
comment on: http://stackoverflow.com/q/48875117
type: Comment
type: QuestionComment
has text: What about the server code?
score: 3

http://stackoverflow.com/comment/84767338
comment on: http://stackoverflow.com/a/48881477
type: AnswerComment
type: Comment
score: 2
has text: @Vivek Kalyanarangan - It is rename default column `<lambda>` only :)

http://stackoverflow.com/a/48830642
upvote count: 9
score: 9
downvote count: 0
has body: you're reading csv files, which are text files. So you need encoding but not binary mode. So you should not use rb to open them (it is advised to do so when using csv module in Python 2, but it's irrelevant in other contexts). Just use plain text mode: open("C:/Users/Nouros/Desktop/Thesis/english.csv","r", encoding='utf8').read() Me I would prefer using csv module, to avoid manual split of lines &amp; cols: import csv with open(r"C:\Users\Nouros\Desktop\Thesis\english.csv","r", encoding='utf8') as f: cr = csv.reader(f,delimiter=",") # , is default rows = list(cr) # create a list of rows for instance (note that csv module recommends using newline="" when opening files for reading in Python 3, but the issues are actually when writing files)
type: Answer
answers question: http://stackoverflow.com/q/48830535

http://stackoverflow.com/a/48890999
has comment: http://stackoverflow.com/comment/84787620
has comment: http://stackoverflow.com/comment/84789280
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84789017
has comment: http://stackoverflow.com/comment/84788730
has body: signup is in the project directory (the one that contains manage.py). Therefore the import should be simply: from signup.models import allusers1
accepted answer of: http://stackoverflow.com/q/48890669
downvote count: 0
has comment: http://stackoverflow.com/comment/84788173
has comment: http://stackoverflow.com/comment/84788244
has comment: http://stackoverflow.com/comment/84787668
has comment: http://stackoverflow.com/comment/84789462
has comment: http://stackoverflow.com/comment/84787631
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48890669
score: 1

http://stackoverflow.com/q/48952188
answer count: 1
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48952315
tagged with: mysql
type: Question
has title: Unable to unpack pymysql query result to variables
has body: I'm using a script that collects data from a database. I wanted to refine the script a bit, but ran into trouble. I'm running a query that I know will ALWAYS return only one row with 3 values in it. I want to unpack those values into separate variables, but only the last seems to actually have some sort of value. Here's my code: import pymysql cnx = pymysql.connect(host=dbHost, database=dbName, user=dbUser, passwd=dbPass) query = "select id_parameter,unit,shortname from t_list_metpara where shortname='TT'" with cnx.cursor() as cursor1: cursor1.execute(query) row = cursor1.fetchone() cnx.close() id_parameter, unit, shortname = row[:3] print(row) print(id_parameter, unit, shortname) print([type(v) for v in [id_parameter, unit, shortname]]) print([row[v] for v in [0, 1, 2]]) and the result: (1, 'Â°C\r', 'tt') tt [&lt;class 'int'&gt;, &lt;class 'str'&gt;, &lt;class 'str'&gt;] [1, 'Â°C\r', 'tt'] Can anyone explain to my why Python (or the pymysql package) behaves this way, and what I can do to avoid it?
score: 0
accepted answer: http://stackoverflow.com/a/48952315

http://stackoverflow.com/comment/84674083
has text: To me, the relative path seems purposeful. That's the point of querying the path of `$0` and `cd`-ing to that location. But you may be right.
type: AnswerComment
comment on: http://stackoverflow.com/a/48834723
score: 0
type: Comment

http://stackoverflow.com/comment/84727580
score: 1
has text: So why don't you use fileName as a class attribute ? you can use self.fileName to store the fileName and so don't need to pass it in function.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48862090

http://stackoverflow.com/comment/84712728
has text: @excaza It looks like text from a file - Kylo can you confirm this?
comment on: http://stackoverflow.com/q/48854669
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/q/48913149
has answer: http://stackoverflow.com/a/48974048
has comment: http://stackoverflow.com/comment/84833082
has body: Hi I am working with python 3 and I've been facing this issue for a while now and I can't seem to figure this out. I have 2 numpy arrays containing strings array_one = np.array(['alice', 'in', 'a', 'wonder', 'land', 'alice in', 'in a', 'a wonder', 'wonder land', 'alice in a', 'in a wonder', 'a wonder land', 'alice in a wonder', 'in a wonder land', 'alice in a wonder land']) If you notice, the array_one is actually an array containing 1-gram, 2-gram, 3-gram, 4-gram, 5-gram for the sentence alice in a wonder land. I purposefully have taken wonderland as two words wonder and land. Now I have another numpy array that contains some locations and names. array_two = np.array(['new york', 'las vegas', 'wonderland', 'florida']) Now what I want to do is get all the elements in the array_one that exist in array_two. If I take out an intersection using np.intersect1d of the two arrays I don't get any matches since wonderland is two separate words in array_one while in array_two it's a single word. Is there any way to do this? I've tried solutions from stack (this) but they don't seem to work with python 3 array_one would at max have 60-100 items while array_two would at max have roughly 1 million items but an average of 250,000 - 500,000 items. Edit I've used a very naive approach since I wasn't able to find a solution uptill now, I replaced white space from both arrays and then using the resultant boolean array ([True, False, True]) to `filter on the origional array. Below is the code: import numpy.core.defchararray as np_f import numpy as np array_two_wr = np_f.replace(array_two, ' ', '') array_one_wr = np_f.replace(array_one, ' ', '') intersections = array_two[np.in1d(array_two_wr, array_one_wr)] But I am not sure this is the way to go considering the number of elements in array_two
tagged with: python
type: AnsweredQuestion
has title: Match strings from one numpy array to another
linked to: http://stackoverflow.com/q/25114338
accepted answer: http://stackoverflow.com/a/48974339
has comment: http://stackoverflow.com/comment/84832956
type: Question
possible better answer: http://stackoverflow.com/a/48974048
has answer: http://stackoverflow.com/a/48974339
upvote count: 5
linked to: http://stackoverflow.com/q/16474848
tagged with: numpy
answer count: 2
score: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/84834276
favorite count: 0

twisted
tags question: http://stackoverflow.com/q/48913525
tags question: http://stackoverflow.com/q/48951957
tags question: http://stackoverflow.com/q/48825929
tags question: http://stackoverflow.com/q/48954666
tags question: http://stackoverflow.com/q/48856268
tags question: http://stackoverflow.com/q/48806013
type: Tag
tags question: http://stackoverflow.com/q/48843728
tag name: twisted
tags question: http://stackoverflow.com/q/48839120

http://stackoverflow.com/a/48961134
score: 0
has comment: http://stackoverflow.com/comment/84929368
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84929598
has body: Your problem is not really well defined, so you will get a rather generic answer. Numpy provides a lot of functionality for this kind of problem and the operations are vectorised, meaning it is fast in comparison to Python loops. import numpy as np #read csv file a = np.genfromtxt("myfile.csv", delimiter = ",", skip_header = 1) #e.g you have an array like #a = np.arange(16).reshape(4, 4) #sample input #[[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11] # [12 13 14 15]] mirror_sum = a.T + a #sample output #[[ 0 5 10 15] # [ 5 10 15 20] # [10 15 20 25] # [15 20 25 30]] #now flatten the upper triangle all_sums = np.hstack(mirror_sum[i][:i] for i in range(mirror_sum.shape[0])) #sample output #[ 5 10 15 15 20 25] This obviously only works with an input of quadratic shape. You haven't specified, what should happen in any other case, so we don't have to consider this. You also have to adapt np.genfromtxt to your csv file, it provides many parameters to deal with different csv files. Again, the sparse information you provide make a more tailored answer impossible.
type: Answer
accepted answer of: http://stackoverflow.com/q/48960107
answers question: http://stackoverflow.com/q/48960107
has comment: http://stackoverflow.com/comment/85063578
has comment: http://stackoverflow.com/comment/84929644
has comment: http://stackoverflow.com/comment/84929408

http://stackoverflow.com/a/48899647
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84804888
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84804657
has body: Try out this: from functools import reduce finaldf = reduce(lambda left,right: pd.merge(left, right, on='id_no', how='left'), [df1,df2,df3,df4,df5])
answers question: http://stackoverflow.com/q/48899550

http://stackoverflow.com/a/48922383
answers question: http://stackoverflow.com/q/48922296
has comment: http://stackoverflow.com/comment/84860643
has comment: http://stackoverflow.com/comment/84861417
upvote count: 2
has comment: http://stackoverflow.com/comment/84859472
has comment: http://stackoverflow.com/comment/84858061
has comment: http://stackoverflow.com/comment/84858024
has comment: http://stackoverflow.com/comment/84860608
has comment: http://stackoverflow.com/comment/84857943
has body: Use merge with left join and drop_duplicates: df = pd.merge(df1, df2, on='user', how='left').drop_duplicates(['cluster','song']) print (df) user song cluster 0 A 11 1 1 A 22 1 2 B 22 2 3 B 33 2 5 C 33 1 Then aggregate join, but before is necessary convert songs to strings: df = df['song'].astype(str).groupby(df['cluster']).apply(', '.join).reset_index() print (df) cluster song 0 1 11, 22, 33 1 2 22, 33 Or if need lists: df = df.groupby('cluster')['song'].apply(list).reset_index() #same as #df = df['song'].groupby(df['cluster']).apply(list).reset_index() print (df) cluster song 0 1 [11, 22, 33] 1 2 [22, 33] EDIT: df = pd.merge(df1, df2, on='user', how='left').drop_duplicates(['user','song']) df1 = df.pivot('user','song', 'cluster') df3 = df1.isnull().stack().reset_index(name='val') df3 = df3[df3['val']].groupby('user')['song'].apply(list).reindex(df2['user']) print (df3) user A [33] B [11] C [22] D [11] E [22, 33] Name: song, dtype: object
score: 2
has comment: http://stackoverflow.com/comment/84859711
has comment: http://stackoverflow.com/comment/84858007
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84859438
has comment: http://stackoverflow.com/comment/84860530
accepted answer of: http://stackoverflow.com/q/48922296
type: Answer
has comment: http://stackoverflow.com/comment/84857915

http://stackoverflow.com/comment/84629985
type: QuestionComment
comment on: http://stackoverflow.com/q/48812979
type: Comment
has text: @sooaran I got it. When a VM is installed, it installs a software NIC; so I do believe Thomas Weller's duplicate link will help you. You'll need to distinguish the NICs by device ID or MAC address, and then pick the right one. Alternately, you could get all the IP addresses, and filter them by the subnet you expect it to be on.
score: 0

fractions
type: Tag
tags question: http://stackoverflow.com/q/48816327
tag name: fractions

http://stackoverflow.com/comment/84732443
comment on: http://stackoverflow.com/a/48861955
type: AnswerComment
has text: Thank you for updating nicocos answer. For me, his original answer worked very well, where the temp array is based on the sequence length of the mapping array. How does the usage of indices shape improve the code? And what is meant by “advanced indices must have consistent shapes“. Thx
score: 0
type: Comment

http://stackoverflow.com/q/48847665
has body: I'm currently building a Python script that will pull all Oscar nominated Best Picture movies from the wikipedia page. I've made two different lists for the winners and the nominees. from lxml import etree import requests r = requests.get('https://en.wikipedia.org/wiki/Academy_Award_for_Best_Picture') doc = etree.fromstring(r.text) winners = doc.xpath('//tr[@style="background:#FAEB86"]/td/i/b/a') nominees = doc.xpath('//tr/td/i/a') As you can see, I'm focusing on the last node as that has both the name of the movie. I am able to get all the movies on for each list, but I want to put them in one list together using xpath. I know I could merge the two lists together, but the movies have to be in the order they appear on the wiki page. The main problem comes from the nodes with @style and /b, which both come before /a. I tried putting them together in a single line winners = doc.xpath('//tr[@style="background:#FAEB86" or not(@style="background:#FAEB86")]/td/i[b or not(b)]/a') but I only get the most recent winner (Moonlight) at the beginning of the list, and the rest of the list is just the nominated movies. Is it possible to put my two list together in a single statement, or will I have to write a work around that puts the movies in the correct oder?
has answer: http://stackoverflow.com/a/48847716
tagged with: python
type: AnsweredQuestion
tagged with: wikipedia
type: Question
has title: xpath - How do I get a node that may or may not contain a parent node
score: 0
accepted answer: http://stackoverflow.com/a/48847716
tagged with: http://stackoverflow.com/tag/html
answer count: 1
tagged with: movie
tagged with: xpath

http://stackoverflow.com/a/48864831
score: 0
answers question: http://stackoverflow.com/q/48864578
type: Answer
has body: In Python dict is and unordered structure. There is no specific order in a dict. So the only way I see is to use a list of fields to be sure you always get them in the same order: import csv d = {'1':1,'2':2,'z':'z'} def fb_catalog_dict(fields_list,dict_object): return [dict_object[f] if f in dict_object else None for f in fields_list] f = open('mycsvfile.csv', 'w',newline='') writer = csv.writer(f) for i in range(10): writer.writerow(get_values_from_dict(['z','1','2'],d)) f.close() P.S> the example is for Python 3.x

http://stackoverflow.com/q/48925097
has title: Impossible to send SIGKILL to supervisord
type: Question
tagged with: docker
score: 0
tagged with: supervisord
type: UnansweredQuestion
has body: Supervisord is run in a docker container. It spawns several processes. Its configuration is below: [supervisord] nodaemon = true [group:maria-as] programs=p1,p2 [program:p1] priority = 1 command = bash ./launcher.sh stopasgroup=true killasgroup=true autorestart=false [program:p2] priority = 1 command = bash ./launcher2.sh stopasgroup=true killasgroup=true autorestart=false [eventlistener:subprocess_stop] events=PROCESS_STATE_EXITED,PROCESS_STATE_FATAL,PROCESS_STATE_STOPPED,PROCESS_STATE_BACKOFF command=/kill.py My goal is to kill supervisord with all its subprocesses once one of the subprocesses goes down. So event listener was implemented which sends SIGKILL to supervisord. kill.py code is below: #!/usr/bin/env python import os import signal def write_stdout(s): sys.stdout.write(s) sys.stdout.flush() def write_stderr(s): sys.stderr.write(s) sys.stderr.flush() def main(): while 1: write_stdout('READY\n') try: print time.time() os.kill(1, signal.SIGKILL) print time.time() except Exception as e: write_stderr('Could not kill supervisor: ' + e.strerror + '\n') write_stdout('RESULT 2\nOK') if __name__ == '__main__': main() But nothing happens once one of the subprocesses goes down. What is more interesting is that running kill -9 1 inside the container has no effect either. kill -9 -1 causes the container to go down, but it takes several seconds. How to send SIGKILL to supervisord so that the container would stop immediately and what's the reason for such a behavior?
tagged with: python
answer count: 0
has comment: http://stackoverflow.com/comment/84861730
tagged with: process
has comment: http://stackoverflow.com/comment/85104840

http://stackoverflow.com/q/48932965
has title: Python unable to loop/search for existing JSON entry
answer count: 1
tagged with: python-2.7
score: 0
accepted answer: http://stackoverflow.com/a/48939082
tagged with: python
has body: Still learning python. I'm building a IPFS hash description master list. Every time I create a new IPFS hash I can then add the hash with a description to this list that I can search at a later date to find the specific hash. I'm also trying to make sure that before I add a new hash that the same existing hash does not already exist in the JSON file. Any help would be greatly appreciated and I can learn how to expand on this in the future. This is the JSON file that I have and will be searching, adding to and deleting from. { "hashlist": [ { "description": "Test Video", "ipfsHash": "QmVZATT8jWoCsNKzy2V3kwBrGXBjuKfifvrE", "url": "" }, { "description": "Cat Photo", "ipfsHash": "QmVqpEomPZBgQ8dU8cpNezxZHG2oc3xQi61P2n", "url": "" }, { "description": "Test Dir", "ipfsHash": "QmYdWbq65R4CdFqWGYnPA7V12bX7hf2zxv64AG", "url": "" } ] }% I can add to this list with new hashes that are created but, I'm unable to search the existing hash list to find a hash or to make sure a new hash is not entered twice. #!/usr/bin/python import json import os data = [] if os.stat("hash.json").st_size != 0 : file = open('hash.json', 'r') data = json.load(file) # print(data) choice = raw_input("What do you want to do? \n a)Add a new IPFS hash \n s)Seach stored hashes \n\n &gt;&gt;") if choice == 'a': # Add a new hash. description = raw_input('Enter hash description: ') ipfsHash = raw_input('Enter IPFS hash: ') entry = {'description': description , 'ipfsHash': ipfsHash} # search existing hash listings here xglobal = 0 for x in data["hashlist"]: if data["hashlist"][xglobal]["ipfsHash"] == ipfsHash: print "Hash already exist!" break else: xglobal += 1 data['hashlist'].append(entry) file = open('hash.json', 'w') json.dump(data, file, sort_keys = True, indent = 4, ensure_ascii = False) file.close() print('IPFS Hash Added.') pass elif choice == 's': # Search the current desciptions. searchTerm = raw_input('Enter search term: ') file = open('hash.json', 'r') data = json.load(file) file.close() # Search…
has answer: http://stackoverflow.com/a/48939082
type: Question
tagged with: ipfs
type: AnsweredQuestion
tagged with: http://stackoverflow.com/tag/json

http://stackoverflow.com/q/48898216
has comment: http://stackoverflow.com/comment/84801874
has comment: http://stackoverflow.com/comment/84801896
answer count: 1
has comment: http://stackoverflow.com/comment/84801968
has comment: http://stackoverflow.com/comment/84801997
score: 0
tagged with: multidimensional-array
tagged with: python
has title: Python - how to convert stringed arrays within arrays to float arrays
has comment: http://stackoverflow.com/comment/84801900
has comment: http://stackoverflow.com/comment/84801947
has answer: http://stackoverflow.com/a/48898341
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84805428
has body: python noob here. i tried to read in from a text file that contain fields of arrays and append to a list but i keep getting error that the array inside the array are string instead of float. from the text file; [81.48, 74.02, 4.03, 23.18, 211359232.0];[0.007, -0.006, -0.082, 0.075, -0.153];[-0.014, 0.025, 0.06, 0.085, 0.014] i read in the text, split it, converted to np.array and append to an array cumulatively but it doesnt seem to work. the array inside the array is a string e.g. ['[82.04, 73.6, 3.7, 24.93, 179081216.0]', '[83.3, 74.0, 3.41, 24.97, 175265792.0]', '[82.94, 74.75, 3.41, 27.62, 177734656.0]' i am trying to convert it to without the ' [[82.04, 73.6, 3.7, 24.93, 179081216.0], [83.3, 74.0, 3.41, 24.97,175265792.0], [82.94, 74.75, 3.41, 27.62, 177734656.0]] import numpy as np f=open('/home/oracle/adpo/result_run_output.txt','r') x=[] for line in f: line=line.rstrip('\n') a = line.split(';') b = np.array(a[2]) x.append(b ultimately is to be used to generate out a correlation matrix. please advise and thanks.
has comment: http://stackoverflow.com/comment/84802507
type: Question
has comment: http://stackoverflow.com/comment/84802022
has comment: http://stackoverflow.com/comment/84802083
has comment: http://stackoverflow.com/comment/84801928

http://stackoverflow.com/a/48815743
has comment: http://stackoverflow.com/comment/84760774
has comment: http://stackoverflow.com/comment/84639231
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84785975
upvote count: 2
has comment: http://stackoverflow.com/comment/84635514
has body: Instead of using subprocess.check_output, you can use subprocess.Popen. This object represents your subprocess, and has stdout and stderr attributes that you can read. If your subprocess only uses stdout, you can probably just call Popen.stdout.readline() in a loop. However, if the subprocess writes to other pipes, you may hit a deadlock (see the documentation for details). In that case, I'd recommend the consume function described at http://stefaanlippens.net/python-asynchronous-subprocess-pipe-reading/ , which safely lets you print stdout and stderr line-by-line as it is output from the subprocess. Alternatively, your approach using subprocess.check_output(['program', '&gt;', 'logfile']) should work if you pass shell=True to the check_output function. The &gt; is a shell directive that isn't recognized if you run it as a standalone command. EDIT: The above won't return any output for your Python program to use. Instead, subprocess.check_output('program | tee logfile', shell=True). If using shell=True, be careful that you have full control over the argument to check_output. For security, never allow any user or network input to be passed to the shell. See this warning for why.
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84636882
has comment: http://stackoverflow.com/comment/84760812
type: Answer
accepted answer of: http://stackoverflow.com/q/48814481
answers question: http://stackoverflow.com/q/48814481

http://stackoverflow.com/comment/84918933
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48955041
has text: Using HDF5. Please add how you want to read your data after writing. For example iterating over the first or the second dimension.
score: 0

http://stackoverflow.com/a/48853090
answers question: http://stackoverflow.com/q/48852716
has body: Yes, you have to build a model including all the layers you want as outputs, this is not automatically done.
score: 2
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48852716
upvote count: 2

http://stackoverflow.com/q/48823609
answer count: 1
favorite count: 0
tagged with: python-module
tagged with: python
has body: I have successfully managed to build and install PySide2 on Python 3.6.4. (default, not Anaconda) on Windows 10 operating system. However shiboken2 has not been installed. How may I install shiboken2? I know that that the code for this module is attached to PySide2 installation files. I suspect that my C++ code which is built as DLL file cannot be imported in Python due to missing shiboken2. However this importing works fine in Anaconda environment. But at the moment I do not want to use Anaconda because there are old versions of 'Qt' (5.6 but I need 5.9.x) and 'PySide2' installed.
has answer: http://stackoverflow.com/a/48824933
accepted answer: http://stackoverflow.com/a/48824933
tagged with: qt
type: AnsweredQuestion
score: 3
upvote count: 3
type: Question
tagged with: pyside
downvote count: 0
has title: PySide 2 installed successfully but not Shiboken 2

http://stackoverflow.com/a/58263567
answers question: http://stackoverflow.com/q/48926384
type: Answer
score: 1
has body: I don't know if this applies to your exact situation, but here is what I have found: There should be a JSON file that defines how the debugger should work. For me, I use VS Code, and I use the Microsoft Python debugger. It uses a file called launch.json, and contains an array called "configurations": "configurations": [ { "name": "Python: Current File", "type": "python", "request": "launch", "program": "${file}", "console": "internalConsole" ] It is missing a key called "cwd", short for "current working directory" (you can read more about it here). If you add it with the value of blank quotes "", then when Python searches for a file without a specified path, it will search within the same folder. Showing the last few lines of what that looks like: "program": "${file}", "console": "internalConsole", "cwd": "" ] For more general advice, your debugger, or whatever else is running your Python file, needs to have its working directory correctly defined. I realize the post is nineteen months old at some point, but I hope this helps someone!
upvote count: 1
downvote count: 0

http://stackoverflow.com/a/48813868
downvote count: 0
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84644652
answers question: http://stackoverflow.com/q/48812282
has body: try this: for con_id in con_ids: for news_id in range(2,10): print(news_id) print("(//div[@id='"+con_id+"']/table/tbody/tr)["+str(news_id)+"]") headline = driver.find_element_by_xpath("(//div[@id='"+con_id+"']/table/tbody/tr)["+str(news_id)+"]") value = headline.find_element_by_xpath(".//td[2]/a") print(value.get_attribute("innerText").encode('utf-8')) I am able to get the headlines with above code
has comment: http://stackoverflow.com/comment/84634431
has comment: http://stackoverflow.com/comment/84654678

http://stackoverflow.com/q/48936082
tagged with: django
upvote count: 1
has answer: http://stackoverflow.com/a/59231307
has answer: http://stackoverflow.com/a/48937003
type: UnansweredQuestion
has title: virtualenv - ModuleNotFoundError: No module named 'django'?
downvote count: 0
has answer: http://stackoverflow.com/a/48942586
score: 1
favorite count: 0
tagged with: linux
type: Question
tagged with: python
has body: New to linux, I have install django in virtualenv, but i am not able to import django. Is there any variable path i need to set ? (virs) akash@akash-Inspiron-3542:/usr/virs/bin$ django-admin --version 1.11.10 (virs) akash@akash-Inspiron-3542:/usr/virs/bin$ python Python 3.6.4 (default, Jan 28 2018, 17:52:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import django Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ModuleNotFoundError: No module named 'django'
answer count: 3

http://stackoverflow.com/q/48892020
has title: Trying to concatenate a string with values of certain list indecies
favorite count: 0
score: -4
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84789595
possible better answer: http://stackoverflow.com/a/48892098
has answer: http://stackoverflow.com/a/48892098
has answer: http://stackoverflow.com/a/48895511
has comment: http://stackoverflow.com/comment/84867624
type: Question
linked to: http://stackoverflow.com/q/11146190
downvote count: 4
answer count: 2
upvote count: 0
has comment: http://stackoverflow.com/comment/84917535
has comment: http://stackoverflow.com/comment/84789720
has comment: http://stackoverflow.com/comment/84789515
linked to: http://stackoverflow.com/q/11194110
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48895511
has comment: http://stackoverflow.com/comment/84789599
has body: I am working on a self project of a 'poker style' game, and I have ran into an error where I am needing to display the player's hand to the player, and to do this I have the players stored in a list, as well as their hands, and I am trying to concatenate the two by writing something along the lines of: print ('%s hand is: %s' % str(players[0]), str(hands[0,2])) ^ # edit: I have realized I was pulling from an incorrect source, modifying threw a new error I will detail below. # player[] being the list of players # and hands[] being the list of values pulled to represent cards The error that I am getting when approaching this line is: Traceback (most recent call last): File "C:/.../poker.py", line 78, in &lt;module&gt; poker() File "C:/.../poker.py", line 73, in poker print ('%s hand is: %s' % str(player[0]), str(hands[0,2])) TypeError: 'int' object has no attribute '__getitem__' now even though I can understand the context of what the error is throwing, I haven't even started to look into modules and the __init__(): style of python, and therefore I can't come close to understanding the issue. If anyone knows what I could do from here I would really appreciate any help. Thanks! EDIT As requested, I am adding in the contents of the players and hands lists: players begins as an empty set, players = [], and is appended by the values that the user passes as names for input, players 1-x. hands begins as an empty set, hands = [], and is appended by the different 'cards' that are delt. Here are the code for these: # def number of players first player_amt = int(raw_input('How many players?: ')) # initialize player number variable player = 1 # create a list for players to be stored in players = [] # loop logic: to pull player names and assign a player number # for as many players as specified above! while player &lt;= player_amt: # gather player names player_name = raw_input('Enter player number %s\'s name: ' % player) # adding players to the list players.append(player_name) # …

http://stackoverflow.com/q/48889639
score: 1
tagged with: netcdf
has answer: http://stackoverflow.com/a/48895682
accepted answer: http://stackoverflow.com/a/48895682
type: Question
has title: How do I read dates into a netcdf4 variable?
has body: I'm trying to put dates into a netcdf4 variable using Python. I made an array mom, which contains 30 times a date in the form YYYY/MM/DD;hh:mm:ss. It has to be this format. The script works and does not give any errors, but when I look at the data in the netcdf file, part_starttime= "222222222222222222222222222222"; (so 30 times 2) is what's really in the variable. How do I get my dates in there instead of the twos? import netCDF4 as nc4 import numpy as np lon= np.loadtxt('Longitude_Sea_30.txt')#latitude lat = np.loadtxt('Latitude_Sea_30.txt')#longitude z = np.tile(1,30)#depth tijd=np.tile(1,30)#time Part = np.tile(3,30) llon=len(lon) llat=len(lat) lz=len(z) ltijd=len(tijd) lPart=len(Part) ntime=1 nparticles=30 mom=np.tile("2013/04/22;00:00:00",30) #create netcdf4 file f = nc4.Dataset('Stack2.nc','w', format='NETCDF4') #create group Jellygrp = f.createGroup('Jelly') #Define dimensions Jellygrp.createDimension('time',None)# Jellygrp.createDimension('tlendim', 23) #time Jellygrp.createDimension('Y009', lPart) Jellygrp.createDimension('X006', llon) #lon Jellygrp.createDimension('X007', llat) #lat Jellygrp.createDimension('X008', lz) #depth #define arrays part_xpos= np.zeros((ntime,nparticles)) part_ypos= np.zeros((ntime,nparticles)) part_zpos= np.zeros((ntime,nparticles)) part_starttime= np.zeros((ntime,nparticles)) #create variables time = Jellygrp.createVariable('time', 'S1', ('time','tlendim')) part_xpos=Jellygrp.createVariable('part_xpos', 'd', ('time','X006')) part_ypos=Jellygrp.createVariable('part_ypos','d',('time','X007')) part_zpos=Jellygrp.createVariable('part_zpos','d',('time','X008')) part_starttime=Jellygrp.createVariable('part_starttime','S1', ('time','Y009')) #Passing data into variables part_xpos[0,:] =lon[:] part_ypos[0,:] =lat[:] part_zpos[0,:] = z[:] part_starttime[0,:] = mom[:] print(f.groups['Jelly']) f.close()
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84787076
downvote count: 0

http://stackoverflow.com/comment/84900569
has text: Is there a way to fetch that from existing project?
comment on: http://stackoverflow.com/q/48946338
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48860586
answer count: 5
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48876298
has title: How to upload and save large data to Google Colaboratory from local drive?
has answer: http://stackoverflow.com/a/49487192
has answer: http://stackoverflow.com/a/48869643
type: Question
has answer: http://stackoverflow.com/a/49699957
downvote count: 0
tagged with: google-colaboratory
score: 6
linked to: http://stackoverflow.com/q/46986398
tagged with: deep-learning
has body: I have downloaded large image training data as zip from this Kaggle link https://www.kaggle.com/c/yelp-restaurant-photo-classification/data How do I efficiently achieve the following? Create a project folder in Google Colaboratory Upload zip file to project folder unzip the files Thanks EDIT: I tried the below code but its crashing for my large zip file. Is there a better/efficient way to do this where I can just specify the location of the file in local drive? from google.colab import files uploaded = files.upload() for fn in uploaded.keys(): print('User uploaded file "{name}" with length {length} bytes'.format( name=fn, length=len(uploaded[fn])))
tagged with: python
upvote count: 6
linked to: http://stackoverflow.com/q/47320052
favorite count: 0
tagged with: jupyter-notebook
has answer: http://stackoverflow.com/a/49270815
tagged with: google-drive-api

http://stackoverflow.com/comment/84620363
type: AnswerComment
comment on: http://stackoverflow.com/a/48805186
has text: you can speed it up by avoiding the lookup of the `append` method using `append = list_b.append`
score: 0
type: Comment

peewee
tag name: peewee
type: Tag
tags question: http://stackoverflow.com/q/48812379
tags question: http://stackoverflow.com/q/48856291
tags question: http://stackoverflow.com/q/48910746

http://stackoverflow.com/q/48884495
tagged with: python
tagged with: http://stackoverflow.com/tag/jpeg
has title: What is the simplest way to extract the jpeg preview from a Nikon raw file with python?
type: Question
linked to: http://stackoverflow.com/q/2422050
has comment: http://stackoverflow.com/comment/84773519
has body: I'm looking for the simplest way to extract the embedded jpg preview from a Nikon raw file (.nef) in Python 2.7. How should I do this?
has answer: http://stackoverflow.com/a/48884714
tagged with: image
score: 0
answer count: 1
type: UnansweredQuestion

http://stackoverflow.com/comment/84887328
has text: @karlphillip it's generated. Just run the program in your own computer.
type: Comment
comment on: http://stackoverflow.com/q/48862451
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84644071
type: Comment
type: QuestionComment
has text: @IceArdor Yes it is. It's defined in the global scope which means it's a global variable. The `global` keyword is only relevant in a local scope. See: https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python
comment on: http://stackoverflow.com/q/48820118
score: 0

http://stackoverflow.com/q/48816873
type: Question
answer count: 2
has title: Intermediate layer makes tensorflow optimizer to stop working
tagged with: python
has answer: http://stackoverflow.com/a/60962860
tagged with: autoencoder
score: 12
tagged with: machine-learning
has body: This graph trains a simple signal identity encoder, and in fact shows that the weights are being evolved by the optimizer: import tensorflow as tf import numpy as np initia = tf.random_normal_initializer(0, 1e-3) DEPTH_1 = 16 OUT_DEPTH = 1 I = tf.placeholder(tf.float32, shape=[None,1], name='I') # input W = tf.get_variable('W', shape=[1,DEPTH_1], initializer=initia, dtype=tf.float32, trainable=True) # weights b = tf.get_variable('b', shape=[DEPTH_1], initializer=initia, dtype=tf.float32, trainable=True) # biases O = tf.nn.relu(tf.matmul(I, W) + b, name='O') # activation / output #W1 = tf.get_variable('W1', shape=[DEPTH_1,DEPTH_1], initializer=initia, dtype=tf.float32) # weights #b1 = tf.get_variable('b1', shape=[DEPTH_1], initializer=initia, dtype=tf.float32) # biases #O1 = tf.nn.relu(tf.matmul(O, W1) + b1, name='O1') W2 = tf.get_variable('W2', shape=[DEPTH_1,OUT_DEPTH], initializer=initia, dtype=tf.float32) # weights b2 = tf.get_variable('b2', shape=[OUT_DEPTH], initializer=initia, dtype=tf.float32) # biases O2 = tf.matmul(O, W2) + b2 O2_0 = tf.gather_nd(O2, [[0,0]]) estimate0 = 2.0*O2_0 eval_inp = tf.gather_nd(I,[[0,0]]) k = 1e-5 L = 5.0 distance = tf.reduce_sum( tf.square( eval_inp - estimate0 ) ) opt = tf.train.GradientDescentOptimizer(1e-3) grads_and_vars = opt.compute_gradients(distance, [W, b, #W1, b1, W2, b2]) clipped_grads_and_vars = [(tf.clip_by_value(g, -4.5, 4.5), v) for g, v in grads_and_vars] train_op = opt.apply_gradients(clipped_grads_and_vars) saver = tf.train.Saver() init_op = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) for i in range(10000): print sess.run([train_op, I, W, distance], feed_dict={ I: 2.0*np.random.rand(1,1) - 1.0}) for i in range(10): print sess.run([eval_inp, W, estimate0], feed_dict={ I: 2.0*np.random.rand(1,1) - 1.0}) However, when I uncomment the intermediate hidden layer and train the resulting network, I see that the weights are not evolving anymore: import tensorflow as tf import numpy as np…
tagged with: tensorflow
possible better answer: http://stackoverflow.com/a/60962860
has comment: http://stackoverflow.com/comment/84839959
upvote count: 12
has comment: http://stackoverflow.com/comment/84840355
tagged with: deep-learning
has answer: http://stackoverflow.com/a/48928133
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85064210
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48928133

http://stackoverflow.com/q/48884147
tagged with: python
tagged with: list
has comment: http://stackoverflow.com/comment/84772984
upvote count: 1
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84773014
has comment: http://stackoverflow.com/comment/84772919
has comment: http://stackoverflow.com/comment/84772714
tagged with: comparison
has title: How many elts from a list are less distant than a value from N others lists
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48888488
has answer: http://stackoverflow.com/a/48884702
favorite count: 0
has body: So I'll try to explain my problem with an example. L1 = [0, 5, 10, 15, 20, 25] L2 = [1, 2, 3, 4, 5, 6, 7] L3 = [1.1, 9.5, 12, 14, 80, 90, 100] L4 = [16, 25, 30, 40, 50, 150, 200, 250] L5 = [15, 16, 18, 19, 29, 300, 350, 500, 600] If I take one element from L1, I want to know if there are less than 2 other elements from L2+L3+L4+L5 that are at a distance &lt; value (let's say 1.5). So for L1[0] = 0 : L2[0] and L3[0] are at a distance &lt; 1.5. So it's OK. For L1[3] = 15: L3[3], L4[0], L5[0] and L5[1] are at a distance &lt; 1.5 => Not Ok Same for L2 with L1+L3+L4+L5, etc... I need to check that there isn't any element close to more than 2 others. I'm looking for a fast way of checking this condition. My current approach uses list comprehension, i quite long, and needs one function for comparing 2 lists, one for comparing 3, ... def duo_overlap(t1, t2): id_t1 = [x for x in range(len(t1)) for y in range(len(t2)) if abs(t1[x] - t2[y]) &lt; 0.3] id_t2 = [y for y in range(len(t2)) for x in range(len(t1)) if abs(t2[y] - t1[x]) &lt; 0.3] return id_t1, id_t2 Thanks for the suggestion :) EDIT: Timeline list as I use them: F20 = [0.0, 50.0, 100.0] F40 = [0.0, 25.0, 50.0, 75.0, 100.0, 125.0] F50 = [0.0, 20.0, 40.0, 60.0, 80.0, 100.0, 120.0, 140.0] F100 = [0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0, 110.0, 120.0, 130.0, 140.0] F125 = [0.0, 8.0, 16.0, 24.0, 32.0, 40.0, 48.0, 56.0, 64.0, 72.0, 80.0, 88.0, 96.0, 104.0, 112.0, 120.0, 128.0, 136.0, 144.0] Function to design one: def time_builder(f, t0=0, tf=150): return list(np.round(np.arange(t0, tf, 1/f*1000),3))
type: UnansweredQuestion

http://stackoverflow.com/comment/85027194
comment on: http://stackoverflow.com/a/48955902
score: 0
type: AnswerComment
has text: Stack trace are the lines printed above the error, it shoud start in your code, and end somewere in tensorflow.
type: Comment

http://stackoverflow.com/comment/84679048
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48837099
has text: content[i*10000:(i*10000)+10], can you expalin for us what does this statement do?
score: 0

http://stackoverflow.com/comment/84867947
type: QuestionComment
comment on: http://stackoverflow.com/q/48928672
has text: The website has a couple of gaps that need filling in order to extract data. I need the exports from a specific group of countries (the 55 african ones). The website, nevertheless, doesn't let me download it all, because the file would be too big. Therefore, I have to download the exports from each of the countries one by one. What I'd like to automate is this process. My idea was to create an array with the africa countries and loop it, while extracting the data, compiling and reporting it in a way that suits me.
score: 0
type: Comment

http://stackoverflow.com/q/48944296
has comment: http://stackoverflow.com/comment/102601891
has comment: http://stackoverflow.com/comment/113062110
tagged with: http://stackoverflow.com/tag/r
has comment: http://stackoverflow.com/comment/102666467
has comment: http://stackoverflow.com/comment/102615756
score: 14
has comment: http://stackoverflow.com/comment/107742921
downvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/102549534
has body: I am using the officer and rvg packages to get plots from R into MS PowerPoint as editable vector graphics. Reproducible example below. I am looking for a way to implement an equivalent solution with python, preferably using matplotlib. The critical part is not the creation of slides from the IDE but rather the editable vector graphics part, i.e. plots should end up in PowerPoint as grouped objects comprised of a range of simple powerpoint geometries such as lines, squares, and text fields. R example: library(tidyverse) library(officer) library(rvg) # Get some data and make a plot ggp &lt;- diamonds %&gt;% group_by(clarity) %&gt;% summarise(price = mean(price)) %&gt;% ggplot(aes(x = clarity, y = price, fill = clarity)) + geom_bar(stat = 'identity', colour = 'black') # Create a new powerpoint document doc &lt;- read_pptx() doc &lt;- add_slide(doc, 'Title and Content', 'Office Theme') # Add the plot doc &lt;- ph_with_vg(doc, ggobj = ggp, type = 'body') # Write the document to a file print(doc, target = 'plots.pptx') The resulting chart is completely editable:
favorite count: 0
tagged with: python
has answer: http://stackoverflow.com/a/58491770
tagged with: plot
has comment: http://stackoverflow.com/comment/113027805
type: AnsweredQuestion
upvote count: 14
has title: Editable plots in PowerPoint from python: equivalent of officer and rvg
tagged with: powerpoint
type: Question
tagged with: graphics
accepted answer: http://stackoverflow.com/a/58491770

http://stackoverflow.com/comment/84617686
comment on: http://stackoverflow.com/a/48807392
type: AnswerComment
type: Comment
has text: Or without squeezing you can just pass the specific row. `np.add.at(a[0], idx, vals)`.
score: 1

http://stackoverflow.com/comment/85046236
type: QuestionComment
comment on: http://stackoverflow.com/q/48821582
has text: @ben Your analogy is invalid in this case, a learning algorithm actually *learns* from the training data, you change the training data and what is learned changes. Now you add changes to the test set, which add more variability, so your results cannot be compared. If you cannot understand this then I recommend you to take a look at good scientific practices in Machine Learning.
score: 0
type: Comment

reverse
tags question: http://stackoverflow.com/q/48856477
tag name: reverse
type: Tag
tags question: http://stackoverflow.com/q/48952467
tags question: http://stackoverflow.com/q/48807818

http://stackoverflow.com/q/48829584
has answer: http://stackoverflow.com/a/48829722
has title: Python program to delete a specific line in a text file
downvote count: 0
has answer: http://stackoverflow.com/a/48829718
has comment: http://stackoverflow.com/comment/129364132
favorite count: 0
linked to: http://stackoverflow.com/q/4710067
upvote count: 8
accepted answer: http://stackoverflow.com/a/48829718
tagged with: python
duplicate of: http://stackoverflow.com/q/4710067
answer count: 4
score: 8
tagged with: text-files
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48829785
type: Question
possible better answer: http://stackoverflow.com/a/48829798
has answer: http://stackoverflow.com/a/48829798
has body: I have a text file Thailand_Rectangle2_National Parks.txt with the following lines. 1 2 3 4 5 dy 0.5965 7 Now, I want to delete the 6th line in this text file. For that, I am using the following python code. f = open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","r") lines = f.readlines() So, I saved all the lines of this text file in 'lines'. line6 = lines[5] t = line6[:2] f.close() So, now, I have 't' = "dy" . Now, if t == "dy": f = open("C:/Users/Sreeraj/Desktop/Thailand_Rectangle2_National Parks.txt","w") for line in lines: if lines[5] != line6: f.write(line) f.close() So, if the condition 't' = "dy" satisfies, then I will open this text file for writing and I will print all the lines except line6 (which means line6 is deleted from this text file). Unfortunately, I am getting the lines in this text file as blank, which means no lines are printed as outputs. But, I want the lines in the text file as given below. 1 2 3 4 5 7 How can I solve this issue ? I want to use only Python programming to solve this issue; since this is a small task of a major work.

http://stackoverflow.com/q/48941381
linked to: http://stackoverflow.com/q/280243
has body: I need to make a linked list and the constructor has these requirements: init(self, head) • The constructor. We’ll have 3 attributes: head, tail, and count. • Make it so we can pass a reference to a node to create an OurLinkedList. • This means that we can by default create an empty list (nothing is passed to the constructor), OR start with an arbitrarily large linked structure (a reference to a node is passed to the constructor). im having trouble understanding how and when to make objects in my code this is what i have so far: def __init__(self, head): self.head= head a= OurLinkedList(self.head) curNode= self.head self.count= 0 while curNode is not None: self.count += 1 curNode= curNode.next self.tail= curNode and I get RecursionError: maximum recursion depth exceeded while calling a Python object
tagged with: python
has comment: http://stackoverflow.com/comment/84890076
has comment: http://stackoverflow.com/comment/84891128
tagged with: linked-list
answer count: 0
type: UnansweredQuestion
score: 0
tagged with: nodes
type: Question
tagged with: recursion
has title: Linked List Implementation python

http://stackoverflow.com/a/48828894
answers question: http://stackoverflow.com/q/48827688
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84668671
has comment: http://stackoverflow.com/comment/84663202
type: Answer
accepted answer of: http://stackoverflow.com/q/48827688
upvote count: 2
score: 2
has body: If I needed my output file to be sorted (I will assume you have a valid reason to want this), I'd probably write a custom exporter. This is how Scrapy's built-in JsonItemExporter is implemented. With a few simple changes, you can modify it to add the items to a list in export_item(), and then sort the items and write out the file in finish_exporting(). Since you're only scraping a few hundred items, the downsides of storing a list of them and not writing to a file until the crawl is done shouldn't be a problem to you.

http://stackoverflow.com/a/48853268
answers question: http://stackoverflow.com/q/48853213
has body: You can split at a proceeded by a capital letter or the bullet character: import re s = """ Peter went to the gym; he worked out for two hours Kyle ate lunch at Kate's house. Kyle went home at 9. Some other sentence here •Here's a bulleted line """ new_list = filter(None, re.split(' (?=•)| (?=[A-Z])', s)) Output: ['Peter went to the gym; he worked out for two hours ', "Kyle ate lunch at Kate's house. Kyle went home at 9. ", 'Some other sentence here', "•Here's a bulleted line "] Or, without using the symbol for the bullet character: new_list = filter(None, re.split(' (?=•)| (?=[A-Z])', s))
has comment: http://stackoverflow.com/comment/84710541
type: Answer
upvote count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84710015
score: 1

http://stackoverflow.com/comment/84631588
score: 0
has text: @L3viathan is right, and should probably make the comment into an answer. :)
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48813957

http://stackoverflow.com/comment/84931905
score: 0
type: Comment
type: QuestionComment
has text: Sorry, my variable naming isn't great. `state` is an array of the four frames leading up to the currents frame (with index 0 being the current frame). To save on memory, `next_state` is just one frame, which is then added to the four frames in `state` (with the last one cut off) to get the input for the network. The `[0]` is because Keras outputs an array with the shape (1, 9). If I wanted to input more than one state at a time and get multiple outputs, it would give me (2, 9) or (3, 9), etc.
comment on: http://stackoverflow.com/q/48898104

http://stackoverflow.com/q/48895537
upvote count: 1
downvote count: 0
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84799924
tagged with: http://stackoverflow.com/tag/csv
tagged with: python
tagged with: text
has body: I am new to Python. I am trying to transfer data from a text file to a csv file. I have included a short description of the data of my text file and csv file. Can someone point me to the right direction of what to read up to get this done? **Input Text file** 01/20/18 12:19:35# TARGET_CENTER_COLUMN=0 TARGET_CENTER_ROW=0 TARGET_COLUMN=0 BASELINE_AVERAGE=0 # 01/21/18 12:19:35# TARGET_CENTER_COLUMN=0 TARGET_CENTER_ROW=13 TARGET_COLUMN=13 BASELINE_AVERAGE=26 # 01/23/18 12:19:36# TARGET_COLUMN=340 TARGET_CENTER_COLUMN=223 TARGET_CENTER_ROW=3608, 3609, 3610 BASELINE_AVERAGE=28 # 01/24/18 12:19:37# TARGET_CENTER_COLUMN=224 TARGET_CENTER_ROW=388 TARGET_COLUMN=348 BASELINE_AVERAGE=26 # 01/25/18 12:19:37# TARGET_CENTER_COLUMN=224 TARGET_CENTER_ROW=388 TARGET_COLUMN=348 BASELINE_AVERAGE=26 # 01/27/18 12:19:37# TARGET_CENTER_COLUMN=223 TARGET_COLUMN=3444 TARGET_CENTER_ROW=354 BASELINE_AVERAGE=25 # **Output CSV file** Date,Time,BASELINE_AVERAGE,TARGET_CENTER_COLUMN,TARGET_CENTER_ROW,TARGET_COLUMN 01/20/18,9:37:16 PM,0,0,0,0 01/21/18,9:37:16 PM,26,0,13,13 01/23/18,9:37:16 PM,28,223,3608,340 0,0,3609,0 0,0,3610,0 01/24/18,9:37:16 PM,26,224,388,348 01/25/18,9:37:16 PM,26,224,388,348 01/27/18,9:37:16 PM,25,223,354,344 Reading up online I've been able to implement this. import csv txt_file = r"DebugLog15test.txt" csv_file = r"15test.csv" mylist = ['Date','Time','BASELINE_AVERAGE' ,'TARGET_CENTER_COLUMN', 'TARGET_CENTER_ROW','TARGET_COLUMN'] in_txt = csv.reader(open(txt_file, "r")) with open(csv_file, 'w') as myfile: wr = csv.writer(myfile, quoting=csv.QUOTE_ALL) wr.writerow(mylist) Beyond this I was planning to start a for loop and read data till # as this would be 1 row, and then use the delimiter to find each '=' and insert the data into the appropriate location in a row list(do this by comparing the column header with the string prior to the delimiter) and populate the row accordingly. Do you think this approach is correct? Thanks for your help!
type: AnsweredQuestion
score: 1
type: Question
has title: Python - txt to csv
has answer: http://stackoverflow.com/a/48896320
accepted answer: http://stackoverflow.com/a/48896320

http://stackoverflow.com/comment/84837519
score: 0
type: AnswerComment
has text: Yes, this is a dictionary generator expression.
type: Comment
comment on: http://stackoverflow.com/a/48915535

http://stackoverflow.com/comment/84910992
comment on: http://stackoverflow.com/q/48952140
score: 0
type: Comment
type: QuestionComment
has text: You could use the Scikit-Learn [One hot encoder](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.OneHotEncoder.html)

http://stackoverflow.com/q/48902504
answer count: 0
downvote count: 0
score: 1
has title: Loading from pickle slow/fails
type: Question
has body: I'm using Gauss-Legendre integration to calculate an integral. To get the necessary roots of the Legendre polynomials, I have followed steps outlined here and it works. To save me the time of generating the roots for high order polynomials, I have added a try:, except: routine to store and load roots generated on prior runs. However, above some number of roots this becomes very slow. For 20 roots, the loading delay is almost non-existent, for 25 it is noticable (on the order of several seconds) and for 30 roots it does not progress at all. (CPU at 100%, but nothing put out to console, no error message.) Why is that and what can I do better? After all, it should just read a list of floats from a file. import math import pickle def Legendre(position, order): # calculates the value of the Legendre polynomial of any order at a position # has to be a separate function because of recursion if order == 0: return 1.0 elif order == 1: return position else: return ((2 * order - 1.0) * position * Legendre(position, order - 1) - (order - 1) * Legendre(position, order - 2)) / float( order) def Legendrederivative(position, order): # calculates the value of the derivative of the Legendre polynomial of any order at a position if order == 0: return 0.0 elif order == 1: return 1.0 else: return order / (math.pow(position, 2) - 1) * ( position * Legendre(position, order) - Legendre(position, order - 1)) def Legendreroots(order, tolerance=10): try: with open('rootsfile' + str(order) + 't' + str(tolerance) + '.txt', 'r+') as filecontents: roots = pickle.load(filecontents) return roots except: if order == 0 or order == 1: raise ValueError('No roots possible') roots = [] for counter in range(1, order + 1): x = math.cos(math.pi * (counter - 0.25) / (float(order) + 0.5)) iterationcounter = 0 dx = 10 * 10 ^ (-tolerance) while (abs(dx) &gt; tolerance) and iterationcounter &lt; 1000: dx = - Legendre(x, order) / Legendrederivative(x, order) x += dx iterationcounter += 1 if iterationcounter == 99…
tagged with: python-2.7
upvote count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: pickle
tagged with: python

http://stackoverflow.com/q/48895902
type: UnansweredQuestion
has title: OpenCV color detection without knowing colors a priori
tagged with: python
has comment: http://stackoverflow.com/comment/84808403
tagged with: opencv
tagged with: image-processing
has answer: http://stackoverflow.com/a/48898499
tagged with: image
has answer: http://stackoverflow.com/a/48899240
type: Question
has body: I'd like to draw bounding boxes around some color blobs, whose color I don't know beforehand. The images look like this: every color in the scene represents a different object. I already tried findContours on the grayscale version of the image, however the contours obtained that way encompass multiple objects if they overlap. My wish would be to obtain the contours for individual objects, or multiple contours for an object if it is divided by another object in the scene. Is there a way to achieve this in OpenCV? Thank you very much for your attention and time! EDIT: as suggested, here my code img = cv2.imread(img_path) imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) kernel = np.ones((5,5), np.uint8) im2, contours, hierarchy = cv2.findContours(imgray, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) bboxes = [] for c in contours: x, y, w, h = cv2.boundingRect(c) M = cv2.moments(c) if M["m00"]: cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) area = cv2.contourArea(c) if area &gt;= 25: colorHash = img[cy, cx] bboxes.append((Box(Point(x, y), Point(x+w, y+h)), colorHash, area)) cv2.drawContours(img, [c], -1, (0, 0, 255), 1) cv2.imshow("Image", img) cv2.waitKey(0) return bboxes, contours Here an image of the problem I'm trying to solve (marked blue, contours are red, the objects should have individual contours)
has answer: http://stackoverflow.com/a/48901163
score: 0
answer count: 3

http://stackoverflow.com/comment/84822703
comment on: http://stackoverflow.com/q/48898300
type: QuestionComment
type: Comment
has text: What have you tried so far? How do you wish to "automate" it -- Python, shell, powershell, etc? Have you been able to do it successfully via the console, and now it's just a matter of automating it? Feel free to Edit your question to provide more details.
score: 0

http://stackoverflow.com/comment/84803335
type: QuestionComment
comment on: http://stackoverflow.com/q/48881067
has text: @AhmedS **"topic"** of the paragraph/document. Won't I need the subject of every sentence to know the topic of the document?
score: 0
type: Comment

http://stackoverflow.com/a/49005067
type: AcceptedAnswer
downvote count: 0
has body: There is a VERY simple solution for that. Use the python-social-auth pipelines. The way this thing work is just like middleware, you can add in your settings page to the SOCIAL_AUTH_PIPELINE section a function that will run every time the user is authenticated using the social_django. An example: In your settings page, add the following: SOCIAL_AUTH_PIPELINE = ( 'social.pipeline.social_auth.social_details', 'social.pipeline.social_auth.social_uid', 'social.pipeline.social_auth.auth_allowed', 'social.pipeline.social_auth.social_user', 'social.pipeline.user.get_username', 'social.pipeline.user.create_user', 'social.pipeline.social_auth.associate_user', 'social.pipeline.social_auth.load_extra_data', 'social.pipeline.user.user_details', 'home.pipeline.save_profile', ) Look at home.pipeline.save_profile, this is a new pipeline in home.pipeline file. (Change it into your own user module folder) In there (home.pipeline) add the following: from .models import UserProfile def save_profile(backend, user, response, *args, **kwargs): if backend.name == "facebook": UserProfile.objects.create( user=user, photo_url=response['user']['picture'] ) This is an example. You need to change it for get/update in case the user already logged in. Also, try and play with the response argument, there might be different data you can use there. One last thing, make sure you add the picture attribute into your settings: SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id, name, email, picture' } http://python-social-auth.readthedocs.io/en/latest/backends/facebook.html https://godjango.com/122-custom-python-social-auth-pipeline/ https://github.com/python-social-auth/social-app-django
has comment: http://stackoverflow.com/comment/85027936
type: Answer
upvote count: 6
answers question: http://stackoverflow.com/q/48857762
accepted answer of: http://stackoverflow.com/q/48857762
score: 6

http://stackoverflow.com/q/48833999
answer count: 1
has comment: http://stackoverflow.com/comment/84672566
favorite count: 0
has body: I currently have a file that's being read and making every line into a list. The file looks like this: A 11 1 B 12 2 C 11 2 It's easy to make a list using split() ['A', '11', '1'] But how do I make a list that contains both chars and ints such that I get this below: ['A', 11, 1] would be grateful for some help!
has comment: http://stackoverflow.com/comment/84672767
has answer: http://stackoverflow.com/a/48834055
tagged with: python
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84673114
has comment: http://stackoverflow.com/comment/84672399
has title: PYTHON: how to make a list with both chars and ints?
score: 1
type: Question
linked to: http://stackoverflow.com/q/1265665
upvote count: 1

http://stackoverflow.com/comment/133590197
has text: In 2023 simply installing liblzo2-dev via `apt-get install -y liblzo2-dev` also works in ubuntu (18.04), so I think this approach is unnecessary. (See https://packages.ubuntu.com/bionic/liblzo2-dev)
comment on: http://stackoverflow.com/a/49018566
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84810458
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48901509
has text: It depends of your inputs. What kind of objects are your inputs? Are you working with sequence of length 15 of scalars?
type: AnswerComment

http://stackoverflow.com/a/48910200
answers question: http://stackoverflow.com/q/48909056
type: Answer
has body: You can also do it like this: values = [0, 1, 2, 3, 4, 5, 351, 0, 1, 2, 3, 4, 5, 6, 750, 0, 1, 2, 3, 4, 5, 559] # Find all indices whose element is 0. indices = [index for index, value in enumerate(values) if value==0] + [len(values)] # Split the list accordingly values = [values[indices[i]:indices[i+1]] for i in range(len(indices)-1)] print(values) Output: [[0, 1, 2, 3, 4, 5, 351], [0, 1, 2, 3, 4, 5, 6, 750], [0, 1, 2, 3, 4, 5, 559]]
score: 0

http://stackoverflow.com/a/48870740
upvote count: 2
type: Answer
has body: Your query does not work because you have not specified which Chamber you want to get the backwards relation for. However, this is not the right approach. Presumably you want the ChamberProperty so you can list them against each Chamber in the template. So, you should follow the relationship there in the template - there's no need to query ChamberProperty separately in the view at all. {% for chamber in chamber_list %} {{ chamber.chamber_name }} {% for property in chamber.chamberproperty_set.all %} {{ property.property_name }} : {{ property.property_value }} {% endfor %} {% endfor %}
has comment: http://stackoverflow.com/comment/84745568
downvote count: 0
score: 2
answers question: http://stackoverflow.com/q/48870584

http://stackoverflow.com/comment/84794533
score: 1
comment on: http://stackoverflow.com/a/48894210
type: AnswerComment
type: Comment
has text: Used up way to many words there, I like your idea of making up my own IP address, it's not at all half bad actually! I can't stress how clever this workaround is. All be it not what I was looking for at all haha. But it does solve the problem in a rather unique way. I already construct Ethernet, IP and TCP headers. Along side with ARP/ICMP/OSPF support to name a few. I will all of a sudden need to support DHCP data as well, but that's manageable haha. I'll try my original train of thought first and see if i can solve it that way, if nothing else - this gets the solve mark!

http://stackoverflow.com/comment/84832476
score: 1
comment on: http://stackoverflow.com/q/48912849
type: Comment
type: QuestionComment
has text: Does `check_password` return true if the password is wrong?? It would seem to me that it's not well named, since to me I would assume "check password" would return true if the password was correct. And if that's the case, that's your issue.

http://stackoverflow.com/q/48878687
upvote count: 4
has title: Using Python to scrape information from a cloudflare site?
has comment: http://stackoverflow.com/comment/84843952
tagged with: python-3.x
type: UnansweredQuestion
score: 3
tagged with: web-crawler
type: Question
tagged with: cloudflare
answer count: 1
has answer: http://stackoverflow.com/a/53597077
favorite count: 0
has comment: http://stackoverflow.com/comment/90520901
downvote count: 1
has body: I work in a marketing firm, and I have several hundred emails I need to compile and sort from a web-page. I have a bit of python knowledge, so often I'll make a simple scraping tool to make life easier, but cloudflare is blocking the email in the source. How can I bypass this? Obviously using an automated tool like this is a lot faster than manually copy and pasting all of the emails. Here's the program I've been testing it with: import requests import urllib from bs4 import BeautifulSoup website = "" r = requests.get(website) soup = BeautifulSoup(r.text,'html.parser') numb = 799 while numb &lt; 800: numb += 1 print(r.status_code) print(soup.prettify()) In the source, this replaces the email: &lt;a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=""&gt;[email;protected]&lt;/a&gt; Is there any way to automate copying and pasting a certain line on the webpage? I've checked the source in a regular browser and it shows the same thing. Thanks for the help.
tagged with: python

http://stackoverflow.com/comment/84657185
type: Comment
has text: this function is only for MNIST dataset. And you need to activate it from the imported object "mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)". And then you can use it like "batch_x , batch_y = mnist.train.next_batch(n)". Where batch_x are the images, batch_y are the labels, and n is the batch size you want to use. Check documentation for details
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48810115

http://stackoverflow.com/q/48809243
tagged with: python
has comment: http://stackoverflow.com/comment/84634017
has comment: http://stackoverflow.com/comment/84622186
has comment: http://stackoverflow.com/comment/84629112
answer count: 0
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/84634022
type: Question
linked to: http://stackoverflow.com/q/6783194
has comment: http://stackoverflow.com/comment/84625349
has body: According this example : link ,I want to implement a thread based small application within a GUI. I have two files TestMain.py and TestManager.py (Worker class), which are connected with each other over sys.path.append('...'). In TestMain.py, I load my GUI, create thread and signal/slot connections, which act on functions in TestManager.py. In TestManager.py I do some calculations and want to visualize them in a QTextEditor at the same time. To do this, I have written following code: TestMain.py sys.path.append('../app/source') from TestManager import * class TestMain(QMainWindow): def __init__(self, parent= None): super(TestMain, self).__init__(parent) self.manager= TestManager() self.thread= QThread() self.manager.moveToThread(self.thread) self.manager.finished.connect(self.thread.quit) self.thread.started.connect(self.manager.first_slot) self.thread.start() self.manager.printFirstSignal.connect(self.print_onTextEdit) self.offlinePushButton.clicked.connect(self.offline_slot) def offline_slot(self): manager.do_some_calc(self) def print_onTextEdit(self, str): self.outputTextEdit.append(str) Manager.py sys.path.append('../app/source') from TestMain import * class TestManager(QObject): #QtCore.QThread finished= pyqtSignal() printFirstSignal= pyqtSignal(str) def __init__(self, parent= None): super(TestManager, self).__init__(parent) def first_slot(self): self.printFirstSignal.emit('TEST') self.finished.emit() def do_some_calc(self): do_someting() TestManager.first_slot("do_some_calc") If I do self.thread.started.connect(self.manager.first_slot) in TestMain and emit the pyqtSignal in function first_slot() in TestManager, then I can update my GUI without any problem. But if I call a slot (e.g do_some_calc()) in TestManager and want to also update the GUI from there, than I get a segmentation fault. Even if I create a separate signal for this function, it does not work. Cause I call this function in TestMain self.offlinePushButton.clicked.connect(self.offline_slot) My que…
has comment: http://stackoverflow.com/comment/84623152
score: 0
has title: Can not emit signal from not threaded slot in pyqt
type: UnansweredQuestion

http://stackoverflow.com/q/48877227
tagged with: scipy
type: Question
answer count: 2
has body: I am trying to import from statsmodels.stats.outliers_influence import variance_inflation_factor This is working fine upto Scipy 0.19. But , with Python 3.6.3 ,it's failing due to unavailability of ss module in Scipy 1.0.0. ~\Anaconda3\lib\site-packages\statsmodels\regression\linear_model.py in &lt;module&gt;() 41 from scipy.linalg import toeplitz 42 from scipy import stats ---&gt; 43 from scipy.stats.stats import ss 44 from scipy import optimize 45 from scipy.stats import chi2 ImportError: cannot import name 'ss' Can anyone please guide me how to do VIF analysis using Scipy1.0.0 ?
downvote count: 0
favorite count: 0
has comment: http://stackoverflow.com/comment/84779540
has answer: http://stackoverflow.com/a/48877765
tagged with: python
has answer: http://stackoverflow.com/a/49089230
accepted answer: http://stackoverflow.com/a/49089230
upvote count: 2
has title: How to calculate VIF in python 3.6 with scipy 1.0.0?
score: 2
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48877765

http://stackoverflow.com/a/48865000
type: Answer
downvote count: 0
upvote count: 8
has body: Change def index(request): return render(request, 'front/index') to def index(request): return render(request, 'front/index.html')
answers question: http://stackoverflow.com/q/48864957
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48864957
score: 8

http://stackoverflow.com/a/48922042
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48922023
type: AcceptedAnswer
type: Answer
has comment: http://stackoverflow.com/comment/84850565
downvote count: 0
has body: I think you want reindex: print (df.reindex(i)) 0 1 11.0 2 22.0 3 NaN 4 44.0 EDIT: If need reindex by unions of indices: i = pd.Index([1,2,3]) df = pd.DataFrame([11,22,44,55],index=[1,2,4,5]) print (df) 0 1 11 2 22 4 44 5 55 print (df.reindex(i.union(df.index))) 0 1 11.0 2 22.0 3 NaN 4 44.0 5 55.0 print (df.reindex(i | df.index)) 0 1 11.0 2 22.0 3 NaN 4 44.0 5 55.0
score: 3
has comment: http://stackoverflow.com/comment/84850910
answers question: http://stackoverflow.com/q/48922023

http://stackoverflow.com/comment/84676927
type: Comment
has text: @acquayefrank correct, added more explanation on my answer
comment on: http://stackoverflow.com/a/48830640
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84677182
has text: You should download [wireshark](https://www.wireshark.org/) and watch some packet traffic that is visually intuitive. The transport layer header immediately follows the IP header. However, note that both IP and TCP have optional fields that should be accounted for. UDP header size is static (checksum field is "optional," but still accounted for by setting to all 0's).
type: AnswerComment
comment on: http://stackoverflow.com/a/48833499
type: Comment
score: 0

http://stackoverflow.com/comment/84619029
has text: there is no error of indentation problem@Narendra
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48807841

http://stackoverflow.com/q/48888489
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84782447
has comment: http://stackoverflow.com/comment/84782435
has comment: http://stackoverflow.com/comment/84782042
type: Question
has answer: http://stackoverflow.com/a/48888624
has comment: http://stackoverflow.com/comment/84782400
has answer: http://stackoverflow.com/a/61270121
score: 0
has title: Pandas read_sql not reading specified date
answer count: 3
tagged with: pandas
has comment: http://stackoverflow.com/comment/84782031
linked to: http://stackoverflow.com/q/902408
has answer: http://stackoverflow.com/a/48888839
accepted answer: http://stackoverflow.com/a/48888839
possible better answer: http://stackoverflow.com/a/48888624
has body: I'm trying to filter my SQL code in Python using a specified date in my where statement. For some reason it isn't filtering based on the date and I'm unsure why. Want to filter on report_dt > '2018-01-01' but result output is giving all data import pandas as pd startdate='2018-01-01' test=pd.read_sql("""SELECT top 10 report_dt FROM db.table where report_dt&gt;{} """.format(startdate) , connection) print(test) REPORT_DT 0 2014-02-15 1 2014-02-15 2 2014-02-15
has comment: http://stackoverflow.com/comment/84782418
tagged with: python
has comment: http://stackoverflow.com/comment/84782422

http://stackoverflow.com/comment/84865430
has text: "df.repartition(partition_col)" is correct way, many empty partitions are not affects you. Please look section "repartition by column" here: https://hackernoon.com/managing-spark-partitions-with-coalesce-and-repartition-4050c57ad5c4
comment on: http://stackoverflow.com/q/48926751
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48837417
answer count: 1
has comment: http://stackoverflow.com/comment/84701847
tagged with: cx-freeze
tagged with: python
has comment: http://stackoverflow.com/comment/84715353
type: AnsweredQuestion
has title: pysnmp.smi.error.MibNotFoundError: No module __SNMP-FRAMEWORK-MIB loaded at <pysnmp.smi.builder.MibBuilder object at 0x0418A110>
has answer: http://stackoverflow.com/a/48859223
has body: I'm just starting out in Python so please bear with me. I've been trying to find a solution to this error for the last 3 days in google, Stack Overflow, Github, python.org and also xxxx.com. I have progressed from other errors (thanks in part to the above websites) but this one has me stumped and I cannot seem to resolve it. I'm running the following versions of stuff: Windows 10 Enterprise 64-bit python 3.6, pysnmp 4.4.4, pyasn1 0.2.3 and I am using paramiko for ssh and tkinter as a GUI My project is composed using Visual Studio Code v1.20.1 Basically I have made a python app that logs into a cisco switch and adds a vlan to a trunk, replaces it with another vlan, or removes both vlans Each time one of these vlan changes is made the script sends an snmp trap to an NMS saying what was just done. The trap is just an OID as follows: def sendTrap(system): debug.setLogger(debug.Debug('msgproc')) next(sendNotification(SnmpEngine(), CommunityData('blahblah'), UdpTransportTarget(('1.1.1.1', 162)), ContextData(), 'trap', # sequence of custom OID-value pairs [ObjectType(ObjectIdentity('1.3.6.1.2.1.1.1.0'), OctetString(system))])) Some other stuff happens as well, like the background colour when a change is made, and a timer begins which resets everything back after a predetermined amount of time. The program works flawlessly when I run it as a python script. However, when I use cx_freeze to create an exe file of my little app everything works EXCEPT for the snmp trap and I currently get the following traceback error: 2018-02-17 02:17:39,956 pysnmp: running pysnmp version 4.4.4 2018-02-17 02:17:39,957 pysnmp: debug category 'msgproc' enabled Exception in Tkinter callback Traceback (most recent call last): File "C:\Python\Python36-32\lib\site-packages\pysnmp\entity\engine.py", line 91, in __init__ '__SNMP-FRAMEWORK-MIB', 'snmpEngineMaxMessageSize') File "C:\Python\Python36-32\lib\site-packages\pysnmp\smi\builder.py", line 409, in importSymbols 'No module %s loaded at %s' % (mod…
type: Question
has comment: http://stackoverflow.com/comment/84687181
tagged with: pysnmp
score: 0
accepted answer: http://stackoverflow.com/a/48859223
has comment: http://stackoverflow.com/comment/84714756

http://stackoverflow.com/comment/84847226
comment on: http://stackoverflow.com/a/48920169
score: 0
type: AnswerComment
type: Comment
has text: i tried your answer but it display this error File "C:\Users\test\Documents\Python_Projects\readCSV.py", line 14, in <module> minTemp.append(float(row[1])) builtins.ValueError: could not convert string to float:

http://stackoverflow.com/comment/84809289
has text: Note that the pickle data format uses a printable ASCII representation, so it is not your desired format.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48901566

http://stackoverflow.com/a/48846498
answers question: http://stackoverflow.com/q/48846252
downvote count: 0
has comment: http://stackoverflow.com/comment/84697283
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84698476
has body: If this is not on the same domain, I would recommend setting up Django REST Framework. If it is on the same domain, then do what is recommended on the Django Docs: you can get the CSRF token with JavaScript (note that I've changed the function to be used without jQuery): // WITHOUT jQuery function getCookie (name) { var cookieValue = null; if (document.cookie &amp;&amp; document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i &lt; cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } Update the form (note the id): &lt;form id="name-form" method="POST" action="http://djangoserver" &gt; &lt;input type="text" name="name" required id="id_name" maxlength="100&gt; &lt;/form&gt; Add the csrftoken input: var form = document.getElementById('name-form'), input = document.createElement('input'); input.name = "csrfmiddlewaretoken"; input.type = "hidden"; input.value = getCookie('csrftoken'); // ^ could be a different string depending on your settings.py file form.appendChild(input); Hope that helps.

http://stackoverflow.com/a/48957375
has comment: http://stackoverflow.com/comment/84931088
type: Answer
accepted answer of: http://stackoverflow.com/q/48956252
has body: You need to know beforehand how many classes you are going to need. After the first call to partial fit, the algorithm assumes you will not have any new classes to add later. In your example, you are added in a new class (y2 = 8) that has never been seen before and was not indicated as existing in your initial call to partial fit (that only contained the labels "5" and "6"). You need at add it to the classes object on the first call. I would also recommend you number your classes starting from 0 just for consistency's sake.
score: 3
answers question: http://stackoverflow.com/q/48956252
upvote count: 3
has comment: http://stackoverflow.com/comment/85262164
has comment: http://stackoverflow.com/comment/84921890
has comment: http://stackoverflow.com/comment/84921810
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85280946
has comment: http://stackoverflow.com/comment/84925034
downvote count: 0
has comment: http://stackoverflow.com/comment/84968564

http://stackoverflow.com/comment/84648394
comment on: http://stackoverflow.com/a/48821805
score: 0
type: Comment
has text: @MinnaAdelRubio always glad to help
type: AnswerComment

http://stackoverflow.com/comment/138957140
type: Comment
comment on: http://stackoverflow.com/a/60466901
has text: the question asks about **inline** buttons
type: AnswerComment
score: 0

http://stackoverflow.com/q/48938042
favorite count: 0
answer count: 3
tagged with: python
has title: TypeError: string indices must be integers, not str with JSON parsing
possible better answer: http://stackoverflow.com/a/48938132
upvote count: 2
downvote count: 1
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
has answer: http://stackoverflow.com/a/48938132
has answer: http://stackoverflow.com/a/48938386
accepted answer: http://stackoverflow.com/a/48938386
type: Question
has comment: http://stackoverflow.com/comment/84883126
has answer: http://stackoverflow.com/a/48938302
has body: I am getting the above error when trying to parse a JSON file. Code: import json data = open('output.json').read() for host in data['ASSET_DATA_REPORT']['HOST_LIST']['HOST']: print(host['IMAGE_ID']) Traceback: Traceback (most recent call last): File "json_format.py", line 11, in &lt;module&gt; for host in data['ASSET_DATA_REPORT']['HOST_LIST']['HOST']: TypeError: string indices must be integers, not str JSON: { "ASSET_DATA_REPORT": { "HOST_LIST": { "HOST": [ { "IP": { "network_id": "0" }, "TRACKING_METHOD": "EC2", "ASSET_TAGS": { "ASSET_TAG": [ "EC2 Running", "IF - Database - MySQL", ] }, "DNS": "i-xxxxxxx", "EC2_INSTANCE_ID": "i-xxxxxx", "EC2_INFO": { "PUBLIC_DNS_NAME": "ec2-xxxxxxxx.amazonaws.com", "IMAGE_ID": "ami-xxxxxx", "VPC_ID": "vpc-xxxxxx", "INSTANCE_STATE": "RUNNING", "PRIVATE_DNS_NAME": "ip-xxxx.ec2.internal", "INSTANCE_TYPE": "m3.xlarge" } } ] } } } It seems like host is a string for some reason and I'm not sure how to overcome this error.

http://stackoverflow.com/q/48838806
has answer: http://stackoverflow.com/a/48838958
has comment: http://stackoverflow.com/comment/84682074
has title: Not Found: /media/ on form submit
tagged with: python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84682191
tagged with: django
has body: I have a form with a ImageField() in it I've already set the media URL and directory and such in setting.py and url.py and on submit everything works perfectly, but suddenly now every time I try submit my form it fails and says in python terminal : [17/Feb/2018 14:40:08] "POST /form/ HTTP/1.1" 200 37885 Not Found: /media/ I didn't modify either setting.py or the url.py (see code below): setting.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') url.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model.py class Model_A(models.Model): name = models.CharField(max_length=200, verbose_name="Name (as in NRIC)") def upload_photo_dir(self, filename): path = 'hiring/employees/photo/{}'.format(filename) return path photo = models.ImageField(upload_to=upload_photo_dir) view.py def application_form_view(request): form = Model_AForm(request.POST or None, request.FILES or None) if form.is_valid(): inst = form.save(commit=False) inst.save() context = {'form': form} return render(request, 'form.html', context=context) html name : {{ form.name}} Photo: {{ form.photo }}
type: Question
score: 0
answer count: 1

http://stackoverflow.com/q/48955833
has answer: http://stackoverflow.com/a/48956251
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84919538
favorite count: 0
has comment: http://stackoverflow.com/comment/84918568
has comment: http://stackoverflow.com/comment/84918491
type: UnansweredQuestion
has body: I have a dataframe and want to find all rows when one of the columns contains a certain string: tmp = data_frame[data_frame["DESC"].str.contains(tag, na=False)] However, assume that tag is a list, and I want the column to contain any string in the list, for example: tmp = data_frame[(data_frame["DESC"].str.contains(tag[0], na=False)) | (data_frame["DESC"].str.contains(tag[1], na=False))] Now, assume that I have a list of lists, and tag is an element in it, and I loop through this list of lists: for tag in tag_list: tmp = data_frame[(data_frame["DESC"].str.contains(tag[0], na=False)) | (data_frame["DESC"].str.contains(tag[1], na=False))] ---do something with tmp Further, now assume that tag_list is a list of lists, but each element may have different length, so sometimes tag has 1 element, sometimes 2, sometimes 4, etc. How can I define tmp in a way that it is independent of a fixed length for tag? Ex: tmp = pandas.DataFrame(columns=["DESC"]) tmp.loc[0] = ["Hello"] tmp.loc[1] = ["Hello"] tmp.loc[2] = ["Hi"] tmp.loc[3] = ["Good Morning"] tag = ["Hi", "Hello"] tmp2 = tmp[(tmp["DESC"].str.contains(tag[0], na=False)) | (tmp["DESC"].str.contains(tag[1], na=False))]
tagged with: python
linked to: http://stackoverflow.com/q/26577516
tagged with: list
linked to: http://stackoverflow.com/q/20109391
score: 1
has title: Create "or" conditions based on elements in a list that may have variable length
upvote count: 1
has comment: http://stackoverflow.com/comment/84919341
type: Question
has comment: http://stackoverflow.com/comment/84918931
has comment: http://stackoverflow.com/comment/84919463
tagged with: pandas

http://stackoverflow.com/q/48849704
has body: I want Python to display data from Access on Label. I tried to do smth like this but it doesn't work. There is no error but Label displays pypyodbc.Cursor object at 0x05E02990. What should I do? Thank you from tkinter import * import pypyodbc import ctypes #Create connection con = pypyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=C:/Users/HP/Desktop/PITL;DBQ=C:/Users/HP/Desktop/PITL/PITL.mdb;') cursor = con.cursor () form = Tk () form.title ("Main") form.geometry ('400x400') form2 = Tk () form2.title ("Main") form2.geometry ('400x400') form2.withdraw() def Show(): cursor.execute ("SELECT Law_ID FROM Laws WHERE Fine=1") a=cursor.execute for a in cursor: print ("Law ID where Fine is 1 is", a) Label(form2, text=cursor).pack() form.withdraw() form2.deiconify() Button(form, text = 'PUSH ME', command = Show).pack() form.mainloop () con.commit () cursor.close () con.close ()
tagged with: ms-access
has title: How Python can display data on Label by Access (SQL)?
has answer: http://stackoverflow.com/a/48850577
tagged with: python
has comment: http://stackoverflow.com/comment/84707401
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84703611
type: UnansweredQuestion
tagged with: select
type: Question
has comment: http://stackoverflow.com/comment/84703067
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/77527097
tagged with: sql

http://stackoverflow.com/a/48828273
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48828173
answers question: http://stackoverflow.com/q/48828173
has body: use pd.merge_asof() In [232]: pd.merge_asof(df1.sort_values('d'), df2, on='d', tolerance=pd.to_timedelta('2S'), direction='nearest') Out[232]: d v vx 0 2018-02-16 10:18:56.768246 4 NaN 1 2018-02-16 13:39:55.562506 1 100.0 NOTE: the joining field (d in your case) must be sorted for both DFs
upvote count: 5
score: 5

http://stackoverflow.com/comment/84693039
comment on: http://stackoverflow.com/a/48843937
score: 0
type: AnswerComment
type: Comment
has text: @JNg, sure. You can always retrieve `n` via `df.columns` or similar. piR's solution should work as well.

http://stackoverflow.com/comment/84670000
score: 1
comment on: http://stackoverflow.com/q/48827917
type: Comment
has text: OK, I will try the code with your data file.
type: QuestionComment

http://stackoverflow.com/comment/84822165
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48899897
score: 0
has text: It's XML. And it's well formed. The problems does not lie there and this question can be pondered without an example of the XML. There is nothing you will glean from that. I'm parsing millions of records and most are parsing just fine. It's the ones with extremely old html-entities, and how to get rid of them. There are entities in there.. such as '&lE;' which cannot be found by searching Google.

http://stackoverflow.com/a/68530872
answers question: http://stackoverflow.com/q/48949526
score: 0
has body: A little bit late and I'm trying Anvil in which the previous answers didn't work. just for the curious people. resp = anvil.http.request("http://<ipaddress>/data.json", json=True) #print(resp) # prints json file tempdict = resp['sensordatavalues'][2].values() humiddict = resp['sensordatavalues'][3].values() temperature = float(list(tempdict)[1]) humidity = float(list(humiddict)[1]) print(temperature) print(humidity)
type: Answer

http://stackoverflow.com/q/48935143
answer count: 1
has comment: http://stackoverflow.com/comment/84878818
has comment: http://stackoverflow.com/comment/84876845
type: AnsweredQuestion
downvote count: 0
linked to: http://stackoverflow.com/q/48924025
has body: In reference to a previous question Python Regex - Capture match and previous two lines I am try to write this match to a text file but it seems to write all the matches on 1 line. Tried these combinations with no luck output = re.findall(r'(?:.*\r?\n){2}.*?random data.*', f.read()) myfilename.write(str(list(output) + '\n')) # gives me TypeError: can only concatenate list (not "str") to list myfilename.write(str(output)) # writes to one line Would I need a for loop to iterate each index to a new line, or am I missing something, it should be matching the CRLLF and keep the original format correct?
favorite count: 0
linked to: http://stackoverflow.com/q/899103
has title: Python - Write list to text file with \n from re.findall
has comment: http://stackoverflow.com/comment/84878833
type: Question
has answer: http://stackoverflow.com/a/48935181
duplicate of: http://stackoverflow.com/q/899103
tagged with: regex
score: 1
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48935181
upvote count: 1
tagged with: python

http://stackoverflow.com/comment/84841016
type: AnswerComment
comment on: http://stackoverflow.com/a/48899337
type: Comment
has text: @gghimire, please specify your error tracback. Did you change the line `self.cursor.execute("CREATE DATABASE {}".format(c_database))`?
score: 0

http://stackoverflow.com/a/48828896
has comment: http://stackoverflow.com/comment/84663250
has comment: http://stackoverflow.com/comment/84662960
has comment: http://stackoverflow.com/comment/84665122
downvote count: 0
has comment: http://stackoverflow.com/comment/91718041
has body: One possible solution is cross join by column category: df1 = df.reset_index() df1 = pd.merge(df1, df1, on='category') m = ((df1.start_x &gt;= df1.start_y) &amp; (df1.end_x &lt;= df1.end_y) &amp; (df1.index_x != df1.index_y)) idx = df1.loc[m, 'index_x'] print (df.drop(idx)) category start end 0 c1 100 200 2 c2 10 40 3 c2 35 45 4 c3 50 100
has comment: http://stackoverflow.com/comment/84704710
score: 5
answers question: http://stackoverflow.com/q/48828456
upvote count: 5
has comment: http://stackoverflow.com/comment/84703783
has comment: http://stackoverflow.com/comment/84663334
has comment: http://stackoverflow.com/comment/84662918
type: Answer
has comment: http://stackoverflow.com/comment/84665073

http://stackoverflow.com/comment/84937819
comment on: http://stackoverflow.com/a/48965367
score: 0
type: AnswerComment
type: Comment
has text: Would be great to isolate the root cause. Start with the ZeroMQ python binding version number ( epgm since 2.1.11+ ) and best test the non-python ( best the original C language mock-up, according to the API documentation ).

http://stackoverflow.com/q/48954155
upvote count: 5
tagged with: python
has answer: http://stackoverflow.com/a/48961122
has comment: http://stackoverflow.com/comment/84915889
accepted answer: http://stackoverflow.com/a/48960719
type: AnsweredQuestion
downvote count: 0
has title: numpy array of arbitrary precision (10 bit int)
type: Question
tagged with: numpy
has answer: http://stackoverflow.com/a/48960719
score: 5
has comment: http://stackoverflow.com/comment/84915654
has comment: http://stackoverflow.com/comment/84916937
has comment: http://stackoverflow.com/comment/84915653
possible better answer: http://stackoverflow.com/a/48961122
has comment: http://stackoverflow.com/comment/84915296
tagged with: int
answer count: 2
has comment: http://stackoverflow.com/comment/84915001
has comment: http://stackoverflow.com/comment/84915140
has body: I need to simulate a piece of hardware that generates binary files where each word is 10 bits. How can I achieve this with a numpy array? Something like: outarray = np.zeros(512, dtype=np.int10) Thanks!
tagged with: precision
favorite count: 0
has comment: http://stackoverflow.com/comment/84916187

http://stackoverflow.com/a/48877329
downvote count: 0
has comment: http://stackoverflow.com/comment/84759534
has comment: http://stackoverflow.com/comment/84759841
has comment: http://stackoverflow.com/comment/84759597
has comment: http://stackoverflow.com/comment/84758747
has comment: http://stackoverflow.com/comment/84759811
type: Answer
has comment: http://stackoverflow.com/comment/84759711
has comment: http://stackoverflow.com/comment/84759121
upvote count: 2
has body: First, load your data using pd.read_csv: import pandas as pd df = pd.read_csv("/home/vipul/Desktop/example.csv", sep=',') print(df) name age address 0 john 25 koramangala banglore +ACMAQA- sales maneger +A... 1 harshuth rao 36 belandur banglore +ACMAQA- maneger +ACUAJA- i... 2 vijay kumar 45 ulsoor banglore +ACMAQA- sales maneger +ACUAJA... 3 suhas 25 koramangala banglore +ACMAQA-analist +ACUAJA- ... 4 mithun 22 venkatapura banglore +ACMAQA- execitive +ACUAJ... Next, use str.split to separate the data + pd.concat to join with the original: v = df.pop('address').str.split('\s*\+.*?-\s*', expand=True) v.columns = ['city', 'position', 'country'] df = pd.concat([df, v], 1) print(df) name age city position country 0 john 25 koramangala banglore sales maneger india 1 harshuth rao 36 belandur banglore maneger india 2 vijay kumar 45 ulsoor banglore sales maneger india 3 suhas 25 koramangala banglore analist india 4 mithun 22 venkatapura banglore execitive india Finally, save to CSV: df.to_csv("/home/vipul/Desktop/new.csv")
has comment: http://stackoverflow.com/comment/84758764
answers question: http://stackoverflow.com/q/48877279
has comment: http://stackoverflow.com/comment/84759822
has comment: http://stackoverflow.com/comment/84759768
has comment: http://stackoverflow.com/comment/84759569
has comment: http://stackoverflow.com/comment/84759789
score: 2
has comment: http://stackoverflow.com/comment/84759722

http://stackoverflow.com/q/48949894
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48982126
tagged with: python
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84906514
has body: I installed some backtesting libraries which updated pandas version. Since then I'm getting ImportError: cannot import name 'hashtable' I referred the existing question: Hashtable Error in Pandas. And tried &gt; pip install pandas &gt; conda update pandas but nothing seems working. Any suggestions are welcome. EDIT : I removed pandas from conda using conda remove --force pandas And reinstalled it. Now I'm getting new error AttributeError: module 'pandas' has no attribute 'compat' Thanks
type: Question
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/14422976
has comment: http://stackoverflow.com/comment/84906585
has title: unable to import pandas
tagged with: pandas
upvote count: 1
accepted answer: http://stackoverflow.com/a/48982126
answer count: 1
has comment: http://stackoverflow.com/comment/84906580
favorite count: 0

http://stackoverflow.com/a/48818024
has comment: http://stackoverflow.com/comment/84640522
upvote count: 2
has comment: http://stackoverflow.com/comment/84643068
answers question: http://stackoverflow.com/q/48817981
has body: urllib.request.retrieve to download zip file https://docs.python.org/3/library/urllib.request.html zipfile module to extract files https://docs.python.org/3/library/zipfile.html find csv file(s) in path with glob module https://docs.python.org/3/library/glob.html finally use csv module https://docs.python.org/3/library/csv.html
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/92953271
downvote count: 0
has comment: http://stackoverflow.com/comment/84640156

http://stackoverflow.com/comment/84865712
score: 0
comment on: http://stackoverflow.com/q/48906238
type: Comment
type: QuestionComment
has text: I think it may be something to do with my Docker container as I added an additional package (lzop), however when I remove lzop from make file and start again it still gives the same issue

http://stackoverflow.com/q/48955851
answer count: 1
linked to: http://stackoverflow.com/q/845058
has comment: http://stackoverflow.com/comment/84918465
score: 0
tagged with: python
linked to: http://stackoverflow.com/q/43320868
has comment: http://stackoverflow.com/comment/84918542
has comment: http://stackoverflow.com/comment/84918772
has comment: http://stackoverflow.com/comment/84918512
has body: I used the following questions as sources, listed along with the code I am asking about: How to get line count cheaply in Python? def file_len(fname): with open(fname) as f: for i, l in enumerate(f): pass return i + 1 fname = '/path/file.xls' file_len(fname) This returned 40, when the actual number of lines is 56. How to count rows in multiple csv file import glob import pandas as pd files = glob.glob('files/*.xls') d = {f: sum(1 for line in open(f)) for f in files} This returned 40 for the same file as well, and did not return the correct counts for other files in that path either. It is not returning an error, and returns the same count consistently across methods, however it is not the correct number of lines. My question is : What is actually being counted in the .xls files, since it is not the number of lines?
tagged with: excel
has title: What is actually being counted when I pass an excel file to python code that counts lines in a file?
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48955976
accepted answer: http://stackoverflow.com/a/48955976
has comment: http://stackoverflow.com/comment/84918590
type: Question
linked to: http://stackoverflow.com/q/15541641

http://stackoverflow.com/a/48868512
answers question: http://stackoverflow.com/q/48867924
score: 0
type: Answer
has body: Your ada variable is now a trained classifier instance. In order to use it to classify new data, you construct an X with the data in a format corresponding to 'game_id', 'game_date_id', 'home_team_id', 'away_team_id', 'referee_id', 'away_team_travel'. Then you run ada.predict(X) and you're done! The issue is that you're currently only passing in the game_id.
has comment: http://stackoverflow.com/comment/84742916

http://stackoverflow.com/q/48952824
upvote count: 3
tagged with: tensorflow
type: Question
downvote count: 0
answer count: 1
has title: Reading multiple images as tensors using tf.map_fn
has body: I am reading in various images (data and labels) in using Tensorflow's Dataset API. Since the Dataset queues are on the CPU, copying data around is expensive. However, I can't seem to find a way to avoid that. Question: Can I efficiently load various kinds of images in a unified order (e.g. h,w,c)? Let's say I want to read in a single single-channel image, I can do that as follows: image = tf.image.decode_png(tf.read_file(file_name), channels=1) # h,w,c Or for multi-channel RGB: image = tf.image.decode_png(tf.read_file(file_name), channels=3) # h,w,c This gives me a height-width-channel ordering, which is convenient for data-augmentation and pre-processing functions such as tf.image.per_image_standardization. However, if I load multiple images and want to stack them together (e.g. a CNN with multiple RGB inputs or a multi-label semantic segmentation problem), I always seem to have to copy the data. Here is one way using a copy in tf.stack: images = [] for image_id in range(0, images): file = file_names[image_id] images.append(tf.image.decode_png(tf.read_file(file), channels=1)[:, :, 0]) images = tf.stack(images, axis=2) # Packs as h,w,c Another way is using tf.map_fn, which looks like it was meant for this purpose. However, it 'stacks' in the wrong dimension, so I still need an expensive transpose: map = tf.map_fn(lambda f: tf.image.decode_png(tf.read_file(f), channels=1)[:, :, 0], file_names, back_prop=False, dtype=tf.uint8) images = tf.transpose(map, [1, 2, 0]) # from c,h,w to h,w,c Is it possible to avoid the tf.stack or tf.transpose?
has answer: http://stackoverflow.com/a/48956595
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 3

http://stackoverflow.com/comment/84770035
comment on: http://stackoverflow.com/q/48882938
score: 1
type: Comment
type: QuestionComment
has text: you are missing `}` after "address_components" list

http://stackoverflow.com/comment/84783369
type: Comment
comment on: http://stackoverflow.com/a/48889118
has text: I have `xadmin` registered in my `settings.py` file, that's not the issue. `xadmin` app works but it's not displaying the chart under MainDashboard
score: 0
type: AnswerComment

http://stackoverflow.com/q/48934362
tagged with: python
type: AnsweredQuestion
upvote count: 2
score: 1
downvote count: 1
type: Question
tagged with: dummy-variable
has answer: http://stackoverflow.com/a/48985074
accepted answer: http://stackoverflow.com/a/48985074
tagged with: pandas
answer count: 1
favorite count: 0
has title: How to store the get_dummies transformation of pandas in Python?
has body: There is the get_dummies transformation in the pandas package in python, which transforms categorical variables to binary (flag) variables with values 0 / 1. This transformation is based on the actual values, but I'd like to store the code of the transformation, so that I can run it on other datasets, with less values, and still get the full-sized transformed data structure. Say you have this code: import pandas as pd a = [[5,12,"blue"], [8,53,"yellow"]] df = pd.DataFrame(a, columns=['Weight','Size','Color']) df.apply(pd.to_numeric, errors='ignore') df Producing this data: Weight Size Color 5 12 blue 8 53 yellow and: df = pd.get_dummies(df) df produces this: Weight Size Color_blue Color_yellow 5 12 1 0 8 53 0 1 I'd like to store this original transformation, so that if I get a record later, like: [2,9,"blue"] I can still get the whole structure, like: Weight Size Color_blue Color_yellow 2 9 1 0 Get_dummies will omit the Color_yellow column in the latter case... What is the simplest solution to it? I was thinking of something like building my own get_dummies function, which goes through all the categorical variables, gets all their possible distinct values, and then produces the code of the python function, which does the transformation. But there must be some already implemented solution to it...

http://stackoverflow.com/comment/84839267
comment on: http://stackoverflow.com/q/48916262
has text: @roganjosh the inv output is a dictionary.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/91988703
type: Comment
has text: It really depends on the case... The natural way seems to be 1) train model A, 2) freeze common layers, 3) train model B with frozen layers from model A
type: AnswerComment
comment on: http://stackoverflow.com/a/48856251
score: 0

http://stackoverflow.com/q/48861328
answer count: 0
score: 1
has body: I am having a trouble converting my datetime string column which contains different formats into one format. Here's the example: test = pd.DataFrame(['2/5/18 21:24', '22/8/17 13:18', '23/8/17 10:47', '2018-09-02 10:15:25'], columns=["date_time"]) # '2018-09-02 10:15:25' this is not September, but should be February If it's only converting from 1 format to another, for example, 2/5/18 21:24 to 2018-02-05 21:24:00 then I know how to do it. import datetime datetime.datetime.strptime('2/5/18 21:24', '%m/%d/%y %H:%M').strftime('%Y-%m-%h %H:%M:%S') Initially, I thought there were only 2 different date formats: %m/%d/%y %H:%M and %Y-%m-%h %H:%M:%S so I thought I could do something like: test['converted_date_time'] = np.where(test['date_time'].str.contains(r'/'), datetime.datetime.strptime(str(test['date_time']), '%m/%d/%y %H:%M').strftime('%Y-%m-%h %H:%M:%S'), test['date_time']) But as you can see it wouldn't work and thus, I received this error: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/Users/usr1/anaconda3/lib/python3.6/_strptime.py", line 565, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "/Users/usr1/anaconda3/lib/python3.6/_strptime.py", line 362, in _strptime (data_string, format)) ValueError: time data '0 2/5/18 21:24\n1 22/8/17 13:18\n2 23/8/17 10:47\n3 2018-09-02 10:15:25\nName: date_time, dtype: object' does not match format '%m/%d/%y %H:%M' Additionally, I have also tried using dateutil module: import dateutil.parser dateutil.parser.parse(str(test['date_time'])) and get this error: Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; File "/Users/usr1/ht_monitoring/venv_ht_monitoring/lib/python3.6/site-packages/dateutil/parser.py", line 1182, in parse return DEFAULTPARSER.parse(timestr, **kwargs) File "/Users/usr1/ht_monitoring/venv_ht_monitoring/lib/python3.6/site-packages/dateutil/parser.py", line 559, in parse raise ValueError("Unknown string format") Valu…
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84756026
has comment: http://stackoverflow.com/comment/84732041
has comment: http://stackoverflow.com/comment/84758145
downvote count: 0
has comment: http://stackoverflow.com/comment/84757409
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84725630
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/84725684
has title: Python 3 - Convert multiple datetime string formats into one format in pandas dataframe column
has comment: http://stackoverflow.com/comment/84734916

http://stackoverflow.com/comment/84807674
type: AnswerComment
comment on: http://stackoverflow.com/a/48898593
type: Comment
score: 1
has text: This won't add the filter function to the Excel file.

http://stackoverflow.com/comment/84694950
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48845287
type: Comment
has text: Check out [the documentation on file reading](https://docs.python.org/3.6/tutorial/inputoutput.html#reading-and-writing-files). In particular, look at `f.read()` function.

http://stackoverflow.com/comment/84803572
comment on: http://stackoverflow.com/q/48899062
score: 0
has text: If one type was universally and objectively the best, why would the others exist? Voting to close as opinion-based and/or too broad.
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48935506
has title: Strptime presumes hours inconsistently
has answer: http://stackoverflow.com/a/48935642
tagged with: strptime
answer count: 1
tagged with: python-3.x
tagged with: datetime
tagged with: python
accepted answer: http://stackoverflow.com/a/48935642
type: AnsweredQuestion
score: 0
has body: I have a (pandas) Series of numbers like 20170809 20181231 I want to convert them into datetime objects. this is trivial with an apply wrapped around datetime.strptime(x, '%Y%M%d'). However, datetime is adding on hours that are different. For instance: 20011231 2001-01-31 00:12:00 20050102 2005-01-02 00:01:00 20000815 2000-01-15 00:08:00 How can I force strptime to assume the same hour/minute/second for every string?
type: Question

http://stackoverflow.com/a/48814757
accepted answer of: http://stackoverflow.com/q/48814715
answers question: http://stackoverflow.com/q/48814715
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: If you are running Python in IDLE, I suspect you don't start IDLE from the shell for which you've defined your new_v. Hence, IDLE does not know about the variable, and neither can Python. If you execute python in your shell and type os.getenv("new_v") you will see your variable. I'm not a Mac user, so I don't know myself how to set env vars in macOS, but this post Setting environment variables in OS X? seems to have an answer :)
upvote count: 6
score: 6

http://stackoverflow.com/comment/103968131
type: QuestionComment
has text: Are you using only two nodes? How about plotting a scatter-plot or `plt.imshow` where each node represents one point on a 2D grid and the color corresponds to the major class in that node? In the SUSI, package, this is called `estimation_map`, maybe this helps: https://github.com/felixriese/susi/blob/master/examples/SOMClassifier_Salinas.ipynb
comment on: http://stackoverflow.com/q/48902586
score: 0
type: Comment

http://stackoverflow.com/comment/84777438
type: Comment
has text: I'm assuming he is not just counting that specific word but many as he says "'I'd like to count specific things" so Counter() is a better option as far I as can tell.
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48886166

http://stackoverflow.com/q/48897561
answer count: 1
has answer: http://stackoverflow.com/a/48897921
favorite count: 0
type: UnansweredQuestion
tagged with: python
upvote count: 4
has comment: http://stackoverflow.com/comment/84800737
has body: In Python the built in constant None is guaranteed to be singular. There is only one instance of it. This is not the case for other built in types. Strings or numbers with the same contents are not unique. Two strings "a" and "a" are not unique but have different instances. The same goes for two numbers with identical internal values, say 1.0 and 1.0. Are the built in Boolean constants True and False unique like None, or do they have different instances? A specific example is: value = 1 == 1 in this case is value the same instance as True?
downvote count: 0
has comment: http://stackoverflow.com/comment/84800890
type: Question
has comment: http://stackoverflow.com/comment/84801266
has title: In Python are the built in constants True and False unique?
score: 4

apache
tag name: apache
tags question: http://stackoverflow.com/q/48920126
tags question: http://stackoverflow.com/q/48860432
tags question: http://stackoverflow.com/q/48818833
tags question: http://stackoverflow.com/q/48954705
tags question: http://stackoverflow.com/q/48841239
tags question: http://stackoverflow.com/q/48840076
type: Tag
tags question: http://stackoverflow.com/q/48850731
tags question: http://stackoverflow.com/q/48821541

http://stackoverflow.com/q/48852586
type: UnansweredQuestion
tagged with: datetime
tagged with: python
has comment: http://stackoverflow.com/comment/84708753
has body: is there a solution to convert an general format for a datetime in a python script without placing on every variable something like this: variable.strftime('%d-%m-%Y') best regards
type: Question
has title: Converting datetime into a general format in python script
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48852851

http://stackoverflow.com/q/48959025
upvote count: 1
downvote count: 1
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48959130
accepted answer: http://stackoverflow.com/a/48959130
has title: pyqt5 set font for all parts in a dialog box
answer count: 1
favorite count: 0
score: 0
tagged with: python
has body: I made a dialog box with PyQt5, there are several QLabels, QLineEdits and QPushButtons, how can I set Font to all these parts? it will to many lines to set font one by one. Can I have Font settings by one time?

http://stackoverflow.com/comment/123872649
type: AnswerComment
has text: In any form of Unix, the CPU is released during sleep() calls. Pretty sure this is the case with Python's time.sleep(). Please update if I'm wrong!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48810684

http://stackoverflow.com/comment/107534175
type: QuestionComment
comment on: http://stackoverflow.com/q/48941191
has text: did either of you ever figure this out? Just starting to investigate this as well... I'm guessing this might have to do with VPC configuration but still haven't been able to find a definitive answer on the topic.
score: 0
type: Comment

http://stackoverflow.com/q/48940547
answer count: 1
downvote count: 0
score: 1
favorite count: 0
has title: python add dictionary to existing dictionary - AttributeError: 'dict' object has no attribute 'append'
has comment: http://stackoverflow.com/comment/84888108
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48940591
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/33640689
has comment: http://stackoverflow.com/comment/84888104
has comment: http://stackoverflow.com/comment/84888358
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84888216
accepted answer: http://stackoverflow.com/a/48940591
has comment: http://stackoverflow.com/comment/84888148
has comment: http://stackoverflow.com/comment/106761503
has body: I'm trying to append an existing JSON file. When I overwrite the entire JSON file then everything works perfect. The problem that I have been unable to resolve is in the append. I'm completely at a loss at this point. { "hashlist": { "QmVZATT8jWo6ncQM3kwBrGXBjuKfifvrE": { "description": "Test Video", "url": "" }, "QmVqpEomPZU8cpNezxZHG2oc3xQi61P2n": { "description": "Cat Photo", "url": "" }, "QmYdWb4CdFqWGYnPA7V12bX7hf2zxv64AG": { "description": "test.co", "url": "" } } }% Here is the code that I'm using where data['hashlist'].append(entry) receive AttributeError: 'dict' object has no attribute 'append' #!/usr/bin/python import json import os data = [] if os.stat("hash.json").st_size != 0 : file = open('hash.json', 'r') data = json.load(file) # print(data) choice = raw_input("What do you want to do? \n a)Add a new IPFS hash\n s)Seach stored hashes\n &gt;&gt;") if choice == 'a': # Add a new hash. description = raw_input('Enter hash description: ') new_hash_val = raw_input('Enter IPFS hash: ') new_url_val = raw_input('Enter URL: ') entry = {new_hash_val: {'description': description, 'url': new_url_val}} # search existing hash listings here if new_hash_val not in data['hashlist']: # append JSON file with new entry # print entry # data['hashlist'] = dict(entry) #overwrites whole JSON file data['hashlist'].append(entry) file = open('hash.json', 'w') json.dump(data, file, sort_keys = True, indent = 4, ensure_ascii = False) file.close() print('IPFS Hash Added.') pass else: print('Hash exist!')

http://stackoverflow.com/a/48838120
has body: Can this help? :p import random l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0' l2 = list(l1.split()) def genpass(n): x = 0 password=[] if n &lt; 100: while n &gt; x: password.append(random.choice(l2)) x+=1 return ''.join(password) else: return('Sorry, too long') #example with 14 char print(genpass(14))
type: Answer
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48838050
answers question: http://stackoverflow.com/q/48838050
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84689206
has text: You don't want to cast the whole thing to a string, just the keys.
comment on: http://stackoverflow.com/q/48842543
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/86006877
has text: fair enough, every codebase and use case is a bit different.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48837525
type: Comment

http://stackoverflow.com/comment/84704212
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48849183
has text: Scrapping [_Facebook_](https://www.facebook.com/) is against the [_ToS_](https://www.facebook.com/legal/terms) and you are liable to be questioned and may even land up in [_Facebook Jail_](https://www.facebook.com/help/community/question/?id=804287426255468). Use _Facebook API_ instead.

http://stackoverflow.com/comment/84778381
comment on: http://stackoverflow.com/q/48886671
has text: Just added the error output
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84683503
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48838958
type: Comment
has text: Is your `settings.DEBUG` is False? make that `True` at server you need to make False as you mostly run on server instead of port

http://stackoverflow.com/a/49143540
upvote count: 1
has comment: http://stackoverflow.com/comment/92947958
type: Answer
has body: A thing that was wrong in my local development setup was that I was serving all the /static and /admin/static through the flask app, instead of serving them through the web-server (in my case, nginx). So for some of the urls I was hitting, there might have been 10 requests come in basically at the same time, with Flask in debug mode, and a debugger connected as well (via PyCharm). When I went through the trouble to ensure that all '/static' and '/admin/static' get served from there, instead of via flask, and flask was only getting 1 request per url, this problem went away. I won't mark this as the answer, because there is still an underlying issue, but in case others have the same problem as me, this was a solution for my situation.
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48832112

http://stackoverflow.com/a/48869071
answers question: http://stackoverflow.com/q/48868819
score: 1
has comment: http://stackoverflow.com/comment/84742901
has body: Is it possible that you are simply looking for this? sim_matrix[:] = levels EDIT: to modify a single row, one should use sim_matrix[row_id] = levels On a side note, beware of using mutables as default function arguments.
has comment: http://stackoverflow.com/comment/84742766
has comment: http://stackoverflow.com/comment/84741719
downvote count: 0
has comment: http://stackoverflow.com/comment/84742771
has comment: http://stackoverflow.com/comment/84742287
has comment: http://stackoverflow.com/comment/84742189
type: Answer
has comment: http://stackoverflow.com/comment/84743142
has comment: http://stackoverflow.com/comment/84742830
has comment: http://stackoverflow.com/comment/84741888
has comment: http://stackoverflow.com/comment/84742126
has comment: http://stackoverflow.com/comment/84742705
upvote count: 1

http://stackoverflow.com/comment/84692393
has text: In order to "complete the rest of the code", you have to write *some* code.
type: QuestionComment
comment on: http://stackoverflow.com/q/48844007
score: 0
type: Comment

http://stackoverflow.com/comment/84648401
has text: @mahatmanich This is _not_ recursion.
score: 4
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48822537

http://stackoverflow.com/comment/84835538
type: Comment
score: 0
type: AnswerComment
has text: @HåkenLid I will mention that in my post. I have only just found that out. I do run Windows.
comment on: http://stackoverflow.com/a/48914264

http://stackoverflow.com/a/48827644
type: Answer
has body: The following will not give you ALL the answers, but it WILL get you going using python, pandas and statsmodels for regression analyses. Given a dataframe like this... # Imports import pandas as pd import numpy as np import itertools # A datafrane with random numbers np.random.seed(123) rows = 12 listVars= ['y','x1', 'x2', 'x3'] rng = pd.date_range('1/1/2017', periods=rows, freq='D') df_1 = pd.DataFrame(np.random.randint(100,150,size=(rows, len(listVars))), columns=listVars) df_1 = df_1.set_index(rng) print(df_1) ...you can get any regression results using the statsmodels library and altering the result = model.rsquared part in the snippet below: x = df_1['x1'] x = sm.add_constant(x) model = sm.OLS(df_1['y'], x).fit() result = model.rsquared print(result) Now you have r-squared. Use model.pvalues for the p-value. And use dir(model)to have closer look at other model results (there is more in the output than what you can see below): Now, this should get you going to obtain your desired results. To get desired results for ALL combinations of variables / columns, the question and answer here should get you very far. Edit: You can have a closer look at some common regression results using model.summary(). Using that together with dir(model) you can see that not ALL regression results are availabel the same way that pvalues are using model.pvalues. To get Durbin-Watson, for example, you'll have to use durbinwatson = sm.stats.stattools.durbin_watson(model.fittedvalues, axis=0). This post has got more information on the issue.
score: 0
accepted answer of: http://stackoverflow.com/q/48817816
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48817816

http://stackoverflow.com/a/48874818
has body: there is nothing bad about using a "naive" for loop unless you have some specific requirements (performance mainly or if you know you will have a large number of checks on the same data etc.) a simple for loop clearly shows the intent and even weaker programmers can see what you are doing, hiding the logic behind more complex language constructs is not the right way of course the for loop should be in a function somewhere as well as the distance calculation when you decide to change how the distance is calculated / you might want to use the distance function elsewhere in your code plus you dont need to have the distance when you are just searching for the closest point - squared distance is easier to calculate def distance_squared(point_from, point_to): return (point_from[0] - point_to[0]) ** 2 + (point_from[1] - point_to[1]) ** 2 def contains(points, target_point, threshold): threshold_squared = threshold ** 2 for point in points: if distance_squared(target_point, point) &lt;= threshold_squared: return True return False my_points = [(1, 2), (3, 4), (5.2, 6.3), (7.4, 8.5), (9.6, 10.7), (11.8, 12.9)] print(contains(my_points,(1,1),0)) # False print(contains(my_points,(1,1),1)) # True print(contains(my_points,(3,4),0)) # True the fact that you require the point to be a tuple of floats limits the use of external libraries like numpy or scipy check out this codereview question https://codereview.stackexchange.com/questions/28207/finding-the-closest-point-to-a-list-of-points to see a numpy solution - it looks cleaner and will run faster, but restricts you to use numpy arrays
upvote count: 1
has comment: http://stackoverflow.com/comment/84754220
score: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48873722

http://stackoverflow.com/q/48927931
has comment: http://stackoverflow.com/comment/84862051
answer count: 2
has answer: http://stackoverflow.com/a/48928159
has body: I'm trying to add another condition here: fword.write(' '.join([chr(c-13+97) if c-13+97&gt;96 else chr(c-3+48) for c in ground_valid])+'\n') fword.write(' '.join([chr(c-13+97) if c-13+97&gt;96 else chr(c-3+48) for c in output_valid])) But I cannot quite understand the python 1 liners. From my understanding, if I expand it will be: for c in ground_valid: if c-13+97&gt;96: fword.write(' '.join(chr(c-13+97))) else if: # my condition # instructions else: fword.write(' '.join(chr(c-3+48))) I tried just that but I don't get the expected output. What am I doing wrong? Thank you!
possible better answer: http://stackoverflow.com/a/48928096
has answer: http://stackoverflow.com/a/48928096
has title: Python 1 liners as arguments to functions
accepted answer: http://stackoverflow.com/a/48928159
tagged with: python
type: AnsweredQuestion
score: 0
has comment: http://stackoverflow.com/comment/84862155
type: Question

http://stackoverflow.com/q/48818884
tagged with: sqlalchemy
downvote count: 0
linked to: http://stackoverflow.com/q/29706278
favorite count: 0
tagged with: pandas
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84661371
upvote count: 7
tagged with: pyodbc
type: Question
has title: pandas.read_sql() is MUCH slower when using SQLAlchemy than pyodbc
score: 7
has body: I am trying to read a small table from SQL and I'm looking into switching over to SQLAlchemy from pyodbc to be able to use pd.to_sql() When I compare the two, the sql alchemy is much slower. s_py = """\ import pandas as pd import pyodbc cxn = pyodbc.connect('DRIVER={SQL SERVER};SERVER=.\;DATABASE=PPIS;UID=sa;PWD=pwd') """ s_alch = """\ import pandas as pd import sqlalchemy cxn = sqlalchemy.create_engine("mssql+pyodbc://sa:pwd@./PPIS?driver=SQL+Server") """ timeit.timeit('pd.read_sql("SELECT * FROM Operators", cxn)',setup=s_py, number=100) Out[21]: 0.18496091418973037 timeit.timeit('pd.read_sql("SELECT * FROM Operators", cxn)',setup=s_alch, number=100) Out[23]: 4.407356934717654 I've seen this that talks about inserting rows. But why would the read be so much slower?

http://stackoverflow.com/a/48897068
type: Answer
has body: This is one way. Just map values from table1 to table2, perform the comparison and convert the Boolean to your desired result. table2['t1_value'] = table2['name'].map(table1.set_index('name')['value']) table2['Greater/Less Than'] = (table2['value'] &lt; table2['t1_value'])\ .map({True: 'Less Than', False: 'Greater Than'}) table2 = table2.drop('t1_value', 1) # name value Greater/Less Than # 0 A 7 Less Than # 1 B 3 Less Than # 2 C 24 Greater Than # 3 A 9 Less Than # 4 B 16 Greater Than # 5 C 17 Greater Than # 6 A 0 Less Than # 7 B 5 Less Than # 8 C 23 Greater Than # 9 A 4 Less Than # 10 B 11 Less Than # 11 C 7 Less Than # 12 A 11 Greater Than # 13 B 8 Less Than # 14 C 9 Less Than # 15 A 0 Less Than # 16 B 28 Greater Than # 17 C 20 Greater Than # 18 A 8 Less Than # 19 B 23 Greater Than # 20 C 2 Less Than
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48897025
answers question: http://stackoverflow.com/q/48897025

http://stackoverflow.com/comment/84905592
has text: Do you have visual c++ installed on your computer? Might be you need to download that as `msvc.py` seems to be unable to locate it
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48949054

http://stackoverflow.com/comment/84901166
score: 0
type: Comment
has text: This solved my problem. Thanks!
type: QuestionComment
comment on: http://stackoverflow.com/q/48947248

http://stackoverflow.com/q/48908842
has comment: http://stackoverflow.com/comment/84835703
score: 0
tagged with: pandas
has body: I have this data df = pd.read_csv('https://docs.google.com/spreadsheets/d/e/2PACX-1vQxY-rTQNBbMWtRI2p8m_gj0TvmkHt3_CqNkhRILq6s5xL3mGX-IXtZt9pej-ae3ZNN1EnAP_iC0unx/pub?output=csv', index=False) df.head() Id Year Period Cumulative YearPeriod YearPeriodStr 0 16432976 1 1 6.0 11 Period 11 1 16432976 1 2 7.0 12 Period 12 2 16432976 1 0 0.0 10 Period 10 3 16879454 1 1 6.0 11 Period 11 4 16879454 1 2 6.0 12 Period 12 What I want to achieve is a combination of two ordinal variables on the x-axis. The first level should be Year, the second Period. The following code is what I thought would lead to the graph I want: %opts Curve [width=600 height=400 show_grid=True default_tools=['save','hover',] show_legend=False] (color='indianred', alpha=0.3, line_width=0.2, ) ds = hv.Dataset(df).sort(['Year','Period']) ds.to(hv.Curve, ['Year','Period'],'Cumulative', 'Id').overlay() But this puts Period on the y-axis. The following code gets me closer to what I want: %opts Curve [width=600 height=400 show_grid=True default_tools=['save','hover',] show_legend=False] (color='indianred', alpha=0.3, line_width=0.2, ) # Numerical column df['YearPeriod'] = (df.Year * 10) + (df.Period) ds = hv.Dataset(df).sort(['Year','Period']) ds.to(hv.Curve, 'YearPeriod','Cumulative', 'Id').overlay() But the x-axis now is a continuous variable, while what I want is the second level, Period, to be ordinal. The following code leads more or less to what I want, but fails when the amount of rows exceeds 120. %opts Curve [width=600 height=400 show_grid=True default_tools=['save','hover',] show_legend=False] (color='indianred', alpha=0.3, line_width=0.2, ) # String df['YearPeriodStr'] = 'Period'+ df['Year'].astype(str) + df['Period'].astype(str) ds = hv.Dataset(df.head(120)).sort(['Year','Period']) ds.to(hv.Curve, 'YearPeriodStr','Cumulative', 'Id').overlay() What am I missing?
has title: Categorical axis in Holoviews Curve leads to error
type: UnansweredQuestion
tagged with: holoviews
tagged with: python
answer count: 0
tagged with: bokeh
type: Question
has comment: http://stackoverflow.com/comment/84824358
has comment: http://stackoverflow.com/comment/84824893

http://stackoverflow.com/comment/84922413
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48957440
has text: Oh, well if you're copying hundreds of megabytes of stuff, then sure, this is worth investigating the performance aspects. :)

http://stackoverflow.com/a/66509649
has body: Use white style to return default background: sns.set(style='white')
score: 0
answers question: http://stackoverflow.com/q/48911572
type: Answer

http://stackoverflow.com/comment/84788237
has text: Thanks! but im trying to make it save the input? rather than the entire thing
comment on: http://stackoverflow.com/a/48891405
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/a/48841637
has comment: http://stackoverflow.com/comment/84693171
accepted answer of: http://stackoverflow.com/q/48841407
has body: class VacationCreateForm(forms.ModelForm): class Meta: model = VacationModel fields = [ 'type', 'startDate', 'enddate', ] def clean(self): start_date = self.cleaned_data['start_date'] end_date = self.cleaned_data['end_date'] from dateutils import parse start_date = parse(start_date) end_date = parse(end_date) # make your calculations raise forms.ValidationError("message.") class AddVacation(LoginRequiredMixin, CreateView): form_class = VacationCreateForm template_name = 'vavcation.html' login_url = 'login' def post(self, request, *args, **kwargs): """ Handles POST requests, instantiating a form instance with the passed POST variables and then checked for validity. """ form = self.get_form() if form.is_valid(): return self.form_valid(form) else: redirect(to_ur_another_view) I'm not solving your specific problem I just deliver the idea or what can you do to jump over your problem
answers question: http://stackoverflow.com/q/48841407
score: 0
type: AcceptedAnswer
type: Answer

http://stackoverflow.com/q/48942917
has comment: http://stackoverflow.com/comment/84892520
has comment: http://stackoverflow.com/comment/85133222
has answer: http://stackoverflow.com/a/79482965
tagged with: interactive-brokers
tagged with: python
possible better answer: http://stackoverflow.com/a/51470089
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/49012298
has comment: http://stackoverflow.com/comment/85153950
linked to: http://stackoverflow.com/q/5963269
has body: Basically, I want to use python to query my IB order history and do some analyze afterwards. But I could not find any existing API for me to query these data, does anyone have experience to do this?
has comment: http://stackoverflow.com/comment/85125656
type: Question
has answer: http://stackoverflow.com/a/49012298
has comment: http://stackoverflow.com/comment/84892492
score: 7
has title: Interactive brokers: How to retrieve transaction history records?
has answer: http://stackoverflow.com/a/51470089
answer count: 3
has comment: http://stackoverflow.com/comment/84997859
upvote count: 7
downvote count: 0
has comment: http://stackoverflow.com/comment/128540947
favorite count: 0

http://stackoverflow.com/comment/84739020
score: 1
type: AnswerComment
has text: @RaviSiswaliya that's really not the same thing
type: Comment
comment on: http://stackoverflow.com/a/48867723

http://stackoverflow.com/comment/84751707
comment on: http://stackoverflow.com/q/48873878
has text: `@functools.lru_cache` could help a little
type: Comment
type: QuestionComment
score: 1

http://stackoverflow.com/a/79473116
answers question: http://stackoverflow.com/q/48820375
has comment: http://stackoverflow.com/comment/140157689
score: 0
has body: Somehow nobody has posted the correct answer yet! getchar() reads a single character from stdin. In Python you would do the same thing with sys.stdin.read(1). Your C++ program would become this in Python: import sys while True: ch = sys.stdin.read(1) if (ch == ' '): break print(ch, end='')
type: Answer
upvote count: 1
downvote count: 1

http://stackoverflow.com/comment/84675413
comment on: http://stackoverflow.com/q/48834794
score: 0
type: Comment
type: QuestionComment
has text: Cool. Other than that issue, nothing seems wrong at the first sight. But please try and follow the simple-to-complicated approach, which lets you find bugs more easily.

http://stackoverflow.com/comment/84738656
type: QuestionComment
comment on: http://stackoverflow.com/q/48866879
has text: Are you using OS X or another OS (like linux)?
score: 0
type: Comment

http://stackoverflow.com/comment/84922534
comment on: http://stackoverflow.com/q/48957525
type: Comment
type: QuestionComment
has text: In addition to what others have said, it's probably worth checking [this, regarding `if __name__ == '__main__'`](https://stackoverflow.com/questions/419163/what-does-if-name-main-do) out.
score: 1

http://stackoverflow.com/comment/84732397
type: Comment
type: QuestionComment
has text: You can open the file like `open(file, 'r', encoding="your_encoding")` then while you apply `read()` the result will be a binary object you can decode it using `decode("utf32")`
comment on: http://stackoverflow.com/q/48864581
score: 0

http://stackoverflow.com/comment/84682019
type: QuestionComment
comment on: http://stackoverflow.com/q/48838842
has text: print music_file
score: 0
type: Comment

http://stackoverflow.com/comment/84718259
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48856920
score: 1
has text: Have you read any documentation or searched this site? There are many, many questions related to getting data out of an Entry widget, and the method is documented.

http://stackoverflow.com/comment/84844961
comment on: http://stackoverflow.com/q/48919353
score: 3
type: Comment
has text: What are you trying to check with `if r==(str)`?
type: QuestionComment

http://stackoverflow.com/comment/84655913
comment on: http://stackoverflow.com/a/48826152
has text: My quick test didn't show that doing the `np.squeeze` is "for free", but it might be an artifact of the small `xy` sample.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/a/73150313
has body: on debianoids there is a nice way out of this bug apt install python3-pyqt5
type: Answer
answers question: http://stackoverflow.com/q/48812195
score: 0

http://stackoverflow.com/a/48825674
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48821092
score: 3
answers question: http://stackoverflow.com/q/48821092
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84666907
type: Answer
has comment: http://stackoverflow.com/comment/84667495
has body: First of all, vectorisation makes complex problems much easier. here are a few suggestion to improve what you already have use the userID as as columns in the pivot table, this makes the example for the prediction easier to see NaN stands for missing value, which is conceptually not the same as 0, in this particular case a high negative number will do and will only bee needed when using the cosine similarity function take advantage of pandas advanced features, e.g. to keep the original values but add the predictions, fillna can be used when constructing the similarity dataframe be sure to keep track of the useIds, you can do so by setting the index and columns to df.columns Here is my edited version of the code including predict implementation: ``` import pandas as pd from sklearn.metrics.pairwise import cosine_similarity from sklearn.preprocessing import scale def predict(l): # finds the userIds corresponding to the top 5 similarities # calculate the prediction according to the formula return (df[l.index] * l).sum(axis=1) / l.sum() # use userID as columns for convinience when interpretering the forumla df = pd.read_csv('ratings.csv').pivot(columns='userId', index='movieId', values='rating') similarity = pd.DataFrame(cosine_similarity( scale(df.T.fillna(-1000))), index=df.columns, columns=df.columns) # iterate each column (userID), # for each userID find the highest five similarities # and use to calculate the prediction for that user, # use fillna so that original ratings dont change res = df.apply(lambda col: ' '.join('{}'.format(mid) for mid in col.fillna( predict(similarity[col.name].nlargest(6).iloc[1:])).nlargest(5).index)) print(res) ``` here is a sample of the output userId 1 1172 1953 2105 1339 1029 2 17 39 150 222 265 3 318 356 1197 2959 3949 4 34 112 141 260 296 5 597 1035 1380 2081 33166 dtype: object Edit The code above will recommends the top 5 regardless of whether the user already watched/rated them. to fix this we can reset the values of the origina…

http://stackoverflow.com/comment/84721652
type: AnswerComment
score: 0
type: Comment
has text: followed by similar set {'Batting team': 'RSA', 'scorecardid': 2, 'Commentary1': '/Commentary2', 'name1': 'Junior Dala*', 'runs10': '175', 'status2': 'Ind won by 28 runs', 'overs10': '20', 'runs20': '203', 'series2': 'India tour of South Africa, 2017-18', 'six1': '0', 'balls2': '2', 'overs6': '4', 'overs20': '20', 'Bowling team': 'IND', 'maidens6': '0', 'wickets20': '5', 'fours2': '0', 'progress2': 'complete', 'wickets6': '1', 'matchno2': '1st T20I', 'runs2': '0', 'matchid2': '9', 'runs5': '32', 'wickets5': '0', 'Batting_team_img': 'images/RSA.png', 'teams2': 'RSA vs IND',
comment on: http://stackoverflow.com/a/48858735

http://stackoverflow.com/q/48884965
has answer: http://stackoverflow.com/a/48885047
accepted answer: http://stackoverflow.com/a/48885047
has answer: http://stackoverflow.com/a/48885049
type: Question
has title: Perform operation on all "key":"value" pair in dict and store the result in a new dict object
possible better answer: http://stackoverflow.com/a/48885030
tagged with: arrays
favorite count: 0
upvote count: 8
answer count: 3
has answer: http://stackoverflow.com/a/48885030
tagged with: python
tagged with: dictionary
downvote count: 1
type: AnsweredQuestion
has body: I have a dictionary S as: {1: [11.1, 13, 15.0], 2: [6.9, 8.5, 10.17], 3: [3.86, 4.83, 6.07], 4: [3.86, 4.83, 6.07], 5: [2.31, 2.58, 3.02]} And an array D1_inv as: [0.0248, 0.0296, 0.0357] I need to obtain a product of all the items in S and D1_inv. For example, for S[1]: [round(i*j,4) for i,j in zip(S[1],D1_inv)] Out[282]: [0.2753, 0.3848, 0.5355] and for S[2]: [round(i*j,4) for i,j in zip(S[2],D1_inv)] Out[283]: [0.1711, 0.2516, 0.3631] Can somebody help me create a loop so that I can store all these products in a dict like S?
score: 7
tagged with: loops

http://stackoverflow.com/q/48879453
has body: I have a list called tokens and would like to format this list so that when I print it, it is human readable. The list: tokens = [' ','Hello','World',' ',' ','Welcome','to','this','planet',' '] What I would like the output to look like once formatted: Heading: Hello World Paragraph: Welcome to this planet What I have tried so far: I have first tried to replace the and tags so that when output it shows 'Heading: ' and 'Paragraph: ' instead. I used a FOR loop to loop through all the tokens and find the correct tags to replace: for token in tokens: # comparing strings elif token == ' ': print(token.replace(' ', 'Heading: ')) elif token == ' ': print(token.replace(' ', 'Paragraph: ')) The next part I need to do is print out the sentences between the tags and the tags. For this I thought of creating a method, the general pseudo code is: def between(tokens, tag, endTag) if token is between tag and endTag print the sentence I don't really know how to get this method to work in python and have tried something like this: def between(tokens, tag, endTag): sentence = [] for token in tokens: if(token > tag and token < endTag): sentance.append(token) return sentance but I know the if statement does not make sense and does not work out overall. How can I solve this problem and format the list correctly?
score: 2
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48879537
possible better answer: http://stackoverflow.com/a/48879608
type: Question
accepted answer: http://stackoverflow.com/a/48879537
answer count: 2
downvote count: 0
has title: How to format a list containing tags in python
favorite count: 0
upvote count: 2
has answer: http://stackoverflow.com/a/48879608
tagged with: python

http://stackoverflow.com/comment/84634938
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48815411
has text: currently by " sudo easy_install pip"
score: 0

http://stackoverflow.com/a/48934385
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84879582
has body: Something Like Data from jpp pd.concat([df,pd.DataFrame(df.name.tolist())],1) Out[1596]: A name 0 1 0 1 [1, 2] 1 2 1 1 [3, 4] 3 4 2 2 [5, 6] 5 6 Update df=pd.DataFrame([[1,[1, 2]], [1,[3, 4]], [2,[5, 6,1,1]]], columns=['A','name']) pd.concat([df,pd.DataFrame(df.name.tolist())],1) Out[1602]: A name 0 1 2 3 0 1 [1, 2] 1 2 NaN NaN 1 1 [3, 4] 3 4 NaN NaN 2 2 [5, 6, 1, 1] 5 6 1.0 1.0
type: Answer
score: 6
has comment: http://stackoverflow.com/comment/84878897
accepted answer of: http://stackoverflow.com/q/48934313
downvote count: 0
answers question: http://stackoverflow.com/q/48934313
has comment: http://stackoverflow.com/comment/84879628
upvote count: 6

http://stackoverflow.com/comment/108140130
type: Comment
type: QuestionComment
score: 0
has text: you can disable it after your possess: def switch(): #your commands b1["state"] = "disabled" b2 = Button(text="test", command=switch)
comment on: http://stackoverflow.com/q/48833908

http://stackoverflow.com/comment/85140189
type: Comment
score: 0
comment on: http://stackoverflow.com/a/49027685
has text: I'm glad this helped you to finish the github repo. If I have the time I'll try it!
type: AnswerComment

http://stackoverflow.com/a/48929642
has comment: http://stackoverflow.com/comment/84867813
has comment: http://stackoverflow.com/comment/84868126
score: 26
accepted answer of: http://stackoverflow.com/q/48929124
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48929124
has comment: http://stackoverflow.com/comment/84869306
has comment: http://stackoverflow.com/comment/138109286
type: Answer
has comment: http://stackoverflow.com/comment/84868477
has comment: http://stackoverflow.com/comment/139471326
has body: It's strange that they don't play together nicely... I'm surprised. I'd extend the class to return the reshaped data like you suggested. class ModifiedLabelEncoder(LabelEncoder): def fit_transform(self, y, *args, **kwargs): return super().fit_transform(y).reshape(-1, 1) def transform(self, y, *args, **kwargs): return super().transform(y).reshape(-1, 1) Then using the pipeline should work. pipe = Pipeline([("le", ModifiedLabelEncoder()), ("ohe", OneHotEncoder())]) pipe.fit_transform(['dog', 'cat', 'dog']) https://github.com/scikit-learn/scikit-learn/blob/a24c8b46/sklearn/preprocessing/label.py#L39
upvote count: 26
has comment: http://stackoverflow.com/comment/84883095

http://stackoverflow.com/q/48856112
tagged with: azure
has body: I want to create VM from a disk in azure using python. So I need VHD file of the disk for this purpose. How can I download or obtain the VHD file in azure using python. And on Azure portal, where are the VHD files listed? I referred a video where it was told to search under storage account->containers->vhds, but I did not find anything as such. Then I found this :- blob_service.get_blob_to_path, but it also did not work for me. Can anyone help me with this problem? I want to obtain VHD file of the disk in azure using python.
answer count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84730651
tagged with: azure-storage
tagged with: vhd
tagged with: azure-blob-storage
has comment: http://stackoverflow.com/comment/84733615
type: Question
has title: How to find vhd files in azure using python
score: 0
has comment: http://stackoverflow.com/comment/84731708

http://stackoverflow.com/comment/84800818
comment on: http://stackoverflow.com/q/48897529
has text: Possible duplicate of [Convert numpy.datetime64 to string object in python](https://stackoverflow.com/questions/19502506/convert-numpy-datetime64-to-string-object-in-python)
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48883695
upvote count: 1
tagged with: excel
has title: how to read content of excel to an object in python
type: Question
has body: I have an excel file, named 'list.xlsx' that looks like this: email username password firstname lastname jobtitle ... w@he.com tom 123 Tom White CEO and I want to use this file to fill in this web page: [signuppage] (http://www.enterprisecloudnews.com/webinar.asp?webinar_id=1110&amp;webinar_promo=2587) Here is the error message I get: Traceback (most recent call last): File "C:\Users\whoareyou\AppData\Local\Programs\Python\Python36-32\exceltopage.py", line 10, in formData = {'email':sheet[Bi].value, 'pin':sheet[str(Ci)].value, 'firstname':sheet[str(Di)].value, NameError: name 'Bi' is not defined Below is my python code, but I don't know how to read a line in my excel file to my object, so that my code can work to fill this webpage in: import openpyxl, pyautogui, os, time os.chdir('C:\\users\\whoareyou') wb = openpyxl.load_workbook('list.xlsx') sheet = wb['Sheet1'] nameField = (168,240) #HELP: How do I read the excel file to become the content of person? for i in range(2,10): formData = {'email':sheet[Bi].value, 'pin':sheet[str(Ci)].value, 'firstname':sheet[str(Di)].value,'lastname':sheet[str(Ei)].value, 'job_title':sheet[str(Fi)].value,'company':sheet[str(Gi)].value, 'Address':sheet[str(Hi)].value, 'city':sheet[str(Ii)].value, 'State':sheet[str(Ji)].value,'Zip':sheet[str(Ki)].value, 'country':sheet[str(Li)].value, 'phone':sheet[str(Mi)].value, 'ba':sheet[str(Ni)].value} pyautogui.PAUSE = 0.5 for person in formData: #Give the user a chance to kill the script print('&gt;&gt;&gt;5 SECOND PAUSE TO LET USER PRESS CTRL+C') time.sleep(15) #Wait until the form page has loaded. pyautogui.typewrite('pagedown') print('Entering %s info...' %(person['email'])) pyautogui.click(nameField[0],nameField[1]) #Fill out the email adress Field pyautogui.typerwrite(person['email'] +'\t') #Fill out the Username pyautogui.typerwrite(person['username']+'\t') #Fill out the Create a pin pyautogui.typerwrite(person['pin']+'\t') #Fill out the Create a pin-double pyautogui.typerwrite(person['pin'…
answer count: 1
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48883800
type: UnansweredQuestion
tagged with: python
score: 1

http://stackoverflow.com/comment/84794869
comment on: http://stackoverflow.com/a/48893905
has text: Well, I edited it to try to be clearer. But it's not the important part anyway. The important observation here is that the OP really wants to do a logical AND between arrays (see my comment to his answer). So any loop / enumerate / zip etc. are redundant and confusing.
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/121662440
type: QuestionComment
type: Comment
has text: 3 years later, still a bumpy ride.. (though hopefully less so)
score: 0
comment on: http://stackoverflow.com/q/48843160

http://stackoverflow.com/comment/84661180
type: QuestionComment
score: 7
comment on: http://stackoverflow.com/q/48828658
has text: If you prefix it with an underscore, you are discouraging other users from using it, but you can still call it from places that you know it is appropriate. Is that not enough?
type: Comment

macos
tags question: http://stackoverflow.com/q/48879011
tags question: http://stackoverflow.com/q/48944703
tags question: http://stackoverflow.com/q/48919738
tags question: http://stackoverflow.com/q/48921541
tags question: http://stackoverflow.com/q/48960039
tags question: http://stackoverflow.com/q/48918725
tags question: http://stackoverflow.com/q/48868807
tags question: http://stackoverflow.com/q/48957469
tags question: http://stackoverflow.com/q/48904183
tags question: http://stackoverflow.com/q/48814715
tags question: http://stackoverflow.com/q/48929553
tags question: http://stackoverflow.com/q/48861287
tags question: http://stackoverflow.com/q/48891406
tags question: http://stackoverflow.com/q/48821969
tags question: http://stackoverflow.com/q/48926402
tags question: http://stackoverflow.com/q/48895303
tags question: http://stackoverflow.com/q/48937709
tags question: http://stackoverflow.com/q/48846844
type: Tag
tags question: http://stackoverflow.com/q/48892935
tags question: http://stackoverflow.com/q/48881959
tags question: http://stackoverflow.com/q/48857657
tag name: macos
tags question: http://stackoverflow.com/q/48862093
tags question: http://stackoverflow.com/q/48877266
tags question: http://stackoverflow.com/q/48811568

http://stackoverflow.com/comment/84694114
comment on: http://stackoverflow.com/a/48843765
score: 0
type: AnswerComment
has text: @EnzoBruckmamaan - Do you get notified of updates to answers? I just realized you may not. I have updated and hopefully its a bit clearer.
type: Comment

http://stackoverflow.com/q/48911071
has answer: http://stackoverflow.com/a/48911312
favorite count: 0
has answer: http://stackoverflow.com/a/48911498
has body: Task: Search a multi column dataframe for a value (all values are unique) and return the index of that row. Currently: using get_loc, but it only seems allow a pass of a single column at a time, resulting in quite a ineffective set of try except statements. Although it works is anyone aware of a more effective way to do this? df = pd.DataFrame(np.random.randint(0,100,size=(4, 4)), columns=list('ABCD')) try: unique_index = pd.Index(df['A']) print(unique_index.get_loc(20)) except KeyError: try: unique_index = pd.Index(df['B']) print(unique_index.get_loc(20)) except KeyError: unique_index = pd.Index(df['C']) print(unique_index.get_loc(20)) Loops don't seem to work because of the KeyError that is raised if a column doesn't contain a value. I've looked at functions such as .contains or .isin but it's the location index that i'm interested in.
score: 9
answer count: 5
has comment: http://stackoverflow.com/comment/84828674
tagged with: python
tagged with: indexing
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48911291
has comment: http://stackoverflow.com/comment/84828708
type: Question
has answer: http://stackoverflow.com/a/48911437
upvote count: 9
has title: More effective way to use pandas get_loc?
has answer: http://stackoverflow.com/a/48911370
tagged with: pandas
accepted answer: http://stackoverflow.com/a/48911291
downvote count: 0
possible better answer: http://stackoverflow.com/a/48911312

http://stackoverflow.com/comment/84713671
has text: @har07 I have updated the XML to include the minimal XML.
comment on: http://stackoverflow.com/q/48847177
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48893492
has comment: http://stackoverflow.com/comment/84797120
type: Answer
has body: I assume you must be using pyqtdeploy version 2.x, which differs in some important ways from pyqtdeploy 1.x. Unfortunately, the documentation currently shown here has not been updated, and refers to version 1.3.2. In the meantime, I suggest you download the source code and open up docs/html/index.html, so you can read the proper documentation for version 2.x. I will quote here the section which deals with the specific problem regarding the Build Tab: Differences from Version 1 There have been a number of changes to pyqtdeploy since v1. Most of these changes are related to the supporting tools rather than the GUI. Project files created for v1 are automatically updated by later versions. [...] The pyqtdeploycli program has been removed. The build functionality has been replaced by the new pyqtdeploy-build program. The Build tab of the pyqtdeploy GUI has been removed. The sole purpose of the GUI is now to create and modify a project file. [...]
score: 1
has comment: http://stackoverflow.com/comment/88451008
upvote count: 1
has comment: http://stackoverflow.com/comment/84795678
answers question: http://stackoverflow.com/q/48882283
accepted answer of: http://stackoverflow.com/q/48882283
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84838103
comment on: http://stackoverflow.com/q/48913757
has text: @ScottBoston, Good idea! :) I will make some up for you guys
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84783600
type: Comment
comment on: http://stackoverflow.com/a/48887880
score: 0
type: AnswerComment
has text: I know that 0<=i<=3 and 0<=j<=6. And because it's not a square matrix, it won't have diagonals per-se. But I don't know what is the value of M[i,j] in terms of i and j.

http://stackoverflow.com/a/48957781
has comment: http://stackoverflow.com/comment/84923187
has comment: http://stackoverflow.com/comment/84923072
has comment: http://stackoverflow.com/comment/84923150
score: 1
upvote count: 2
downvote count: 1
answers question: http://stackoverflow.com/q/48957745
has body: arr = [0]*len(df) for i, v in enumerate([c for c in df.columns if not isinstance(c,str)]): arr = arr + df[v]*v df['sumproduct'] = arr or even: cols = [c for c in df.columns if not isinstance(c, str)] # or as @ilia cols = pd.to_numeric(df.columns,errors='coerce').dropna() df[cols].apply(lambda x: x*x.name).sum(axis='columns')
has comment: http://stackoverflow.com/comment/84923015
type: Answer
has comment: http://stackoverflow.com/comment/84923177
has comment: http://stackoverflow.com/comment/84923111
has comment: http://stackoverflow.com/comment/84922801

http://stackoverflow.com/q/48873890
tagged with: pandas
answer count: 1
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48874056
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84751888
has title: how to rename label X in a merged/joined data-frame in python
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84751779
upvote count: 1
type: Question
has body: When I am trying to merge the two df using: merged = pd.merge(left=df1, left_index=True, right=df2, right_index=True, how='inner') it results in a merged df with headers X and Y based on the df1/df2 which is as expected. for further/future ease of read, how can i set the label X to be something else?

http://stackoverflow.com/comment/84902019
has text: @AbhishekGupta - You need same columns names, what return `print ((df1.index == df2.index).all())` and `print ((df1.columns == df2.columns).all())` ? Both has to be True.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48926933

http://stackoverflow.com/a/48924443
has body: This will save a file as Group_name.pdf in your working directory. You may change the path as you wish. # Columns to get histograms names = list(data.columns) names.remove('Group') print(names) ['Parameter_1', 'Parameter_2', 'Parameter_3', 'Weight'] # plotting for i in (data['Group'].unique()): fig, ax = plt.subplots(len(names),1) group_data = data.loc[data['Group']==i] for number, col_name in enumerate(names): ax[number].hist(data[col_name]); ax[number].set_title("Histogram for " + col_name) plt.tight_layout() plt.savefig(i+'.pdf') # provide a valid path
answers question: http://stackoverflow.com/q/48923495
has comment: http://stackoverflow.com/comment/84866753
has comment: http://stackoverflow.com/comment/84923909
score: 0
has comment: http://stackoverflow.com/comment/84868066
has comment: http://stackoverflow.com/comment/84865888
type: Answer

http://stackoverflow.com/q/48816612
has comment: http://stackoverflow.com/comment/84637339
has body: I need to send a username , password and message to a tcp server to get an output that I need for a code challenge that i'm working on. I have been given this set of instructions: Connect to alien server ('localhost', 10000), Then send USER followed by aliensignal, Then send PASS followed by unlockserver, Next SEND followed by moonbase. Then send END and if all followed key will provided. I have written a python code that does exactly what it says: import socket clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect(('localhost', 10000)) clientsocket.send('USER: aliensignal') clientsocket.send('PASS: unlockserver') clientsocket.send('SEND: moonbase') clientsocket.send('END') data = clientsocket.recv(4096) print(data) But i get an output that says: ############# DARKSTORE KEY SERVER SPEC ############################ Set username then password. Once set send name then end connection and you access key will be sent. USER: Tell server you will be sending username PASS: Tell server you will be sending password SEND: Tell server you will be sending data. (Must be authenticated) END: Tell server to end transaction. ###################################################### It gives me this output whether or not I send the username and password. Does anyone know why this is happening?
answer count: 1
downvote count: 0
has title: Use socket to send username and password to tcp server
favorite count: 0
tagged with: sockets
score: 6
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/84637205
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49094345
type: Question
has comment: http://stackoverflow.com/comment/84637272
has comment: http://stackoverflow.com/comment/84637162
accepted answer: http://stackoverflow.com/a/49094345

hex
tags question: http://stackoverflow.com/q/48826099
tags question: http://stackoverflow.com/q/48893881
tag name: hex
type: Tag

http://stackoverflow.com/comment/84681704
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48838390
has text: I am sure it is plugged in. In fact, I have a labview program works, and try to write python to control it too. Strange thing is that after run the labview program with no problem, then I run python code, and the error showed up. Then I run labview program again, and it didn't work too. Then I have to turn off the DC power supply, and turn on again, the labview program works again. I am not sure what is going on.
score: 0

http://stackoverflow.com/q/48900149
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/27831228
tagged with: python
score: -1
downvote count: 1
type: Question
duplicate of: http://stackoverflow.com/q/31948285
upvote count: 0
has title: Showing a progress bar on front-end until a processing function finish executing in back-end in flask web application
tagged with: flask
tagged with: progress-bar
linked to: http://stackoverflow.com/q/35437668
answer count: 1
has answer: http://stackoverflow.com/a/48902960
has body: I'm developing an online GNSS post processing portal for my office website. In the application user have to enter 2 files. I have implemented a html form to get relevant information from user. Generated form Once user submitted the files, Post-processing function will be executed in the back-end. Since the function is very long I want to display a background progress bar. Following code represent the post processing function. @app.route('/pp.php', methods=['GET', 'POST']) def pp(): pp = MyForm() target = os.path.join(APP_ROOT, 'images/') print(target) if not os.path.isdir(target): os.mkdir(target) for obsfile in request.files.getlist("obsfile"): print(obsfile) filename = obsfile.filename destination = "/".join([target, filename]) print(destination) obsfile.save(destination) for navfile in request.files.getlist("navfile"): print(navfile) filename = navfile.filename destination = "/".join([target, filename]) print(destination) navfile.save(destination) a=obsfile.filename b=navfile.filename command='rnx2rtkp -p 0 -m '+pp.textarea.data+' -n -o out.pos '+a+' '+b os.system(command) email_user = '*******' email_password = '******' email_send = pp.email.data subject = 'subject' msg = MIMEMultipart() msg['From'] = email_user msg['To'] = email_send msg['Subject'] = subject body = 'This is your Post-Processed position file' msg.attach(MIMEText(body,'plain')) filename='out.pos' attachment =open(filename,'rb') part = MIMEBase('application','octet-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('Content-Disposition',"attachment; filename= "+filename) msg.attach(part) text = msg.as_string() server = smtplib.SMTP('smtp.gmail.com',587) server.starttls() server.login(email_user,email_password) server.sendmail(email_user,email_send,text) server.quit() return render_template('pp.php', pp=pp) please let me know any suggestions that might help to resolve this issue
favorite count: 0
duplicate of: http://stackoverflow.com/q/35437668

http://stackoverflow.com/comment/84819096
comment on: http://stackoverflow.com/a/48906154
score: 1
has text: `myreader = ...; content = list(myreader); minTemp = min(elem[0] for elem in content); maxTemp = max(elem[2] for elem in content)`
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/123411684
has text: @CharlieParker some torch operations only work when the index order of the tensor matches the order in memory, the coding of the operation assumes consistency between both.
comment on: http://stackoverflow.com/a/48922607
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84831241
type: QuestionComment
has text: Thanks for the quick response, trying to decode 'w' causes this error: AttributeError: 'str' object has no attribute 'decode'
type: Comment
comment on: http://stackoverflow.com/q/48911850
score: 0

http://stackoverflow.com/q/48848061
accepted answer: http://stackoverflow.com/a/48848630
type: AnsweredQuestion
downvote count: 0
type: Question
score: 3
has body: I keep getting this error: ImportError: cannot import name 'QWebView' ...for this bit of code: import sys from PyQt5.QtCore import QUrl from PyQt5.QtWidgets import QApplication from PyQt5.QtWebEngineWidgets import QWebPage -I'm on a Mac running High Sierra 10.13.3 -I installed Python 3.6.4 -Installed PyQt5 (did this several times, including using HomeBrew) I'm pretty sure everything is installed correctly cause when I run python3 -m pip install PyQt5 it tells me Requirement already satisfied: MacBook-Pro-3:~ ericj36$ python3 -m pip install PyQt5 Requirement already satisfied: PyQt5 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages Requirement already satisfied: sip&lt;4.20,&gt;=4.19.4 in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages (from PyQt5) The full error I get when I try to run my code is: ...line 4, in &lt;module&gt; from PyQt5.QtWebEngineWidgets import QWebView ImportError: cannot import name 'QWebView' So what could be happening here? What am I doing wrong? (I'm new to Python - but not to development.) Any help would be greatly appreciated.
tagged with: python
has title: Python PyQt5 cannot import name 'QWebView'
favorite count: 0
has answer: http://stackoverflow.com/a/48848630
tagged with: pyqt5
has comment: http://stackoverflow.com/comment/84700126
answer count: 1
upvote count: 3

http://stackoverflow.com/a/48838060
downvote count: 0
type: Answer
score: 1
upvote count: 1
has body: Assuming your collection name as: youCollection field name to be converted from string to date: date var records = db.youCollection.find(); records.forEach(function(doc) { var dateStr = doc.date; if(typeof dateStr === "string") { var date = new Date(dateStr); db.youCollection.update({_id: doc._id}, {$set: {date: date}}) }}) This will convert date of "2018-02-17T05:01:32.028Z" format to ISODate("2018-02-17T05:01:32.028Z")
answers question: http://stackoverflow.com/q/48837505

http://stackoverflow.com/a/48809759
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48807861
type: Answer
answers question: http://stackoverflow.com/q/48807861
has body: One thing is for sure, multicast is basically sending UDP packages and you have to keep listening for new packages. That is true even for TCP protocol based communication. When you use low level interfaces for network communication, like socket is, it's up on both sides to define application level protocol. That means, you define how receiving party concludes that message is complete. This is because message could get split in multiple parts/packets that get through the network. So receiving side has to assemble them in a proper way and then check if the message is whole. After that you push it up through the pipeline of processing messages or whatever you do in receiving side. When using UDP, receiving side doesn't know if there is any packet on its way, so it just does try to recvfrom 1024 bytes and finishes. It doesn't know and should not care if there is more data on it's way. It's up to you to take care of that.
score: 0

http://stackoverflow.com/q/48941116
has answer: http://stackoverflow.com/a/48941162
score: 46
type: Question
has body: In NodeJS's npm you can create a package.json file to track your project dependencies. When you want to install them you just run npm install and it looks at your package file and installs them all with that single command. When distributing my code, does python have an equivalent concept or do I need to tell people in my README to install each dependency like so: pip install package1 pip install package2 Before they can use my code?
has answer: http://stackoverflow.com/a/48941150
favorite count: 0
has answer: http://stackoverflow.com/a/67526207
possible better answer: http://stackoverflow.com/a/67650340
answer count: 5
linked to: http://stackoverflow.com/q/50977743
linked to: http://stackoverflow.com/q/49519208
tagged with: python
has title: Does python pip have the equivalent of node's package.json?
tagged with: node.js
tagged with: npm
tagged with: pip
downvote count: 1
upvote count: 47
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48941163
accepted answer: http://stackoverflow.com/a/48941163
has answer: http://stackoverflow.com/a/67650340
linked to: http://stackoverflow.com/q/46330327

http://stackoverflow.com/comment/120026686
has text: But you need a training dataset. If this guy has 30k reviews and he has no labels, there's no training data available.
type: QuestionComment
comment on: http://stackoverflow.com/q/48961822
score: 0
type: Comment

flask-sqlalchemy
tags question: http://stackoverflow.com/q/48951285
tags question: http://stackoverflow.com/q/48858449
tags question: http://stackoverflow.com/q/48820336
tags question: http://stackoverflow.com/q/48851097
tags question: http://stackoverflow.com/q/48846288
type: Tag
tags question: http://stackoverflow.com/q/48836082
tags question: http://stackoverflow.com/q/48825957
tags question: http://stackoverflow.com/q/48852513
tags question: http://stackoverflow.com/q/48946552
tags question: http://stackoverflow.com/q/48938945
tags question: http://stackoverflow.com/q/48849701
tags question: http://stackoverflow.com/q/48896993
tags question: http://stackoverflow.com/q/48849087
tags question: http://stackoverflow.com/q/48867212
tag name: flask-sqlalchemy
tags question: http://stackoverflow.com/q/48890955
tags question: http://stackoverflow.com/q/48904160

http://stackoverflow.com/a/48840788
answers question: http://stackoverflow.com/q/48840699
has comment: http://stackoverflow.com/comment/84686237
has comment: http://stackoverflow.com/comment/84686310
has comment: http://stackoverflow.com/comment/84686415
score: 1
has comment: http://stackoverflow.com/comment/84685738
upvote count: 1
has comment: http://stackoverflow.com/comment/84686438
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84686046
has comment: http://stackoverflow.com/comment/84685728
has comment: http://stackoverflow.com/comment/84685972
has comment: http://stackoverflow.com/comment/84686358
has comment: http://stackoverflow.com/comment/84686194
has comment: http://stackoverflow.com/comment/84686132
type: Answer
has comment: http://stackoverflow.com/comment/84685717
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48840699
has body: Something like this should work: import pandas as pd import matplotlib.pyplot as plt # Create small dummy data set, import your real data here instead data = pd.DataFrame([['2009-10', 89], ['2009-10', 60], ['2010-11', 85]], columns=['Year', 'Score']) plt.figure() data[data['Year'] == '2009-10'].boxplot(column='Score') plt.savefig('plot.png')

http://stackoverflow.com/comment/84751537
type: QuestionComment
has text: @internet_user in Python 3.6, you can use `random.choices` for sampling with replacement... before that, you'd have to do something like `[random.choice(list_of_vals) for _ in range(n)]` instead of `random.choices(list_of_vals, k=n)`
comment on: http://stackoverflow.com/q/48873797
score: 0
type: Comment

http://stackoverflow.com/q/48956904
tagged with: python
type: AnsweredQuestion
upvote count: 0
has body: I'm only in secondary school so I'm not even competent at coding, but my school website is down and I cant find some answers to questions in python coding. There's probably a really simple answer, but I cant remember how to print a variable. the variable I simply a string of numbers I am sorting and I cant fid out how to print the variable. can anyone show me what to write to print the variable?
has comment: http://stackoverflow.com/comment/84920723
has title: How do you print variables in Python?
type: Question
has comment: http://stackoverflow.com/comment/84920942
has comment: http://stackoverflow.com/comment/84920743
accepted answer: http://stackoverflow.com/a/48956948
has comment: http://stackoverflow.com/comment/84920849
has comment: http://stackoverflow.com/comment/84921003
downvote count: 8
has answer: http://stackoverflow.com/a/48956948
has comment: http://stackoverflow.com/comment/84921005
has comment: http://stackoverflow.com/comment/84921634
answer count: 1
tagged with: variables
has comment: http://stackoverflow.com/comment/84920949
favorite count: 0
has comment: http://stackoverflow.com/comment/84921027
score: -8
has comment: http://stackoverflow.com/comment/84920850

http://stackoverflow.com/a/48908160
score: 8
has body: The error is to "put the test data through the same pipeline". Basically i was doing: data_prepared = full_pipeline.fit_transform(train_set) lin_reg = LinearRegression() lin_reg.fit(data_prepared, labels) some_data = train_set.iloc[:5] some_data_prepared = full_pipeline.fit_transform(some_data) lin_reg.predict(some_data_prepared) # =&gt; error because mismatching shapes The problematic line is: some_data_prepared = full_pipeline.fit_transform(some_data) By doing fit_transform, I'll fit the LabelBinarizer to a set containing only 3 labels. Instead I should do: some_data_prepared = full_pipeline.transform(some_data) This way I'm using the pipeline fitted by the full set (train_set) and transform it in the same way. Thanks @Vivek Kumar
accepted answer of: http://stackoverflow.com/q/48891538
type: Answer
downvote count: 0
upvote count: 8
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48891538

http://stackoverflow.com/comment/84937094
type: Comment
has text: Hi, In the aSUB.connect() it throws error saying protocol not supported
comment on: http://stackoverflow.com/a/48965367
type: AnswerComment
score: 0

http://stackoverflow.com/q/48861456
tagged with: python-3.x
has title: What is the significance of Min and Max in below python function
has body: Can someone explain why the min and max is used in the below function def rgb(r, g, b): round = lambda x: min(255, max(x, 0)) return ("{:02X}" * 3).format(round(r), round(g), round(b))
tagged with: python
downvote count: 4
has answer: http://stackoverflow.com/a/48861552
type: AnsweredQuestion
upvote count: 0
score: -4
has comment: http://stackoverflow.com/comment/84725899
type: Question
has comment: http://stackoverflow.com/comment/84725903
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48861552

dialogflow-es
tag name: dialogflow-es
tags question: http://stackoverflow.com/q/48922795
type: Tag

http://stackoverflow.com/comment/84894368
type: AnswerComment
score: 0
has text: but, my data record = 1 bilion data, how to find and remove that? can you help me? and what about the other solution?
comment on: http://stackoverflow.com/a/48919847
type: Comment

django-queryset
tags question: http://stackoverflow.com/q/48913008
tags question: http://stackoverflow.com/q/48830854
tags question: http://stackoverflow.com/q/48905283
tag name: django-queryset
tags question: http://stackoverflow.com/q/48885254
tags question: http://stackoverflow.com/q/48852092
tags question: http://stackoverflow.com/q/48832294
type: Tag
tags question: http://stackoverflow.com/q/48844877
tags question: http://stackoverflow.com/q/48841782
tags question: http://stackoverflow.com/q/48898672
tags question: http://stackoverflow.com/q/48902303
tags question: http://stackoverflow.com/q/48850438

http://stackoverflow.com/a/48848431
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48848335
type: Answer
upvote count: 2
has body: I believe tuples and lists are limited by the size of the machine's virtual memory, unless you're on a 32 bit system in which case you're limited by the small word size. Also, lists are dynamically resized by... I believe about 12% each time they grow too small, so there's a little overhead there as well. If you're concerned you're going to run out of virtual memory, it might be a good idea to write to a file or files instead.

http://stackoverflow.com/comment/84861950
comment on: http://stackoverflow.com/a/48927810
score: 0
type: Comment
has text: Interesting approach! Seems like the "more Pythonic" version that OP was asking for, +1
type: AnswerComment

http://stackoverflow.com/comment/126876277
type: Comment
score: 1
comment on: http://stackoverflow.com/a/67650340
has text: This should be the accepted answer because simply `pip install -r requirements.txt` does not compare to the possibilities of the `package.json` at all.
type: AnswerComment

http://stackoverflow.com/a/48922998
answers question: http://stackoverflow.com/q/48922716
has body: Is it possible, but need if-else in custom function: def f(x): a = x.mean() return a if isinstance(a, (float, int)) else list(a) df = df.groupby('A').agg(f) print (df) B C D A bar 0.306945 0.147823 [0.306944666667, 0.147822666667] foo -0.344944 0.505811 [-0.3449438, 0.5058112] df = df.groupby('A').agg(lambda x: x.mean()) print (df) B C D A bar 0.306945 0.147823 NaN foo -0.344944 0.505811 NaN
upvote count: 2
type: Answer
score: 2
downvote count: 0

http://stackoverflow.com/a/48871753
upvote count: 1
has comment: http://stackoverflow.com/comment/84832731
answers question: http://stackoverflow.com/q/48852907
downvote count: 0
has comment: http://stackoverflow.com/comment/84869447
score: 1
has comment: http://stackoverflow.com/comment/84891199
type: Answer
has comment: http://stackoverflow.com/comment/84786741
has body: From your code prediction = tf.layers.dense(net, 2, activation=tf.nn.sigmoid) I infer that you have a two class classification problem and the activation function of your output layer is the sigmoid function. However, as your loss function you are using the tf.losses.softmax_cross_entropy function. So first of all I would suggest to use the tf.losses.sigmoid_cross_entropy function. Note that this function (and also the tf.losses.softmax_cross_entropy function) expects the (unscaled) logits as an input. So in your case, the result of your final layer before applying the sigmoid non-linearity. Hence, I would recommend to change the following line prediction = tf.layers.dense(net, 2, activation=tf.nn.sigmoid) to logits = tf.layers.dense(net, 2) prediction = tf.nn.sigmoid(logits) # this line is only needed if you want to use predictions somewhere else and then loss = tf.losses.sigmoid_cross_entropy(onehot_labels=labels, logits=logits) Maybe this already solves your problem. If not, what learning rate are you using? I usually get this error if the learning rate is too large.

http://stackoverflow.com/q/48875213
tagged with: python-3.5
upvote count: 0
answer count: 1
tagged with: python-importlib
favorite count: 0
has body: I use this to import a function in 2.7 which works: def import_x(): import os import imp directory = os.path.dirname(os.path.realpath(__file__)) os.environ['__PYTHON_SYS_PATH_FOR_TESTFOLDER__'] = directory fp, pathname, description = imp.find_module('test', [ directory ]) if fp is not None: try: x = imp.load_module('test', fp, os.path.realpath(pathname), description) finally: fp.close() return x test = import_x() But I struggle to make this work in 3.5. Any idea please?
type: UnansweredQuestion
tagged with: imp
has title: python: import function doesnt work in 3.5
tagged with: python
has answer: http://stackoverflow.com/a/48875336
downvote count: 1
type: Question
score: -1
tagged with: python-2.7

http://stackoverflow.com/q/48827285
score: 5
upvote count: 5
has body: I have the following dataframe where I want to assign the bottom 1% value to a new column. When I do this calculation with using the ".loc" notification, it takes around 10 seconds for using .loc assignment, where the alternative solution is only 2 seconds. df_temp = pd.DataFrame(np.random.randn(100000000,1),columns=list('A')) %time df_temp["q"] = df_temp["A"].quantile(0.01) %time df_temp.loc[:, "q1_loc"] = df_temp["A"].quantile(0.01) Why is the .loc solution slower? I understand using the .loc solution is safer, but if I want to assign data to all indices in the column, what can go wrong with the direct assignment?
tagged with: pandas
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48828091
favorite count: 0
has comment: http://stackoverflow.com/comment/84660494
tagged with: python
has title: Using .loc in pandas slows down calculation
linked to: http://stackoverflow.com/q/27596832
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84664829
has answer: http://stackoverflow.com/a/48828091
type: Question
has comment: http://stackoverflow.com/comment/84661142

http://stackoverflow.com/q/48903666
type: Question
tagged with: split
downvote count: 5
has body: I have a list from which I want to extract a number which corresponds to totalsec. I proceeded with the split method to constitute a list of list and then extract the totalsec but I got an error "list has no attribute split". Here is my list: ['nbresets:0,totalsec:14,lossevtec:0,lossevt:0,sevlossec:0,sevloss:0,paclosevtec:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0,paclosevt:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0,dellosevtec:0:0:0:0:0:0:0:0:0:0:0,dellosevt:0:0:0:0:0:0:0:0:0:0:0,dursevlossec:0:0:0:0:0:0:0:0:0:0:0:0,dursevloss:0:0:0:0:0:0:0:0:0:0:0:0,nbfailures:0,notif:2'] the number I want to extract from this list is 14. Please if you have any Idea how to do that please help!
upvote count: 0
has answer: http://stackoverflow.com/a/48905111
favorite count: 0
has answer: http://stackoverflow.com/a/48903790
has answer: http://stackoverflow.com/a/48903746
tagged with: python
possible better answer: http://stackoverflow.com/a/48903790
accepted answer: http://stackoverflow.com/a/48903746
answer count: 4
has answer: http://stackoverflow.com/a/48904008
type: AnsweredQuestion
score: -5
has title: Extracting a determined value from a list
has comment: http://stackoverflow.com/comment/84812708

http://stackoverflow.com/comment/84673624
has text: Thanks a lot, it worked. Never used Windows Forms before so had to search a bit before making what I wanted.
type: Comment
type: AnswerComment
comment on: http://stackoverflow.com/a/48833003
score: 0

http://stackoverflow.com/comment/84697294
comment on: http://stackoverflow.com/q/48846256
score: 0
type: Comment
type: QuestionComment
has text: Hi! Please include input data and fix indent in code below #Market Cap Calculation. And it will be useful to show complete error stack.

http://stackoverflow.com/a/48920099
accepted answer of: http://stackoverflow.com/q/48918438
score: 0
answers question: http://stackoverflow.com/q/48918438
has comment: http://stackoverflow.com/comment/84861297
has comment: http://stackoverflow.com/comment/84871120
type: AcceptedAnswer
type: Answer
has body: It depends how you want to specify the item you want. I am going to assume that you want to specify the text you want as that which follows the p element with class 'description_text'. But the method I'm describing works more generally. First find an element that encloses the one you want to find. In this case, I've chosen the div. Then browse through that element's descendants until you see the one that immediately precedes the one you want. For illustrative purposes (and my own laziness) I haven't written this in the form of a loop. Use items = div.descendants to get an iterator in items. Then use next to obtain each descendant of the div in turn, in item. If the item.name is empty then the item is a string, otherwise, item.name names the tag. When you see the p tag mentioned above you know that the next item will be the text item you actually want. >>> import bs4 >>> soup = bs4.BeautifulSoup(open('bueno.htm').read(), 'lxml') >>> div = soup.find('div') >>> items = div.descendants >>> item = next(items) >>> item.name >>> item ' ' >>> item = next(items) >>> item.name 'h2' >>> item TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT” HD >>> item = next(items) >>> item.name >>> item 'TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT” HD' >>> item = next(items) >>> item.name >>> item ' ' >>> item = next(items) >>> item.name 'p' >>> item >>> item = next(items) >>> item.name >>> item ' *********I WANT TO EXTRACT THIS TEXT HEAR!!!!!!*************************************************** \n '

http://stackoverflow.com/a/48886496
upvote count: 26
has comment: http://stackoverflow.com/comment/84781932
has comment: http://stackoverflow.com/comment/84868572
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84782011
accepted answer of: http://stackoverflow.com/q/48880646
has comment: http://stackoverflow.com/comment/84783424
type: Answer
has comment: http://stackoverflow.com/comment/137051606
answers question: http://stackoverflow.com/q/48880646
downvote count: 1
score: 25
has body: Well, since this question is upvoted but my flag as duplicated question wasn't accepted I will post here the same exact answer I already posted for a similar question: You can use pickle to save cookies as text file and load it after: def save_cookie(driver, path): with open(path, 'wb') as filehandler: pickle.dump(driver.get_cookies(), filehandler) def load_cookie(driver, path): with open(path, 'rb') as cookiesfile: cookies = pickle.load(cookiesfile) for cookie in cookies: driver.add_cookie(cookie) With a script like: from selenium import webdriver from afile import save_cookie driver = webdriver.Chrome() driver.get('http://website.internets') foo = input() save_cookie(driver, '/tmp/cookie') What you can do is: Run this script On the (selenium's) browser, go to the website, login Go back to your terminal, type anything hit enter. Enjoy your cookie file at /tmp/cookie. You can now copy it into your code repo and package it into your app if needed. So, now, in your main app code: from afile import load_cookie driver = webdriver.Chrome() load_cookie(driver, 'path/to/cookie') And you are now logged.
has comment: http://stackoverflow.com/comment/84782260
has comment: http://stackoverflow.com/comment/84783518

http://stackoverflow.com/q/48829227
type: Question
score: 1
accepted answer: http://stackoverflow.com/a/48829296
tagged with: python-2.7
answer count: 2
downvote count: 0
favorite count: 0
has title: change elements in a list of lists to match a different list in python
tagged with: python
has answer: http://stackoverflow.com/a/48829296
possible better answer: http://stackoverflow.com/a/48829533
type: AnsweredQuestion
tagged with: list
has answer: http://stackoverflow.com/a/48829533
has body: I am using Python 2.7 and have a list of lists: my_list_0 = [ ['X00001', 1123477, 1.25, 'Yes', 'No', 11.53, 3.23, 0.25, 3.0025], ['X00002', 1125251, 0.22, 'Yes', 'No', 22.83, 3.6, 0.5, 0.0012], ['X00003', 1125433, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15, 12.0014536], ['X00003', 1125435, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15, 12.0014536], ['X00003', 1125436, 966.33, 'Yes', 'No', 1.8, 3.8, 0.36, 30.12121], ['X00004', 1125437, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15, 12.0014536], ['X00007', 1125438, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15, 12.0014536], ['X00001', 1125439, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15, 12.0014536], ['X00004', 1231254, 1.3, 'Yes', 'No', 21.83, 3.6, 0.5, 1005.000336669], ['X00008', 2520250, 54.02, 'Yes', 'No', 1.83, 3.8, 0.01, 82.0000001], ['X00005', 3202020, 966.33, 'Yes', 'No', 1.8, 3.8, 0.36, 0.000001200012], ['X00006', 3215204, 1.36, 'Yes', 'No', 1.86, 3.65, 0.15, 0.1234565], ['X00007', 4561230, 6.33, 'Yes', 'No', 1.83, 66.22, 0.1, 1.1111111], ['X00009', 5721365, 1.25, 'No', 'No', 11.53, 3.23, 0.25, 11.1110001], ['X00010', 8520525, 6.33, 'Yes', 'No', 1.83, 66.22, 0.1, 20.000156], ['X00110', 8520725, 6.33, 'Yes', 'No', 1.83, 66.22, 0.1, 20.000156], ['X00010', 8520825, 6.33, 'Yes', 'No', 1.83, 66.22, 0.1, 20.000156], ['X00012', 8520123, 966.33, 'Yes', 'No', 1.8, 3.8, 0.36, 30.12121], ['X00011', 9536122, 54.01, 'Yes', 'No', 1.83, 3.8, 0.01, 15.2312456], ['X00015', 1212021, 0.333, 'No', 'No', 1.83, 3.8, 0.01, 0], ['X00015', 1222221, 0.333, 'No', 'No', 1.83, 3.8, 0.01, 0], ['X00013', 9654123, 4.1, 'No', 'No', 1.83, 3.8, 0.01, 90.01], ['X00014', 2021230, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15, 0.00001], ['X00017', 3322123, 1.23, 'Yes', 'Yes', 1.88, 1.25, 1.12, 0.0002], ['X00016', 9531450, 23.15, 'Yes', 'Yes', 1.83, 3.25, 0.12, 30.123], ['X00020', 3625252, 1.23, 'Yes', 'No', 1.86, 3.65, 0.15, 0.02123589], ['X00009', 5721777, 1.25, 'No', 'No', 11.53, 3.23, 0.25, 11.1110001], ['X00018', 1205203, 1.87, 'Yes', 'No', 1.88, 1.25, 1.12, 89.21233456987], ['X00019', 1124521, 0…
upvote count: 1

http://stackoverflow.com/comment/84692418
has text: (B[:,None,:] == A).all(axis=-1).argmax(axis=0) works very good, thx. :)
comment on: http://stackoverflow.com/a/48843836
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48953784
type: AcceptedAnswer
upvote count: 1
type: Answer
accepted answer of: http://stackoverflow.com/q/48953689
downvote count: 0
answers question: http://stackoverflow.com/q/48953689
has body: io.BytesIO() is the correct type to use to create a seekable in-memory file object containing binary data. However, you made the mistake of reading out the bytes data from your io.BytesIO() file object, and passing those in instead of the actual file object. Don't read, pass in the actual io.BytesIO file object with the binary data read from stdin: buf = io.BytesIO(args.input_file.buffer.read()) r = DataFileReader(buf, DatumReader()) I passed in the args.input_file.buffer data directly, assuming that args.input is the TextIOWrapper instance that decodes the stdin bytes, and .buffer is the underlying BufferedReader instance providing the raw binary data. There is no point in decoding this data as Latin-1, then encoding as Latin-1 again. Just pass the bytes on.
score: 1
has comment: http://stackoverflow.com/comment/84917316

http://stackoverflow.com/q/48827495
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
accepted answer: http://stackoverflow.com/a/48827677
favorite count: 0
type: Question
has body: So I have a filtered MultiIndexed pandas dataframe, df, and I want to get rid of the indexes which have been filtered out. How can I do this? The code I used to filter is df.groupby(level=0).filter(lambda x : len(x) == 2). Thanks, Jack
tagged with: python
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48827677
has title: How to Delete Redundant Indexes from Filtered Dataframe

http://stackoverflow.com/comment/84746454
score: 0
type: Comment
type: QuestionComment
has text: @Stev No, I just sorted it differently to include a mistake
comment on: http://stackoverflow.com/q/48870463

http://stackoverflow.com/a/48928097
type: Answer
answers question: http://stackoverflow.com/q/48927604
has body: Based on the strings you provided, you could iterate over the dictionaries, get value for "url" and use the following regex ([^\/]*)$ Explanation: () - defines capturing group [^\/] - Match a single character not present after the ^ \/ - matches the character / literally (case sensitive) * - Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy) $ - asserts position at the end of the string, or before the line terminator right at the end of the string (if any) For example: for record in records: print(re.search("([^\/]*)$", record['url']).group(1)) In this case, we are exploiting the fact that the filename occurs at the end of the string. Using the $ anchor makes the only valid match one that terminates the string. If you wanted to do this to a dictionary cast as a string, you could by changing the ending condition. Like so ([^\/]*?)\",. Now ", terminates the match (note the \ to escape the ". See https://regex101.com/r/k9VwC6/25 Finally, if we weren't so lucky that the capturing group was at the end of the string (meaning we couldn't use $) we could use a negative look behind. You can read up on those here.
has comment: http://stackoverflow.com/comment/84923983
has comment: http://stackoverflow.com/comment/84924995
has comment: http://stackoverflow.com/comment/84924205
score: 0
has comment: http://stackoverflow.com/comment/84924092

http://stackoverflow.com/q/48959183
score: 0
has body: I want to get [[1,2,4], [11, 12, 14], [21, 22, 24]] from [[1,2,3,4], [11, 12, 13, 14], [21, 22, 23, 24]]. What is an elegant way? My real problem is a 100000*17 2d list. Thanks.
has comment: http://stackoverflow.com/comment/84925163
has answer: http://stackoverflow.com/a/65920608
has answer: http://stackoverflow.com/a/48959253
answer count: 5
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84925140
tagged with: python
has answer: http://stackoverflow.com/a/48959338
has answer: http://stackoverflow.com/a/48963968
has answer: http://stackoverflow.com/a/48959284
tagged with: list
type: Question
has title: python how to skip an element when slice a list
tagged with: slice
has comment: http://stackoverflow.com/comment/84925129

http://stackoverflow.com/q/48920126
has comment: http://stackoverflow.com/comment/84847431
type: Question
tagged with: apache
has comment: http://stackoverflow.com/comment/84878656
has comment: http://stackoverflow.com/comment/84846970
has title: forbidden 4.3 error on apache in ubuntu for my flask script
score: 0
has comment: http://stackoverflow.com/comment/84878689
answer count: 0
has body: I created my flask service and hosted in apache by following this tutorial but after configuring When I go to my localhost it says, Forbidden You don't have permission to access / on this server. Apache/2.4.18 (Ubuntu) Server at localhost Port 80 Please help. apache2.conf file: Options FollowSymLinks AllowOverride None Require all denied AllowOverride None Require all granted Options Indexes FollowSymLinks AllowOverride None Require all granted AccessFileName .htaccess Require all denied LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %O" common LogFormat "%{Referer}i -> %U" referer LogFormat "%{User-agent}i" agent etc/apache2/sites-available/flask.conf file: ServerName 192.168.175.35 ServerAdmin pechi@email.com WSGIScriptAlias / /var/www/flask/flask.wsgi Order allow,deny Allow from all Alias /static /var/www/flask/flask/static Order allow,deny Allow from all ErrorLog ${APACHE_LOG_DIR}/error.log LogLevel warn CustomLog ${APACHE_LOG_DIR}/access.log combined Please help, thanks in advance!. Please let me know if you need anymore details.
type: UnansweredQuestion
tagged with: python
tagged with: mod-wsgi

http://stackoverflow.com/comment/84838078
comment on: http://stackoverflow.com/q/48915732
score: 0
type: Comment
type: QuestionComment
has text: Why can't you just chunk the list of ID's into lists of 500 and run your IN query on those lists, concatenate the results?

http://stackoverflow.com/q/48859515
has comment: http://stackoverflow.com/comment/132757951
has comment: http://stackoverflow.com/comment/122584906
score: 2
tagged with: django-users
has comment: http://stackoverflow.com/comment/84722608
linked to: http://stackoverflow.com/q/74192495
upvote count: 2
tagged with: django
has comment: http://stackoverflow.com/comment/84722545
type: Question
tagged with: django-forms
has title: trying to delete inactive users in django
downvote count: 0
answer count: 1
favorite count: 0
has answer: http://stackoverflow.com/a/74260329
has body: I am writing a site that sends confirmation emails on signup. Until the user clicks the link, the is_active field is set to false. How can I automatically delete any users who do not click the activation link within a certain period of time? Is this even a viable option or is there a better way to work around users who never confirmed their accounts? Thanks for any help!
has comment: http://stackoverflow.com/comment/114811868
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84722496
tagged with: python

http://stackoverflow.com/a/48829849
downvote count: 0
score: 1
has body: Both training and testing require mini-batches of data, because both may lead to out-of-memory error (OOM) otherwise. You are right that the problem is more critical in training because backward pass effectively doubles memory consumption. But it doesn't mean OOM is impossible in inference. Examples from my experience: Python kernel died when using tensorflow OOM when allocating tensor ... and I'm sure there are many more examples that I haven't seen. Depending on your resources, 16281 might be small enough to fit into one batch, but in general it makes perfect sense to iterate in batches in inference and have a separate setting for this batch size, for instance if the model would ever run on another machine with fewer resources.
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84667616
answers question: http://stackoverflow.com/q/48829294
type: Answer
has comment: http://stackoverflow.com/comment/84667637
accepted answer of: http://stackoverflow.com/q/48829294

http://stackoverflow.com/comment/84873751
has text: Read https://nedbatchelder.com/text/names.html
comment on: http://stackoverflow.com/q/48933543
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48963327
tagged with: python
has title: Can't import third party libraries python3
tagged with: python-3.x
has answer: http://stackoverflow.com/a/48963371
accepted answer: http://stackoverflow.com/a/48963371
type: AnsweredQuestion
score: 3
downvote count: 0
tagged with: eof
type: Question
answer count: 1
has body: I downloaded requests and BeautifulSoup modules using pip and when i try to import using command line it works. But when I code in notepad++ and then run the .py file using cmd it gives an error. This is my code: import requests from bs4 import BeautifulSoup response=requests.get('') html=response.text soup=BeautifulSoup(html,'html.parser') soup.p.a.string The error I am getting is: Traceback (most recent call last): File "soup.py", line 1, in &lt;module&gt; import requests File "C:\Users\person8565\AppData\Local\Programs\Python\Python36\lib\site-packages\requests\__init__.py", line 43, in &lt;module&gt; import urllib3 File "C:\Users\person8565\AppData\Local\Programs\Python\Python36\lib\site-packages\urllib3\__init__.py", line 8, in &lt;module&gt; from .connectionpool import ( File "C:\Users\person8565\AppData\Local\Programs\Python\Python36\lib\site-packages\urllib3\connectionpool.py", line 3, in &lt;module&gt; import logging File "C:\Users\person8565\AppData\Local\Programs\Python\Python36\lib\logging\__init__.py", line 28, in &lt;module&gt; from string import Template File "C:\Users\person8565\Documents\python\string.py", line 13 ^ SyntaxError: unexpected EOF while parsing Can anyone tell me what I am doing wrong?
favorite count: 0
upvote count: 3

http://stackoverflow.com/a/48945041
has body: Well according to your error which says, you have no SECRET_KEY defined. You need to add one to your settings.py. Django will refuse to start if SECRET_KEY is not set. You can read more about it in docs The SECRET_KEY can be anything...but if you want to use Django to generate one, you can do the following from the python shell: &gt;&gt;&gt; from django.utils.crypto import get_random_string &gt;&gt;&gt; chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&amp;*(-_=+)' &gt;&gt;&gt; SECRET_KEY = get_random_string(50, chars) &gt;&gt;&gt; print SECRET_KEY Copy the secret_key to your setting file. Hope this will help you! :)
type: Answer
answers question: http://stackoverflow.com/q/48944711
score: 0

http://stackoverflow.com/comment/84864804
comment on: http://stackoverflow.com/a/48929034
type: Comment
score: 1
has text: It's just if you read between the lines OP is reading a large excel file. In any other case downcast integer is the way.
type: AnswerComment

http://stackoverflow.com/a/48827252
score: 0
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48810468
accepted answer of: http://stackoverflow.com/q/48810468
has body: It looks like django-modeltranslation doesn't workwith django 2.0 (at least for me and the installation procedure out there). But it does with django 1.11.

http://stackoverflow.com/a/48832225
downvote count: 0
has comment: http://stackoverflow.com/comment/84669872
score: 1
answers question: http://stackoverflow.com/q/48832178
accepted answer of: http://stackoverflow.com/q/48832178
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84671908
type: Answer
has body: a = [1,2,3] b = [4,5,6] def add(a, b): c = [] for i in range(len(a)): c.append(a[i] + b[i]) return c print(add(a, b)) Output: [5, 7, 9]
has comment: http://stackoverflow.com/comment/84668942

http://stackoverflow.com/a/48820674
answers question: http://stackoverflow.com/q/48820478
score: 0
has comment: http://stackoverflow.com/comment/84644958
type: Answer
has body: In [5]: xmax, ymax = 7, 8 ...: dst = np.linspace(-2,10,20).reshape((2,-1)).astype(np.int32) ...: mask = np.where((0 &lt;= dst) &amp; (dst[1,:] &lt; xmax) &amp; (dst[0,:] &lt; ymax)) ...: In [6]: mask Out[6]: (array([0, 0, 0, 1, 1, 1, 1, 1], dtype=int32), array([2, 3, 4, 0, 1, 2, 3, 4], dtype=int32)) In [8]: dst[mask] Out[8]: array([0, 0, 0, 4, 4, 5, 6, 6]) mask does select the right elements of dst, but from either row. But this selects from both rows, using just part of the the mask info. So it has some of the masked values, but also the value from the other row. In [9]: dst[:,mask[1]] Out[9]: array([[ 0, 0, 0, -2, -1, 0, 0, 0], [ 5, 6, 6, 4, 4, 5, 6, 6]]) In [10]: dst[0,mask[1]] Out[10]: array([ 0, 0, 0, -2, -1, 0, 0, 0]) In [11]: dst[1,mask[1]] Out[11]: array([5, 6, 6, 4, 4, 5, 6, 6])

http://stackoverflow.com/q/48850468
tagged with: pyqt
has comment: http://stackoverflow.com/comment/84795833
has title: UI is degraded after converting to single file
tagged with: pyinstaller
type: UnansweredQuestion
has body: I have created simple UI with QT Designer: <?xml version="1.0" encoding="UTF-8"?> MainWindow <x>0</x> <y>0</y> 800 600 MainWindow <x>80</x> <y>110</y> 141 161 false false false true <x>80</x> <y>40</y> 141 61 <x>0</x> <y>0</y> 800 21 Main <addaction name="actionOfaman"/> <addaction name="menuMain"/> test <resources/> <connections/> It contains one dial widget and lcd display. Then I used the following to convert it to python: pyuic5 -x main.ui -o mainui.py Then I converted it to single executable: pyinstaller.exe --onefile --windowed mainui.py Original UI should look like this: But running single executable is degrading UI: As you can see dial control is degraded and some line has been added under main menu. Conversion is much identical when using cx_Freeze, but I would like to know if pyinstall is not capable to handle PyQT5/Python36.
tagged with: python
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/84711540
score: 0

http://stackoverflow.com/q/48810367
has comment: http://stackoverflow.com/comment/84653868
has comment: http://stackoverflow.com/comment/84653605
tagged with: python-newspaper
favorite count: 0
has comment: http://stackoverflow.com/comment/84654102
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
score: 2
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/84653546
tagged with: url-encoding
has comment: http://stackoverflow.com/comment/84653983
downvote count: 0
has comment: http://stackoverflow.com/comment/84653646
has body: I am trying to get the content of a news article with python newspaper module. I can find the body of a news item with the following code. The code parses the feed URL in feed_url variable with feedparser and then tries to find the news body and publishing date with newspaper module. import newspaper from newspaper import Article import feedparser import urllib.parse count = 0 feed_url="https://www.extremetech.com/feed" #feed_url="http://www.prothomalo.com/feed/" d = feedparser.parse(feed_url) for post in d.entries: count+=1 if count == 2: break #post_link = post.link post_link =urllib.parse.unquote(post.link) #Added later to decode the # encoded URL into the original Bengali langauge print("count= ",count," url = ",post_link,end="\n ") try: content = Article(post_link) content.download() content.parse() print(" content = ", end=" ") print(content.text[0:50]) print(" content.publish_date = {}".format(content.publish_date)) except Exception as e: print(e) I mentioned 2 different values for the variable feed_url in the code - one is from extremetch site and another one is from prothomalo website . Let us say for example, extremetech has a news item (which I get through feedparser.parse )with URL as https://www.extremetech.com/computing/263951-mit-announces-new-neural-network-processor-cuts-power-consumption-95. And I can easily get the news body text and publishing date for this URL. But prothomalo for example has a news item with the URL ( obtained from feedparser.parse) as http://www.prothomalo.com/sports/article/1432086/%E0%A6%B8%E0%A6%B0%E0%A7%8D%E0%A6%AC%E0%A7%8B%E0%A6%9A%E0%A7%8D%E0%A6%9A-%E0%A6%B8%E0%A7%8D%E0%A6%95%E0%A7%8B%E0%A6%B0-%E0%A6%97%E0%A7%9C%E0%A7%87%E0%A6%93-%E0%A6%B9%E0%A6%BE%E0%A6%B0 . But the actual URL does not look so in prothomalo website. You can visit the URL and will find that the URL has changed into Bengali language. I think the reason behind such encrypted (?) URL is that the URL has some parts that are in Bengali language. The content he…
has title: python newspaper - cannot extract article if URL is not in english language

http://stackoverflow.com/q/48957632
tagged with: python-2.7
tagged with: odoo-10
upvote count: 1
answer count: 1
has body: I would like to know how I can print in a report qweb a whole field many2many, similar to what happens in the quotes, invoices of the sales module. Or if it is possible to print them separately in the report cie10_app model from odoo import models, api, fields class Cie10Db(models.Model): _name = 'cie10.list' _rec_name = 'detalleCie' codCie = fields.Char('Codigo Cie10') detalleCie = fields.Char('Detalle Diagnostico') cie10_informed from odoo import models, fields class DiagRec(models.Model): _name = 'info.cie10' ob_cie10 = fields.Many2one('cie10.list',string='Dx (CIE 10)') ob_codCie10 = fields.Char(related='ob_cie10.codCie') ob_observaciones = fields.Char('Observaciones') informed_app from odoo import models, fields, api class InfMed(models.Model): dx1 = fields.Many2many('info.cie10') I need to print the whole field many2many in the report qweb informed_report &lt;span t-field="o.tratRec1"/&gt; but I only get this
favorite count: 0
tagged with: python
tagged with: qweb
has answer: http://stackoverflow.com/a/48960238
accepted answer: http://stackoverflow.com/a/48960238
tagged with: http://stackoverflow.com/tag/xml
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has title: print many2many fields on qweb-report

http://stackoverflow.com/q/48838386
has comment: http://stackoverflow.com/comment/84681523
upvote count: 6
answer count: 4
favorite count: 0
has answer: http://stackoverflow.com/a/50770587
type: UnansweredQuestion
has body: In duration of following these tutorial Neural net , on running test.py file , I am getting these exceptions and warnings .I had already tried previous suggestions but nothing has worked . WARNING (theano.configdefaults): g++ not available, if using conda: `conda install m2w64-toolchain` C:\ProgramData\Anaconda3\lib\site-packages\theano\configdefaults.py:560: UserWarning: DeprecationWarning: there is no c++ compiler.This is deprecated and with Theano 0.11 a c++ compiler will be mandatory warnings.warn("DeprecationWarning: there is no c++ compiler." WARNING (theano.configdefaults): g++ not detected ! Theano will be unable to execute optimized C-implementations (for both CPU and GPU) and will default to Python implementations. Performance will be severely degraded. To remove this warning, set Theano flags cxx to an empty string. WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions. Any proper fix will be appreciated. After trying with conda install m2w64-toolchain . Another error comes which says, *You can find the C code in this temporary file: C:\Users\CERTAI~1\AppData\Local\Temp\theano_compilation_error_7bgw9_s9 Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\theano\gof\lazylinker_c.py", line 75, in &lt;module&gt; raise ImportError() ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\ProgramData\Anaconda3\lib\site-packages\theano\gof\lazylinker_c.py", line 92, in &lt;module&gt; raise ImportError() ImportError During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\shubhamprojectwork\all Work 2018\kaggle\DeepLearningPython35-master\DeepLearningPython35-master\test.py", line 156, in &lt;module&gt; import network3 File "C:\shubhamprojectwork\all Work 2018\kaggle\DeepLearningPython35-master\DeepLearningPython35-master\network3.py", line 37, in &lt;module&gt; import theano …
tagged with: tensorflow
type: Question
tagged with: g++
tagged with: theano
has comment: http://stackoverflow.com/comment/84681366
tagged with: conda
downvote count: 0
score: 6
has title: g++ not available, if using conda: `conda install m2w64-toolchain`
has answer: http://stackoverflow.com/a/50665419
has answer: http://stackoverflow.com/a/62340737
has answer: http://stackoverflow.com/a/49749800
tagged with: python

http://stackoverflow.com/comment/84751256
type: Comment
comment on: http://stackoverflow.com/q/48873623
type: QuestionComment
has text: An `if` statement only executes once. Is this in some kind of loop? Are you rebooting the device that this code runs on? Or some other remote device?
score: 0

task
type: Tag
tag name: task
tags question: http://stackoverflow.com/q/48807708

http://stackoverflow.com/comment/84883653
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48938346
has text: This is a dictionary comprehension.

http://stackoverflow.com/q/48854455
has answer: http://stackoverflow.com/a/48854606
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84714213
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48854606
score: 1
tagged with: matplotlib
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/13634349
has body: I have a matrix A: A = np.matrix(np.random.rand(4,2)) matrix([[ 0.01124212, 0.45879116], [ 0.10993219, 0.00142847], [ 0.34650295, 0.98693131], [ 0.20417694, 0.81177707]]) Is there an easy way to use matplotlib (or similar libary) to show a scatterplot in 2-d? When I use plt.plot(A) it shows as a line graph.
has title: How to plot a matrix in scatterplot python
duplicate of: http://stackoverflow.com/q/13634349
answer count: 1
downvote count: 0
favorite count: 0

http://stackoverflow.com/comment/84801502
type: Comment
has text: Is there a name for this?
comment on: http://stackoverflow.com/a/48898008
score: 0
type: AnswerComment

dicom
tag name: dicom
type: Tag
tags question: http://stackoverflow.com/q/48948290
tags question: http://stackoverflow.com/q/48860881
tags question: http://stackoverflow.com/q/48846517

http://stackoverflow.com/comment/85405734
comment on: http://stackoverflow.com/q/48853484
type: QuestionComment
score: 1
has text: Not sure about how gdal works in python, but this is pretty easily accomplished in R using gdal. Interestingly it looks like you're trying to do some kind of imputation. If things stay slow today, I'll throw up an example in R. Very good packages for dealing with rasters.
type: Comment

http://stackoverflow.com/q/48887198
has comment: http://stackoverflow.com/comment/84779331
has comment: http://stackoverflow.com/comment/84779355
tagged with: loops
has comment: http://stackoverflow.com/comment/84779367
answer count: 1
tagged with: arrays
favorite count: 0
has comment: http://stackoverflow.com/comment/84779434
downvote count: 3
has title: Dict operation in loop
has comment: http://stackoverflow.com/comment/84779541
has comment: http://stackoverflow.com/comment/84779336
has comment: http://stackoverflow.com/comment/84779638
tagged with: python
tagged with: dictionary
upvote count: 0
has body: I have a dict as follows: A[1] Out[351]: [0, 4, 5, 6] A[2] Out[352]: [1, 25, 8, 4] upto: A[7] Out[352]: [0, 3, 6, 9] Given these, I have to populate another dict using the following condition: if A[1][0] &lt;= A[2][0]: l=1 else: l=A[2][0]-A[1][2]/((A[1][1]-A[1][2])-(A[2][1]-A[2][0])) which gives: l Out[354]: 1 Similarly: if A[1][0] &lt;= A[3][0]: l=1 else: l=A[3][0]-A[1][2]/((A[1][1]-A[1][2])-(A[3][1]-A[3][0])) if A[1][0] &lt;= A[4][0]: l=1 else: l=A[4][0]-A[1][2]/((A[1][1]-A[1][2])-(A[4][1]-A[4][0])) upto: if A[1][0] &lt;= A[7][0]: l=1 else: l=A[7][0]-A[1][2]/((A[1][1]-A[1][2])-(A[7][1]-A[7][0])) If I append these, I'm supposed to get: l Out[360]: [1, 1, 1, 1, 1, 1, 1] I want the l to be a dict: {1: [1, 1, 1, 1, 1, 1, 1]} for A1 and {2: [some values]} for A2..upto {7: [some values]} for A7. One problem is I have to compute this starting from A[1][0], A[2][0] to A[1][0],A[7][0] and then for A[2][0], A[1]A[0]...so on upto A[7][0],A[6][0]. The other problem is that I need to skip the computation wherever A[i][0] and A[i][0] are to be compared. I've initially tried a loop like this: i=[i for i in A.keys()] k=[k for k in A.keys()] while i != k: if A[i][0] &lt;= A[k][0]: B=1 else: B=A[k][0]-A[i][2]/((A[i][1]-A[i][2])-(A[k][1]-A[k][0])) k +=1 i +=1 I'm getting this error: File "&lt;ipython-input-350-9d9e2d0e5d59&gt;", line 8, in &lt;module&gt; k +=1 TypeError: 'int' object is not iterable Somebody kindly help me get the loop please. Please note that B has to be a dict.
has comment: http://stackoverflow.com/comment/84779843
type: UnansweredQuestion
score: -3
has comment: http://stackoverflow.com/comment/84779585
has answer: http://stackoverflow.com/a/48887880
has comment: http://stackoverflow.com/comment/84779817
type: Question
has comment: http://stackoverflow.com/comment/84779528
has comment: http://stackoverflow.com/comment/84779400

http://stackoverflow.com/comment/84695843
has text: 33 Thank you very much fam
comment on: http://stackoverflow.com/a/48841328
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/a/48811030
has comment: http://stackoverflow.com/comment/84626091
has comment: http://stackoverflow.com/comment/84625693
type: Answer
score: 0
has body: Anaconda's Python interpreter is isolated from the system. If you install anything system-wide, your Anaconda's Python won't be able to find it. If you want/need to use Anaconda you have two options: use conda use the pip that comes with Anaconda (which very likely is the version that you are using) Otherwise don't use Anaconda: remove /home/username/miniconda3/bin/python from your PATH and use the system Python executable (should be something like /usr/bin/python). The system Python executable knows where to look for packages installed with your system package manager, e.g. packman)
answers question: http://stackoverflow.com/q/48810925

http://stackoverflow.com/a/48855990
has body: The line, for key,value in dftest[4].items(): looks to me the only place in the code where unpacking values is necessary. This being the case, dftest[4].items() would need to be one of the kinds of items like those on the right sides of these assignments: &gt;&gt;&gt; k,v = 1,2 &gt;&gt;&gt; k,v = 2,[3,4,5] &gt;&gt;&gt; k,v = [1,2], [3,4,5] &gt;&gt;&gt; k,v = [1,2], {2: 3} If I were in your position I'd print dftest[4].items() just ahead of that for-loop, to see what kind of a structure it is. (Hazarding a guess I'd say it's a list.) Or, look again at the doc.
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48855737

http://stackoverflow.com/q/48893545
answer count: 1
downvote count: 1
has answer: http://stackoverflow.com/a/48918116
has comment: http://stackoverflow.com/comment/84792899
has comment: http://stackoverflow.com/comment/84792964
has comment: http://stackoverflow.com/comment/84792997
upvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84792851
type: Question
tagged with: python
favorite count: 0
score: -1
has comment: http://stackoverflow.com/comment/84792764
has title: Importing error in python3.6
has body: from flask import Flask, request from flask_restful import Resource, Api from flask_jwt import JWT, jwt_required from .security import authenticate, identity app = Flask(__name__) app.secret_key = "jose" api = Api(app) # Can easily add resources to this "app" jwt = JWT(app, authenticate, identity) items = [] # every resource has to be a class class Item(Resource): @jwt_required() def get(self, name): item = next(filter(lambda x: x["name"] == name, items), None) return {"item": item}, 200 if item else 404 def post(self, name): if next(filter(lambda x: x["name"] == name, items), None) is not None: return {"Message": "An Item with the name {} already exit".format(name)}, 400 data = request.get_json() item = {"name": name, "price": data["price"]} items.append(item) return item, 201 # 201 is status code for created class ItemList(Resource): def get(self): return {"items": items} api.add_resource(Item, "/item/&lt;string:name&gt;") api.add_resource(ItemList, "/items") app.run(port=5000, debug=True) from werkzeug.security import safe_str_cmp from .user import User users = [ User(1, "bob", "asdf") ] username_mapping = {u.username: u for u in users} userid_mapping = {u.id: u for u in users} def authenticate(username, password): user = username_mapping.get(username, None) if user and safe_str_cmp(user.password, password): return user def identity(payload): user_id = payload["identity"] return userid_mapping.get(user_id, None) I am trying to import authenticate and identity into my app.py from security.py. They are both in the same directory. The linter is not giving me any errors but when i Run app.py it gives me this error: ModuleNotFoundError: No module named 'main.security'; 'main' is not a package I am not sure where this is coming from. Is it not recognizing security.py exist with in the same directory?

http://stackoverflow.com/comment/84656153
comment on: http://stackoverflow.com/a/48826044
type: AnswerComment
has text: That I don't know. Just that these two are most widely used to my knowledge :)
score: 0
type: Comment

http://stackoverflow.com/comment/84692566
type: Comment
comment on: http://stackoverflow.com/q/48841927
score: 0
type: QuestionComment
has text: try using jupyter notebook seems the one u are using is from a different version

http://stackoverflow.com/a/48924536
has comment: http://stackoverflow.com/comment/84855442
score: 1
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48923810
answers question: http://stackoverflow.com/q/48923810
type: Answer
upvote count: 1
has body: I can confirm the segmentation fault on Ubuntu 16.04 and Python 2.7, if I omit the initialization. Looking at Embedding Python in Another Application, there's this example #include &lt;Python.h&gt; int main(int argc, char *argv[]) { Py_SetProgramName(argv[0]); /* optional but recommended */ Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(time())\n"); Py_Finalize(); return 0; } So when I do an equivalent minimal main int main() { Py_Initialize(); PyObject *p = convert_to_python(); Py_Finalize(); return 0; } it works without crash. The difference between the two examples is long int a = 20; and long int a = 65454984; I guess, it has to do with PyInt_FromLong(long ival) The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object. Maybe Python tries to access an uninitialized pointer or memory range without the initialization. When I change the example using a = 256, it crashes. Using a = 257, it doesn't. Looking at cpython/Objects/intobject.c:79, you can see an array of pointers static PyIntObject *small_ints[NSMALLNEGINTS + NSMALLPOSINTS]; which is accessed right below in PyInt_FromLong(long ival) v = small_ints[ival + NSMALLNEGINTS]; Py_INCREF(v); But without initialization from _PyInt_Init(void) for (ival = -NSMALLNEGINTS; ival &lt; NSMALLPOSINTS; ival++) { if (!free_list &amp;&amp; (free_list = fill_free_list()) == NULL) return 0; /* PyObject_New is inlined */ v = free_list; free_list = (PyIntObject *)Py_TYPE(v); (void)PyObject_INIT(v, &amp;PyInt_Type); v-&gt;ob_ival = ival; small_ints[ival + NSMALLNEGINTS] = v; } these pointers are all NULL, causing the crash.

http://stackoverflow.com/comment/84872396
comment on: http://stackoverflow.com/a/48932833
type: Comment
has text: Queue is a list
score: 0
type: AnswerComment

http://stackoverflow.com/q/48882283
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: pyqt5
type: Question
tagged with: pyqtdeploy
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48893492
has title: Build Tab missing in pyqtdeploy
accepted answer: http://stackoverflow.com/a/48893492
favorite count: 0
tagged with: user-interface
has body: I'm trying to deploy my PyQt5 application using pyqtdeploy. The pyqtdeploy GUI shows up, but there is no tab for Build. I have tried in different computers, but the Build tab is still not there. What is the problem?
upvote count: 2

http://stackoverflow.com/comment/84649813
type: AnswerComment
has text: @BinduManjunath that is a new question(!) and even more important just giving us this single line does not help, because we don't know how it is related ..
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48822812

http://stackoverflow.com/a/48906367
upvote count: 9
type: AcceptedAnswer
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48906246
has body: Using BeautifulSoup. from bs4 import BeautifulSoup import json s = """So I got now a variable String with this text ins variable &lt;div class="header-product js-header-product" data-product='{ "sku": "218009200", "fullTitle": "iPhone 7 Apple 32GB Preto Matte 4G Tela 4.7”Retina - Câm. 12MP + Selfie 7MP iOS 11 Proc. Chip A10", "baseUrl": "https://www.myurl.com.br", "variationPath": "iphone-7-apple-32gb-preto-matte-4g-tela-4-7-retina-cam-12mp-selfie-7mp-ios-11-proc-chip-a10/p/2180092/te/iph7/", "imageUrl": "https://a-static.mlcdn.com.br/{w}x{h}/iphone-7-apple-32gb-preto-matte-4g-tela-4-7-retina-cam-12mp-selfie-7mp-ios-11-proc-chip-a10/myurl/218009200/f06f03c5ea2ba95deaa3e55e5e0e687e.jpg", "urlSubcategories": "https://www.myurl.com.br/iphone-7-e-iphone-7-plus/celulares-e-smartphones/s/te/iph7/", "quantitySellers": 1, "categoryId": "te", "serviceUrl": "/produto/garantia-plus/?product=218009200&amp;amp;marketplaceSellerId=myrul&amp;amp;productDiscountPrice=3199.00&amp;amp;productCashPrice=2879.10&amp;amp;productQuantity=10", "title": "iPhone 7 Apple 32GB Preto Matte 4G Tela 4....", "serviceUrl": "/produto/garantia-plus/?product=218009200&amp;amp;marketplaceSellerId=myurl&amp;amp;productDiscountPrice=3199.00&amp;amp;productCashPrice=2879.10&amp;amp;productQuantity=10", "bestPriceTemplate": " 2.879,10", "installmentQuantity": "10", "buyTogetherImage": "https://a-static.mlcdn.com.br/195x145/iphone-7-apple-32gb-preto-matte-4g-tela-4-7-retina-cam-12mp-selfie-7mp-ios-11-proc-chip-a10/myurl/218009200/f06f03c5ea2ba95deaa3e55e5e0e687e.jpg", "thumbailBuyTogether": "https://a-static.mlcdn.com.br/70x90/iphone-7-apple-32gb-preto-matte-4g-tela-4-7-retina-cam-12mp-selfie-7mp-ios-11-proc-chip-a10/myurl/218009200/f06f03c5ea2ba95deaa3e55e5e0e687e.jpg", "list_price_price_parcel_cash_price": "list_price_price_parcel_cash_price.html", "listPrice": " 3.499,90", "installmentAmount": " 319,90", "priceTemplate": " 3.199,00", "seller": "myurl", "attributes": [{"label":"Cor","value":"Preto Matte",…
accepted answer of: http://stackoverflow.com/q/48906246
score: 9

http://stackoverflow.com/q/48932694
has comment: http://stackoverflow.com/comment/84874179
answer count: 0
score: 1
has comment: http://stackoverflow.com/comment/84873816
type: Question
linked to: http://stackoverflow.com/q/7204805
upvote count: 2
has title: How do I merge two multi-dictionary dictionaries?
downvote count: 1
favorite count: 0
tagged with: python-3.x
has body: I am new to Python and this might've been answered already but I'm having trouble finding a similar question which would be dealing with merging multi-dictionary dictionaries. So my question is: How can I merge dict1 and dict2 to end up with dict3 as shown below? Thank you for your time and help! #inputs dict1 = {'aapl': {'Cash &amp; Cash Equivalents': {'2017': 74181, '2016': 67155}, 'Receivables': {'2017': 29299, '2016': 30343}}, 'nvda': {'Cash &amp; Cash Equivalents': {'2017': 7108, '2016': 6798}, 'Receivables': {'2017': 826, '2016': 505}} } dict2 = {'aapl': {'Income Tax': {'2017': 41181, '2016': 12355}, 'After-Tax Income': {'2017': 22323, '2016': 12345}}, 'nvda': {'Income Tax': {'2017': 1209, '2016': 1192}, 'After-Tax Income': {'2017': 12326, '2016': 11093}} } #output dict3 = {'aapl': {'Cash &amp; Cash Equivalents': {'2017': 74181, '2016': 67155}, 'Receivables': {'2017': 29299, '2016': 30343}, 'Income Tax': {'2017': 41181, '2016': 12355}, 'After-Tax Income': {'2017': 22323, '2016': 12345}}, 'nvda': {'Cash &amp; Cash Equivalents': {'2017': 7108, '2016': 6798}, 'Receivables': {'2017': 826, '2016': 505}, 'Income Tax': {'2017': 1209, '2016': 1192}, 'After-Tax Income': {'2017': 12326, '2016': 11093}} }
type: UnansweredQuestion
duplicate of: http://stackoverflow.com/q/7204805
tagged with: python
tagged with: merge
tagged with: dictionary

http://stackoverflow.com/a/48850016
upvote count: 1
has comment: http://stackoverflow.com/comment/84703713
answers question: http://stackoverflow.com/q/48849920
has comment: http://stackoverflow.com/comment/84704126
score: 1
has comment: http://stackoverflow.com/comment/84703904
type: AcceptedAnswer
has body: I would try running with debug=False or use_reloader to prevent flask from restarting after detecting a change in your files and see if anything changes. More info about the reloaded here: How to stop Flask from initialising twice in Debug Mode? The slowness in the startup could be attributed to any long running tasks in your app initialization code. You would need to include more code or profile the code yourself to troubleshoot that. If you are reading or writing from/to a network location IO might be your bottleneck. Lastly, I recently went through an effort of troubleshooting/optimizing a flask app startup time - maybe something there could be useful to you: Slow Flask Development Server Initialization Profiling: `WaitForSingleObject`
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48849920
has comment: http://stackoverflow.com/comment/84703987

http://stackoverflow.com/comment/85280946
type: Comment
score: 1
has text: few-show learning is not the same as online learning, but they are related. Few-shot usually involves online-learning. Online-learning generally does not involve new classes, just new data. Few-show involves new class and new data.
type: AnswerComment
comment on: http://stackoverflow.com/a/48957375

http://stackoverflow.com/comment/84803360
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48898744
type: Comment
has text: Probably violates the basic structure, but sure why not?

http://stackoverflow.com/a/48918858
answers question: http://stackoverflow.com/q/48918175
score: 0
type: Answer
has body: I think I was able to achieve what you wanted by using lists instead of tuples. Tuples cannot be modified, but if you really want to know how click here (I also added the possibility to quit the program) Important: Never forget to comment your code The code: def exercise11(): import string while True: try: fname = input('Enter the file name -&gt; ') print('Press 0 to quit the program') # give the User the option to quit the program easily if fname == '0': break fop = open(fname) break except: print('This file does not exists. Please try again!') continue counts = {} for line in fop: line = line.translate(str.maketrans('', '', string.punctuation)) line = line.translate(str.maketrans('', '', string.whitespace)) line = line.translate(str.maketrans('', '', string.digits)) line = line.lower() for ltr in line: if ltr in counts: counts[ltr] += 1 else: counts[ltr] = 1 lst = [] countlst = [] freqlst = [] for ltrs, c in counts.items(): # add a zero as a place holder &amp; # use square brakets so you can use a list that you can modify lst.append([c, ltrs, 0]) countlst.append(c) totalcount = sum(countlst) for ec in countlst: efreq = (ec/totalcount) * 100 freqlst.append(efreq) freqlst.sort(reverse=True) lst.sort(reverse=True) # count the total of the letters counter = 0 for ltrs in lst: counter += ltrs[0] # calculate the percentage for each letter for letter in lst: percentage = (letter[0] / counter) * 100 letter[2] += float(format(percentage, '.2f')) for i in lst: print('The letter {} is repeated {} times, which is {}% '.format(i[1], i[0], i[2])) exercise11()

http://stackoverflow.com/comment/85812130
comment on: http://stackoverflow.com/a/48928133
score: 0
type: Comment
type: AnswerComment
has text: @thigi pay attention to the variance of grad distribution. It jumped from `~0.000002` to `~0.1`. That is more than enough for NN to learn

http://stackoverflow.com/comment/84637015
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48816433
has text: @Peter: SO is for questions regarding problems for which you have already partial solutions. In you case, this is more like a problem for [cs](https://cs.stackexchange.com/). Note that from your question, it looks like you have a [linear assignment problem](https://en.wikipedia.org/wiki/Assignment_problem).

http://stackoverflow.com/q/48827580
upvote count: 1
accepted answer: http://stackoverflow.com/a/48828290
tagged with: data-manipulation
has body: I have car rental booking data, of this form: location | day_of_drive | day_of_reservation | number_of_bookings ------------------------------------------------------------------- foo | 01-01-2015 | 24-12-2014 | 1 foo | 01-01-2015 | 26-12-2014 | 1 foo | 01-01-2015 | 29-12-2014 | 3 foo | 01-01-2015 | 30-12-2014 | 2 foo | 01-01-2015 | 31-12-2014 | 1 foo | 02-01-2015 | 29-12-2014 | 2 foo | 02-01-2015 | 31-12-2014 | 1 foo | 02-01-2015 | 01-01-2015 | 1 bar | 25-06-2016 | 03-07-2016 | 1 . . . What I want is to pad this dataset to include dates where 0 bookings were made. The data frame is already sorted, first by location, then by day_of_drive, then by day_of_reservation. What I want is an efficient way to pad with zero values the day_of_reservation variable between the first observed value of this variable, which corresponds to the first booking for this day_of_drive/location pair, and the day_of_drive , for a given pair of location and day_of_drive itself. I have come across solutions using unstacking, then using fillna(0), then stacking back up, but I don't think I can use these as each pair of location and day_of_drive has a different min and max date I want to pad between. Desired output: location | day_of_drive | day_of_reservation | number_of_bookings ------------------------------------------------------------------- foo | 01-01-2015 | 24-12-2014 | 1 foo | 01-01-2015 | 25-12-2014 | 0 foo | 01-01-2015 | 26-12-2014 | 1 foo | 01-01-2015 | 27-12-2014 | 0 foo | 01-01-2015 | 28-12-2014 | 0 foo | 01-01-2015 | 29-12-2014 | 3 foo | 01-01-2015 | 30-12-2014 | 2 foo | 01-01-2015 | 31-12-2014 | 1 foo | 02-01-2015 | 29-12-2014 | 2 foo | 02-01-2015 | 30-12-2014 | 0 foo | 02-01-2015 | 31-12-2014 | 1 foo | 02-01-2015 | 01-01-2015 | 1 bar | 25-06-2016 | 03-07-2016 | 1 bar | 25-06-2016 | 04-07-2016 | 0 . . . I have a feeling the solution is with a groupby.
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48828071
has answer: http://stackoverflow.com/a/48828290
type: Question
tagged with: python
possible better answer: http://stackoverflow.com/a/48828071
has title: Padding pandas groupby with zeros for inconsistent date ranges
answer count: 2

http://stackoverflow.com/comment/84821383
has text: Still don't know what you mean by `dimensions`. Is it some sort of integer? Why did you say `80*100*10` and not `80,000`?
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48905837

http://stackoverflow.com/q/48826588
type: Question
tagged with: random-forest
downvote count: 0
answer count: 1
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/48857959
has body: I have applied random forest classifier to get the feature that contributed for a specific row in a dateset. However, I get 2 values for the feature, instead of one. I am not quite sure why. Here is my code. import numpy as np import pandas as pd from sklearn.datasets import make_classification from sklearn.ensemble import RandomForestClassifier from treeinterpreter import treeinterpreter as ti from treeinterpreter import treeinterpreter as ti X, y = make_classification(n_samples=1000, n_features=6, n_informative=3, n_classes=2, random_state=0, shuffle=False) # Creating a dataFrame df = pd.DataFrame({'Feature 1':X[:,0], 'Feature 2':X[:,1], 'Feature 3':X[:,2], 'Feature 4':X[:,3], 'Feature 5':X[:,4], 'Feature 6':X[:,5], 'Class':y}) y_train = df['Class'] X_train = df.drop('Class',axis = 1) rf = RandomForestClassifier(n_estimators=50, random_state=0) rf.fit(X_train, y_train) print ("-"*20) importances = rf.feature_importances_ indices = X_train.columns instances = X_train.loc[[60]] print(rf.predict(instances)) print ("-"*20) prediction, biases, contributions = ti.predict(rf, instances) for i in range(len(instances)): print ("Instance", i) print ("-"*20) print ("Bias (trainset mean)", biases[i]) print ("-"*20) print ("Feature contributions:") print ("-"*20) for c, feature in sorted(zip(contributions[i], indices), key=lambda x: ~abs(x[0].any())): print (feature, np.round(c, 3)) print ("-"*20) This is the output of my code. Can someone explain why the bias and features output 2 values instead of one ? -------------------- [0] -------------------- Instance 0 -------------------- Bias (trainset mean) [ 0.49854 0.50146] -------------------- Feature contributions: -------------------- Feature 1 [ 0.16 -0.16] Feature 2 [-0.024 0.024] Feature 3 [-0.154 0.154] Feature 4 [ 0.172 -0.172] Feature 5 [ 0.029 -0.029] Feature 6 [ 0.019 -0.019]
favorite count: 0
tagged with: machine-learning
tagged with: python
type: AnsweredQuestion
score: 3
upvote count: 3
has title: Understanding the output of the TreeInterpreter with RandomForestClassifier
has answer: http://stackoverflow.com/a/48857959

http://stackoverflow.com/comment/84740683
comment on: http://stackoverflow.com/q/48868228
type: Comment
type: QuestionComment
has text: You’re missing the point. `sorted()` acts on *elements* not on *collections*. It does not preserve the collection type. It is implemented this way so it can accept a wide range of collections, both ordered and unordered. It only cares that it’s arguments are itereable. It then guarantees ordering by returning a simple ordered collection, i.e. a list.
score: 1

http://stackoverflow.com/comment/84754918
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48875339
has text: Do you have to use bokeh?

http://stackoverflow.com/q/48934473
has answer: http://stackoverflow.com/a/48934648
downvote count: 0
accepted answer: http://stackoverflow.com/a/48934595
favorite count: 0
tagged with: tuples
answer count: 3
tagged with: python
has comment: http://stackoverflow.com/comment/84875563
has answer: http://stackoverflow.com/a/48934651
type: AnsweredQuestion
has body: I have a python tuple whose elements are actually sentences. I want to compare the first letters of each element and if they are lowercase, I join it to the previous element. And if they aren't I just join the first element. For instance if I have: tuple1 = ('Traditionally, companies have been communicating', 'with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence', 'which is incomplete.') My result should be: tuple1 = ('Traditionally, companies have been communicating with consumers through traditional or old media.', 'The rapid changes in the cyber world.', 'This is another sentence which is incomplete.') This is my working code: i=0 while i&lt;(len(tuple1)-1): if tuple1[i+1][0].islower(): tuple1[i] + " " + tuple[i+1] i+=1 How can I achieve this? Thanks
type: Question
has answer: http://stackoverflow.com/a/48934595
score: 4
upvote count: 4
has title: Comparing and Concatenating Tuples in Python
possible better answer: http://stackoverflow.com/a/48934648
tagged with: concatenation

http://stackoverflow.com/q/48924059
answer count: 1
has comment: http://stackoverflow.com/comment/84854757
type: UnansweredQuestion
tagged with: sockets
has comment: http://stackoverflow.com/comment/84854564
tagged with: python
has title: Socket Program not working
has body: I am writing a simple socket program, but it's not working. Can you please help. import socket s = socket.socket() host = socket.gethostname() port = 12345 s.bind((host, port)) s.listen(5) while True: c, addr = s.accept() print ('Got connection from', addr) c.send('Thank you for connecting') c.close() The below error I use to get. s = socket.socket() TypeError: 'module' object is not callable
has comment: http://stackoverflow.com/comment/84854487
type: Question
linked to: http://stackoverflow.com/q/4534438
score: 0
has answer: http://stackoverflow.com/a/48924731

http://stackoverflow.com/a/48951807
has comment: http://stackoverflow.com/comment/84912423
upvote count: 1
has comment: http://stackoverflow.com/comment/84911830
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84912287
type: Answer
answers question: http://stackoverflow.com/q/48951408
downvote count: 0
has body: There's a few things at work here, lets go through them one by one. 1. Calculating the output value Use the request data to build the form, validate it, and then calculate the sum: if request.GET.get('submit_button'): input_form = InputForm(request.GET) if input_form.is_valid(): data = input_form.cleaned_data result = data["field1"] + data["field2"] 2. Read-only output It's not clear why you're using a submittable form field for data that is to be calculated by your app, as opposed to playing the result into a regular html 'label' in the template. If you really want/need to set the result in a form field, I'd at least make it read-only. See In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited? for an example of how to do that. 3. Set the output data in the form Set the output form/field's initial data to the result you have calculated. following on form the code at (1): result = data["field1"] + data["field2"] output_form = OutputForm(initial={"outfield": result}) then render the view as you're already doing: return render( request, 'index.html', {'input_form': input_form, 'output_form': output_form}, )
has comment: http://stackoverflow.com/comment/84912405
accepted answer of: http://stackoverflow.com/q/48951408
score: 1
has comment: http://stackoverflow.com/comment/84912563

http://stackoverflow.com/q/48887163
has comment: http://stackoverflow.com/comment/84809387
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84779816
tagged with: pyqtgraph
has answer: http://stackoverflow.com/a/48889004
type: Question
accepted answer: http://stackoverflow.com/a/48889004
has body: import sys from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg import numpy as np app = QtGui.QApplication(sys.argv) mw = QtGui.QMainWindow() mw.resize(800, 800) view = pg.GraphicsLayoutWidget() mw.setCentralWidget(view) mw.setWindowTitle('pyqtgraph example: ScatterPlot') w1 = view.addPlot() x = ['0:09:48', '0:09:49', '0:09:50', '0:09:51', '0:09:52', '0:09:53', '0:09:54', '0:09:55', '0:09:56', '0:09:57'] x1=[583, 584, 585, 586, 587, 588, 589, 590, 591, 592] y = [10, 8, 6, 4, 2, 20, 18, 16, 14, 12] import datetime import pytz UNIX_EPOCH_naive = datetime.datetime(1970, 1, 1, 0, 0) #offset-naive datetime UNIX_EPOCH_offset_aware = datetime.datetime(1970, 1, 1, 0, 0, tzinfo = pytz.utc) #offset-aware datetime UNIX_EPOCH = UNIX_EPOCH_naive TS_MULT_us = 1e6 def now_timestamp(ts_mult=TS_MULT_us, epoch=UNIX_EPOCH): print (int((datetime.datetime.utcnow() - epoch).total_seconds()*ts_mult)) return(int((datetime.datetime.utcnow() - epoch).total_seconds()*ts_mult)) def int2dt(ts, ts_mult=TS_MULT_us): return(datetime.datetime.utcfromtimestamp(float(ts)/ts_mult)) def dt2int(dt, ts_mult=TS_MULT_us, epoch=UNIX_EPOCH): delta = dt - epoch return(int(delta.total_seconds()*ts_mult)) def td2int(td, ts_mult=TS_MULT_us): return(int(td.total_seconds()*ts_mult)) def int2td(ts, ts_mult=TS_MULT_us): return(datetime.timedelta(seconds=float(ts)/ts_mult)) class TimeAxisItem(pg.AxisItem): def __init__(self, *args, **kwargs): super(TimeAxisItem, self).__init__(*args, **kwargs) def tickStrings(self, values, scale, spacing): # print values # print [int2dt(value).strftime("%H:%M:%S") for value in values] return [int2dt(value).strftime("%H:%M:%S") for value in values] # Create seed for the random time = QtCore.QTime.currentTime() QtCore.qsrand(time.msec()) for i in range(len(x)): s = pg.ScatterPlotItem([x1[i]], [y[i]], size=10, pen=pg.mkPen(None),axisItems={'bottom': x[i]}) # brush=pg.mkBrush(255, 255, 255, 120)) print s s.setBrush(QtGui.QBrush(QtGui.QColor(QtCore.qrand() % 256, QtCore.qrand() …
tagged with: python-2.7
tagged with: pyqt
answer count: 1
tagged with: pyqt4
score: 0
has title: Using time in Scatter plot items x-axis in pyqt4
tagged with: python

http://stackoverflow.com/q/48930987
type: Question
has body: Im using scrapy to extract user info on twitter but im currently having issues extracting the following, followers count etc using python. i can succesfully extract the id, screenname and avatar etc using.. user['ID'] = tweet['user_id'] user['name'] = item.xpath('.//@data-name').extract()[0] user['screen_name'] = item.xpath('.//@data-screen-name').extract()[0] user['avatar'] = item.xpath('.//div[@class="content"]/div[@class="stream-item-header"]/a/img/@src').extract()[0] twitter html unfortunately im having issues extracting the attributes count from the 'following' html for the user as i do not know the correct xpath to extract the data or if its possible... i can successfully extract the count using java script using the code below but having issues in python. following = $new.find('.ProfileNav-item--following .ProfileNav-value').first().text(); Any help and suggestions would be brilliant. thanks picture of twitter without javascript twitter without javascript
answer count: 1
downvote count: 0
favorite count: 0
type: UnansweredQuestion
has title: Python Twitter scrapy used for extracting twitter following, followers count etc
tagged with: python
score: 2
has answer: http://stackoverflow.com/a/48931534
upvote count: 2
tagged with: scrapy

http://stackoverflow.com/a/48895795
accepted answer of: http://stackoverflow.com/q/48895575
upvote count: 3
has comment: http://stackoverflow.com/comment/84797767
has comment: http://stackoverflow.com/comment/84797616
score: 3
has body: Slice-reversal makes things more concise and less nested: list(itertools.accumulate(A[::-1], max))[::-1] It's still something you'd want to bundle up into a function, though: from itertools import accumulate def suffix_maximums(l): return list(accumulate(l[::-1], max))[::-1] If you're using NumPy, you'd want numpy.maximum.accumulate: import numpy def numpy_suffix_maximums(array): return numpy.maximum.accumulate(array[::-1])[::-1]
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48895575
type: Answer

http://stackoverflow.com/q/48881296
downvote count: 0
has answer: http://stackoverflow.com/a/48881395
favorite count: 0
has comment: http://stackoverflow.com/comment/84766752
has answer: http://stackoverflow.com/a/48881379
upvote count: 2
type: UnansweredQuestion
tagged with: django
tagged with: python
tagged with: unit-testing
score: 2
has body: I'm doing some unit tests for my Django database and I keep getting a True value instead of the False I expected to get because that entry isn't in my database: import requests from django.test import TestCase from convoapp.models import InputInfo class InputInfoTestCase(TestCase): def setUp(self): #valid entry InputInfo.objects.create(name="Skywalker", conversation_id='1', message_body='I am a Jedi, like my father before me') #invalid entry - missing 'name' field InputInfo.objects.create(conversation_id='4', message_body="No, I am your Father") #invalid entry - integer entered instead of string InputInfo.objects.create(name='Leia', conversation_id=3, message_body='You are a little short') def test_for_valid_entries(self): luke = InputInfo.objects.get(name='Skywalker') self.assertTrue(bool(luke), True) def test_for_invalid_entries(self): vader = InputInfo.objects.get(conversation_id='4') #invalid because of non-strong entry for conversation_id #leia = InputInfo.objects.get(name='Leia') self.assertFalse(bool(vader)) I get the error: Traceback (most recent call last): File "C:\Users\ELITEBOOK\documents\github\challenge\convoapp\tests.py", line 25, in test_for_invalid_entries self.assertFalse(bool(vader)) AssertionError: True is not false Why is vaderreturning True? I assume it's because of InputInfo.objects.create(conversation_id='4', message_body="No, I am your Father"), is it because the entry is temporarily created? Because after the test ends it's not in my database
has title: Receiving True boolean value for Django unit tests instead of False
type: Question
has comment: http://stackoverflow.com/comment/84766751
answer count: 2

http://stackoverflow.com/a/48847399
has comment: http://stackoverflow.com/comment/84712262
type: AcceptedAnswer
type: Answer
has body: For structured data, pandas provides an efficient solution: from datetime import datetime import pandas as pd # read data from file df = pd.read_csv('data.csv') # this creates a dataframe as below: # id Start Time End Time # 0 0 2017-01-01 00:00:21 2017-01-01 00:11:41 # 1 1 2017-01-01 00:00:45 2017-01-01 00:11:46 # 2 2 2017-02-01 00:00:57 2017-02-01 00:22:08 # 3 3 2017-03-01 00:01:10 2017-03-01 00:11:42 # 4 4 2017-01-01 00:01:51 2017-01-01 00:12:57 # cast string columns to datetime df['Start Time'] = pd.to_datetime(df['Start Time']) df['End Time'] = pd.to_datetime(df['End Time']) def get_month(df): month = input('\nWhich month? January, February, March, April, May, or June?\n') return df[df['Start Time'].dt.month == datetime.strptime(month, '%B').month] get_month(df)
downvote count: 0
has comment: http://stackoverflow.com/comment/84719386
score: 3
has comment: http://stackoverflow.com/comment/84719327
accepted answer of: http://stackoverflow.com/q/48847264
has comment: http://stackoverflow.com/comment/84719403
has comment: http://stackoverflow.com/comment/84719365
upvote count: 3
answers question: http://stackoverflow.com/q/48847264

http://stackoverflow.com/comment/84926194
type: AnswerComment
score: 0
type: Comment
has text: OK, so I did that and now i get a syntax error that says "non-default argument follows default argument". what do i do with that?
comment on: http://stackoverflow.com/a/48942027

http://stackoverflow.com/a/48847136
type: Answer
answers question: http://stackoverflow.com/q/48846530
has body: An option you have is to change the x-axis labels. Assuming your plot's current x-axis is using the index of the dataframe, you can use this code: labels = data_count['start_date'].tolist() plt.xticks(data_count.index.values, labels, rotation='vertical')
score: 0

http://stackoverflow.com/q/48869611
favorite count: 0
has comment: http://stackoverflow.com/comment/84742988
tagged with: turtle-graphics
type: UnansweredQuestion
tagged with: python
answer count: 0
has body: I am trying to create a basic Turtle Race. My only requirement is that the turtles must move with each click on the screen. I am trying to use onscreenclick to call a function that moves the turtles forward a random amount and then checks their x-coordinates to determine if someone has won. import turtle import random import time def raceRound(): firstRacer.forward(random.randint(1, 10)) secondRacer.forward(random.randint(1, 10)) checkWinner() def firstRacerSetup(): # setup turtle def secondRacerSetup(): # set up second turtle def screenSetup(): # create screen def checkWinner(): if firstRacer.xcor() &gt;= 80: announcer.write("Congratualtions! You won!") if secondRacer.xcor() &gt;= 80: announcer.write("Sorry... You lost") wn = turtle.Screen() racerName = wn.textinput("Name Entry", "What would you like your turtle's name to be?") screenSetup() announcer = turtle.Turtle() announcer.hideturtle() announcer.penup() announcer.goto(0, -140) announcer.write("Welcome to the race!", align='center') time.sleep(3) firstRacerSetup() secondRacerSetup() announcer.write("Click to start the race!", align='center') wn.onscreenclick(raceRound) turtle.done() I'm just not sure where I am going wrong and some assistance would be greatly appreciated
upvote count: 1
has comment: http://stackoverflow.com/comment/84743307
type: Question
has comment: http://stackoverflow.com/comment/84743498
has comment: http://stackoverflow.com/comment/84743419
has title: Turtle onscreenclick not behaving as expected
has comment: http://stackoverflow.com/comment/84743195
has comment: http://stackoverflow.com/comment/84743123
downvote count: 0
score: 1

atomic
type: Tag
tag name: atomic
tags question: http://stackoverflow.com/q/48889144

http://stackoverflow.com/q/48903282
favorite count: 0
has body: I am creating a single script for setup and running whole Django project. venv_parent_dir = os.path.abspath(os.path.join(os.getcwd(),os.pardir)) venv_dir = os.path.abspath(os.path.join(venv_parent_dir, 'fvenv')) subprocess.run(args=['virtualenv', '-p', 'python3', venv_dir]) os.popen('/bin/bash --rcfile %s'%(venv_dir+'/bin/activate')) With the above code I created a virtual environment then activate this. Now I want to install the requirements.txt file in the activated virtual environment subprocess.run(args=['pip3', 'install', '-r', 'requirements.txt']) I tried with subprocess, but it's not installing in the virtual environment, it is installing in the operating system Python.
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48903372
accepted answer: http://stackoverflow.com/a/48903372
type: AnsweredQuestion
downvote count: 0
has title: How can install Django project requirement.txt with python script
type: Question
score: 3
upvote count: 3
tagged with: python-3.5
answer count: 1

http://stackoverflow.com/comment/84700918
comment on: http://stackoverflow.com/a/48848424
type: AnswerComment
score: 1
has text: I recommend replacing the first line with `missing['ROE'] = missing['ROE'].str.strip('%')`, and using `pd.to_numeric`.
type: Comment

http://stackoverflow.com/a/48960578
score: 5
has body: For starters and unrelated unless you want uneeded precision on something called "tax" I would put your tax in a string. from decimal import Decimal Decimal(3.16) =&gt; Decimal('3.160000000000000142108547152020037174224853515625') Decimal('3.16') =&gt; Decimal('3.16') Decimal('3.16') * Decimal(2) =&gt; Decimal('6.32') Decimal(3.16) * Decimal(2) =&gt; Decimal('6.320000000000000284217094304') Decimal(3.16) * Decimal(2.5434) =&gt; Decimal('8.037144000000000693745505487') Decimal('3.16') * Decimal('2.5434') =&gt; Decimal('8.037144') As for why it thinks you have a float from a DecimalField, that is unknown to me. So this is a partial answer at best, sorry.
answers question: http://stackoverflow.com/q/48960432
type: Answer
upvote count: 6
downvote count: 1

http://stackoverflow.com/comment/84641106
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48818535
has text: Thank you @Yilun Zhang, `figsize=(16,6)` did the trick. If you post this workaround as an aswer I will be pleased to accept it.
type: Comment

http://stackoverflow.com/comment/84830900
score: 0
comment on: http://stackoverflow.com/q/48912258
type: Comment
type: QuestionComment
has text: Possible duplicate of [Peak detection in a 2D array](https://stackoverflow.com/questions/3684484/peak-detection-in-a-2d-array)

http://stackoverflow.com/q/48951492
tagged with: dataframe
has title: Concatenate rows of Pandas multiindex dataframe by index value
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48951680
favorite count: 0
tagged with: pandas
tagged with: python
upvote count: 3
accepted answer: http://stackoverflow.com/a/48951680
has body: Given the following DataFrame, 00:00:00 01:00:00 02:00:00 Date ID 2018-01-01 A1 x1 x2 x3 B3 y1 y2 y3 2018-01-02 A1 x4 x5 x6 B3 y4 y5 y6 2018-03-02 A1 x7 x8 x9 B3 y7 y8 y9 which was obtained with import pandas as pd idx = pd.MultiIndex.from_product([pd.to_datetime(["2018-01-01", "2018-01-02", "2018-03-02"]), ["A1", "B3"]], names=["Date", "ID"]) col = pd.timedelta_range("00:00:00", periods=3, freq="1H") df = pd.DataFrame([["x1", "x2", "x3"], ["y1", "y2", "y3"], ["x4", "x5", "x6"], ["y4", "y5", "y6"], ["x7", "x8", "x9"], ["y7", "y8", "y9"]], idx, col) I want to transform it to the following form, datetime A1 B3 2018-01-01 00:00 x1 y1 2018-01-01 01:00 x2 y2 2018-01-01 02:00 x3 y3 2018-01-02 00:00 x4 y4 2018-01-02 01:00 x5 y5 2018-01-02 02:00 x6 y6 2018-03-02 00:00 x7 y7 2018-03-02 01:00 x8 y8 2018-03-02 02:00 x9 y9 But how?
type: Question
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/48851583
has title: SqlAlchemy: How to handle required circular foreign keys
has body: I would like to model a User having many Addresses and being able to have a "primary" address. I'm trying to create the strict guarantee that a User must have at least one Address by making the primary_address_id required. I would also like no orphaned addresses and therefore make Address.user_id also required. class User(db.Model): __tablename__ = 'Users' id = Column(Integer, primary_key=True) primary_address_id = Column(Integer, ForeignKey('Addresses.id'), nullable=False) primary_address = relationship(Address, primaryjoin=primary_address_id == Address.id, foreign_keys=primary_address_id) addresses = relationship(Address, primaryjoin=id == Address.building_id, foreign_keys=Address.building_id) class Address(db.Model): __tablename__ = 'Addresses' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('Users.id'), nullable=False) When I try the following insertion of a User with a single address it fails because primary_address_id is None. user = User() address1.user = user user.addresses = [address1] user.primary_address = address1 session.add_all([address1, user]) session.commit() cursor.execute(statement, parameters) sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) null value in column "primary_address_id" violates not-null constraint [SQL: 'INSERT INTO "Users" (primary_address_id) VALUES (%(primary_address_id)s) RETURNING "Users".id'] [parameters: {'primary_address_id': None}] (Background on this error at: http://sqlalche.me/e/gkpj) Is there a way around the chicken-egg problem with SqlAlchemy and Postgres without having to make one side nullable? Alternatively is there another way to model this with the same referential requirements?
linked to: http://stackoverflow.com/q/8394177
has comment: http://stackoverflow.com/comment/84708692
answer count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
score: 1
tagged with: sqlalchemy
type: Question
downvote count: 0
has comment: http://stackoverflow.com/comment/121734594
favorite count: 0
tagged with: postgresql
has comment: http://stackoverflow.com/comment/84716386
tagged with: sql

http://stackoverflow.com/comment/84754020
comment on: http://stackoverflow.com/q/48874733
score: 0
type: Comment
type: QuestionComment
has text: Are your `Density` values available by any chance? Right now it is not possible to test your code.

http://stackoverflow.com/comment/84858800
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48926353
has text: Thanks, that fixed it. But what does "listening on an addresses" mean?
type: Comment

http://stackoverflow.com/comment/84653549
comment on: http://stackoverflow.com/a/48824958
score: 0
has text: For the sanity of every python deverloper out there, pretty please never use the `params,` syntax to create a tuple.
type: Comment
type: AnswerComment

gunicorn
tags question: http://stackoverflow.com/q/48937210
type: Tag
tags question: http://stackoverflow.com/q/48923230
tags question: http://stackoverflow.com/q/48917810
tags question: http://stackoverflow.com/q/48906173
tags question: http://stackoverflow.com/q/48859606
tags question: http://stackoverflow.com/q/48936687
tags question: http://stackoverflow.com/q/48954705
tag name: gunicorn

http://stackoverflow.com/a/68471772
type: Answer
has body: I have tried and tested this import yaml with open(r'test.yaml') as file: documents = yaml.full_load(file) for item, doc in documents.items(): print(item, &quot;:&quot;, doc)
score: 0
answers question: http://stackoverflow.com/q/48825011

http://stackoverflow.com/q/48960191
upvote count: 1
type: Question
tagged with: time-series
accepted answer: http://stackoverflow.com/a/48960230
tagged with: dataframe
has title: create customized transpose of data in python
has answer: http://stackoverflow.com/a/48960230
answer count: 1
downvote count: 0
favorite count: 0
tagged with: transpose
tagged with: python
has body: I have a dataframe like this: ID Month Price Sale sk1 1 100 6 sk1 2 120 7 sk1 3 130 8 sk2 1 50 3 sk2 2 60 4 sk2 3 70 5 Desired output: ID 1_Price 2_Price 3_Price 1_Sale 2_Sale 3_Sale sk1 100 120 130 6 7 8 sk2 50 60 70 3 4 5 I tried pandas transpose with index option, but it's not giving desired results.
type: AnsweredQuestion
score: 1

http://stackoverflow.com/a/48964944
answers question: http://stackoverflow.com/q/48944037
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84972872
has body: It looks like it is crashing because you have not added the "logo.ico" file to the package, so when master.iconbitmap('logo.ico') looks for the icon, it is not there. With the command -i 'C:\temp\Util\logo.ico' you are telling pyinstaller to set that icon file as the windows icon, but this is not the same as including it in the package. To do that try including this in your pyinstaller command: --add-data "C:\temp\Util\logo.ico;." The "." after the semi-colon tells pyinstaller where to put the file. In this case it will put it into the same folder as the .exe file.
score: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84982113
has comment: http://stackoverflow.com/comment/85218493

http://stackoverflow.com/comment/90056754
has text: If you are lazy like me and tried to transpose, it won't work. Gotta type out more characters and go with the response below.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48841624
score: 0

remote-debugging
tag name: remote-debugging
type: Tag
tags question: http://stackoverflow.com/q/48958221

http://stackoverflow.com/comment/84936949
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48931843
type: Comment
has text: can you show the code that gives the error?

http://stackoverflow.com/comment/84690228
type: Comment
type: QuestionComment
score: 1
has text: Do you need to store the entire file in the list at once, or can you just iterate over the file object?
comment on: http://stackoverflow.com/q/48842992

http://stackoverflow.com/q/48841074
type: Question
has comment: http://stackoverflow.com/comment/84686346
has answer: http://stackoverflow.com/a/77835022
answer count: 2
has comment: http://stackoverflow.com/comment/84686365
downvote count: 0
upvote count: 7
tagged with: virtualenv
favorite count: 0
has body: I'm trying to use the collectstatic command in pythonanywhere's bash terminal: python manage.py collectstatic But I get: PermissionError: [Errno 13] Permission denied: '/static' Please can anyone help? I've been trying to fix this for two days now. Here's the full error : nomadpad-virtualenv) 11:51 ~/nomadpad (master)$ python manage.py collectstatic Copying '/home/DMells123/.virtualenvs/nomadpad-virtualenv/lib/python3.6/site-packages/djang o/contrib/admin/static/admin/img/inline-delete.svg' Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/DMells123/.virtualenvs/nomadpad-virtualenv/lib/python3.6/site-packages/django /core/management/init.py", line 364, in execute_from_command_line utility.execute() File "/home/DMells123/.virtualenvs/nomadpad-virtualenv/lib/python3.6/site-packages/django /core/management/init.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/DMells123/.virtualenvs/nomadpad-virtualenv/lib/python3.6/site-packages/django /core/management/base.py", line 283, in run_from_argv self.execute(*args, cmd_options) File "/home/DMells123/.virtualenvs/nomadpad-virtualenv/lib/python3.6/site-packages/django /core/management/base.py", line 330, in execute output = self.handle(*args, options) File "/home/DMells123/.virtualenvs/nomadpad-virtualenv/lib/python3.6/site-packages/django /contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle collected = self.collect() File "/home/DMells123/.virtualenvs/nomadpad-virtualenv/lib/python3.6/site-packages/django /contrib/staticfiles/management/commands/collectstatic.py", line 124, in collect handler(path, prefixed_path, storage) File "/home/DMells123/.virtualenvs/nomadpad-virtualenv/lib/python3.6/site-packages/django /contrib/staticfiles/management/commands/collectstatic.py", line 364, in copy_file self.storage.save(prefixed_path, source_file) File "/home/DMells123/.virtualenvs/nomadpad-virtualenv/lib…
possible better answer: http://stackoverflow.com/a/77835022
has answer: http://stackoverflow.com/a/48842262
accepted answer: http://stackoverflow.com/a/48842262
tagged with: django
tagged with: python
tagged with: pythonanywhere
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84688496
has title: Collectstatic - permission denied, pythonanywhere bash terminal
score: 7

http://stackoverflow.com/comment/84755882
type: QuestionComment
has text: SKU=root.xpath("./ul/li/b[.='SKU']/following-sibling::text()[1]")
comment on: http://stackoverflow.com/q/48875911
score: 0
type: Comment

http://stackoverflow.com/comment/117644675
type: Comment
score: 1
has text: Note that you cannot rely on the existence of `__init__.py` files to solve this, especially not in newer versions of Python where a single package can span multiple different folders on a file system. For example see the docs on [namespace packages](https://packaging.python.org/guides/packaging-namespace-packages/) in Python.
type: AnswerComment
comment on: http://stackoverflow.com/a/48881746

http://stackoverflow.com/comment/84864003
has text: In the debugger I see: dtype: object
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48915218
score: 0

http://stackoverflow.com/comment/84789611
has text: actually tweepy library says `Python 2.6 and 2.7, 3.3, 3.4, 3.5 & 3.6 are supported.` maybe 3.7 is not compatible yet.. virtualenv with 3.6 should do the trick.
score: 0
comment on: http://stackoverflow.com/q/48891714
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48882705
has body: From the documentation for timedelta objects: Note that normalization of negative values may be surprising at first. For example: &gt;&gt;&gt; from datetime import timedelta &gt;&gt;&gt; d = timedelta(microseconds=-1) &gt;&gt;&gt; (d.days, d.seconds, d.microseconds) (-1, 86399, 999999) This occurs in both Python 2.7 and Python 3. The reason for the observed result is simple: a , b = datetime.datetime.now(), datetime.datetime.now() # here datetime.now() in a will be &lt;= b. # That is because they will be executed separately at different CPU clock cycle. a - b # datetime.timedelta(-1, 86399, 999973) b - a # datetime.timedelta(0, 0, 27) To get the proper time difference: (tnow - datetime.datetime.now()).total_seconds() # output: -1.751166 See also Python timedelta issue with negative values.
accepted answer of: http://stackoverflow.com/q/48882468
upvote count: 7
answers question: http://stackoverflow.com/q/48882468
type: AcceptedAnswer
downvote count: 0
score: 7
type: Answer

http://stackoverflow.com/a/48832851
type: Answer
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48832690
has body: You are defining Getmodel as an instance method. So it have to be called on an instance of the class Test. To create an instance of class Test you can write instance_of_test = Test() Now you can call Getmodel on instance_of_test instance_of_test.Getmodel() You can shorten this process by writing Test().Getmodel() Note that self is (usually) passed hiddenly when calling an instance method; it represents the instance calling the method. Consider the following class Pizza class Pizza: def __init__(self, size): self.size = size def get_size(self): return self.size First you need to create an instance of Pizza mypizza = Pizza(42) then you can call the instance method get_size on mypizza mypizza.get_size()
upvote count: 2

http://stackoverflow.com/q/48868713
answer count: 1
favorite count: 0
tagged with: python-3.x
tagged with: python
has answer: http://stackoverflow.com/a/48881615
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84742440
score: 1
has title: Streaming twitter data and saving to csv in Python
tagged with: twitter
upvote count: 1
has comment: http://stackoverflow.com/comment/84742120
type: Question
tagged with: export-to-csv
accepted answer: http://stackoverflow.com/a/48881615
downvote count: 0
linked to: http://stackoverflow.com/q/48090148
has comment: http://stackoverflow.com/comment/84741281
tagged with: sentiment-analysis
has body: I’m trying to follow this tutorial on streaming tweets from twitter into a database, before then converting the database to a CSV file. I can implement the streaming API feature to capture data fine, however when trying to save the data in a csv file I am having problems. At first I encountered a similar problem to this question where I receive the following error. AttributeError: module 'dataset' has no attribute 'freeze' The solution removes the error when running the script but I am left with no CSV file and empty DB file instead. I have looked over all the documentation but I'm really unsure on what I am doing wrong and how I can proceed. My GitHub with all source code can be found here

http://stackoverflow.com/comment/84871811
score: 0
has text: Yes. Depth is 16bits in both, and the sample is selected manually via Audacity. I export the labels corresponding to the selection - so exactly the same start and end timestamp as when I export via Audacity interface. I updated the post with mediainfo outputs for both files Files are available here https://files.fm/u/mrq2zjgf
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48923943

http://stackoverflow.com/comment/84811434
score: 1
has text: I know that works. My problem is that I can not find the way to prepare the string. When I read the row I obtain "b'\xe7\x94\xb3\xe8\xbf\xaa\xe8\..." But I need b'\xe7\x94\xb3\xe8\xbf\xaa\xe8...'
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48902965

http://stackoverflow.com/comment/84650226
comment on: http://stackoverflow.com/a/48822043
score: 0
has text: On screenshot you just pass the string into `all_text` while in code you use `driver.find_element_by_xpath("//li[@role='checkbox']/div[@class='extend_clickable']").get_attribute("innerHTML")`. Values of these variables are different!
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84716799
type: Comment
comment on: http://stackoverflow.com/a/48846403
score: 0
type: AnswerComment
has text: `plt.draw()` does the same as `plt.gcf().canvas.draw_idle()`. `fig.canvas.draw()` is different, as it does not draw the current figure, but the figure `fig`. But since there is only one figure in the code, this is then again the same.

http://stackoverflow.com/comment/84747646
type: QuestionComment
has text: @Silvermoon My strongest suggestion is that you edit and clarify your question so that we can understand your problem better
comment on: http://stackoverflow.com/q/48871785
score: 0
type: Comment

http://stackoverflow.com/comment/84837564
comment on: http://stackoverflow.com/q/48915307
score: 0
type: QuestionComment
has text: Thnx for correcting it but the issue is still there....
type: Comment

http://stackoverflow.com/a/48827620
has comment: http://stackoverflow.com/comment/84659958
answers question: http://stackoverflow.com/q/48827226
has body: You can use converters: In [156]: def conv(val, default_val=999): ...: try: ...: return int(val) ...: except ValueError: ...: return default_val ...: In [157]: conv('a') Out[157]: 999 In [158]: pd.read_csv(r'C:\Temp\test.csv', converters={'a':conv}) Out[158]: a b c 0 1 11 2000-01-01 1 999 12 2000-01-02 2 3 13 2000-01-02 Another approach, would be to convert columns in a vectorized way after parsing a CSV file: In [166]: df = pd.read_csv(r'C:\Temp\test.csv', parse_dates=['c']) In [167]: df Out[167]: a b c 0 1 AAA 2000-01-01 1 XXX 12 2000-01-02 2 3 13 2000-01-02 In [168]: df.dtypes Out[168]: a object b object c datetime64[ns] dtype: object In [169]: int_cols = ['a','b'] In [170]: df[int_cols] = df[int_cols].apply(pd.to_numeric, errors='coerce').fillna(999).astype(int) In [171]: df Out[171]: a b c 0 1 999 2000-01-01 1 999 12 2000-01-02 2 3 13 2000-01-02 In [172]: df.dtypes Out[172]: a int32 b int32 c datetime64[ns] dtype: object Speed comparison for 300.000 rows DF: In [175]: df = pd.concat([df] * 10**5, ignore_index=True) In [176]: df.shape Out[176]: (300000, 3) In [177]: filename = r'C:\Temp\test.csv' In [184]: df.to_csv(filename, index=False) In [185]: %%timeit ...: df = pd.read_csv(filename, parse_dates=['c'], converters={'a':conv, 'b':conv}) ...: 632 ms ± 25.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [186]: %%timeit ...: df = pd.read_csv(filename, parse_dates=['c']) ...: df[int_cols] = df[int_cols].apply(pd.to_numeric, errors='coerce').fillna(999).astype(int) ...: 706 ms ± 60.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
upvote count: 5
score: 5
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48827226
type: Answer

http://stackoverflow.com/q/48936843
tagged with: python
has answer: http://stackoverflow.com/a/49020828
has body: I'm creating a survey application that displays the survey question and choices and allows the user to pick a choice through the Flask-WTForms package. The form uses a RadioField and seems to fail form.validate() when populating the choices attribute dynamically. When I manually enter in the choices as such: class SurveyAnswerForm(FlaskForm): answers = RadioField('Answers', coerce=str, choices=[('18-25', '18-25'), ('26-35', '26-35')]) form.validate() returns True and there are no errors in form.error. When I decide to populate the choices attribute dynamically (see below), form.validate() returns False and form.error returns: {'answers': ['Not a valid choice']}. I've been working at this for hours and am not sure why form.validate() returns False. forms.py: from flask_wtf import FlaskForm from wtforms import RadioField class SurveyAnswerForm(FlaskForm): answers = RadioField('Answers', coerce=str, choices=[]) app.py: @app.route('/survey/<int:survey_id>/questions', methods=['GET', 'POST']) def survey_questions(survey_id): survey = Survey.query.filter_by(id=survey_id).first() page = request.args.get('page', 1, type=int) questions = SurveyQuestion.query.filter_by(survey_id=survey_id)\ .order_by(SurveyQuestion.id)\ .paginate(page, 1, True) for question in questions.items: question_id = question.id choices = QuestionChoices.query\ .join(SurveyQuestion, and_(QuestionChoices.question_id==question_id, SurveyQuestion.survey_id==survey_id)).all() form = SurveyAnswerForm(request.form) form.answers.choices = [(choice.choice, choice.choice)\ for choice in choices] if request.method =='POST' and form.validate(): print('Successful POST') next_url = url_for('survey_questions', survey_id=survey.id, page=questions.next_num)\ if questions.has_next else None prev_url = url_for('survey_questions', survey_id=survey.id, page=questions.prev_num)\ if questions.has_prev else None return render_template('survey_question.html', survey=survey, questions=questions.items, choices=choices, form=for…
tagged with: flask-wtforms
has title: Flask-WTForms form.validate() fails on dynamic choices
upvote count: 1
type: AnsweredQuestion
tagged with: wtforms
accepted answer: http://stackoverflow.com/a/49020828
has comment: http://stackoverflow.com/comment/84888075
type: Question
has comment: http://stackoverflow.com/comment/84881443
answer count: 1
downvote count: 0
score: 1
tagged with: flask
favorite count: 0
has comment: http://stackoverflow.com/comment/84884837
has comment: http://stackoverflow.com/comment/84884745
has comment: http://stackoverflow.com/comment/84881242

http://stackoverflow.com/a/48849086
type: Answer
has body: You probably wanna use Popen.communicate(input=None, timeout=None) and set the shell arg to true. Then you wanna wait on the process output stream for the response to your command. Note: Popen.communicate requires the input to be byte-encoded. The output of Popen.communicate is also byte encoded, so you need to do a str.decode() on it to extract the encoded strings. All of this is fully documented in the Python API. I would suggest you read the manual. Or, you could use a library like this one which wraps all of this stuff for you. import subprocess proc = subprocess.Popen('ls', stdout=subprocess.PIPE, stdin=subprocess.PIPE) try: outs, errs = proc.communicate(timeout=15) # use input= param if you need to proc.wait() except TimeoutExpired: proc.kill() outs, errs = proc.communicate() print ('%s, %s' % (outs, errs)) Output and comparison to actual 'ls' output: $ python popen_ex.py b'__pycache__\npopen_ex.py\n', None $ ls __pycache__ popen_ex.py Any additional commands you need to send to popen can be sent in proc.communicate. If you REALLY want to communicate to an interactive shell, Popen.communicate() allows for a ONE TIME write to stdin and read from stdout/stderr. After one call to Popen.communicate(), the input/output/error streams are closed by subprocess. IF YOU WANT A FULLY INTERACTIVE SHELL, you MUST either write one yourself, or use a library, like the one I linked. import subprocess proc = subprocess.Popen('sh', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) try: outs, errs = proc.communicate(input='ls'.encode('ascii'), timeout=15) proc.wait() print ('%s, %s' % (outs, errs)) proc = subprocess.Popen('sh', stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE) outs, errs = proc.communicate(input='ps'.encode('ascii'), timeout=15) proc.wait() print ('%s, %s' % (outs, errs)) except TimeoutError: proc.kill() outs, errs = proc.communicate() Output and comparison to actual 'ls', 'ps' $ python popen_ex.py b'__pycache__\npopen_e…
has comment: http://stackoverflow.com/comment/85255709
accepted answer of: http://stackoverflow.com/q/48849044
has comment: http://stackoverflow.com/comment/85113016
answers question: http://stackoverflow.com/q/48849044
score: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/85112914

http://stackoverflow.com/a/51233379
type: Answer
has comment: http://stackoverflow.com/comment/90570968
downvote count: 2
has comment: http://stackoverflow.com/comment/120813973
score: 3
upvote count: 5
has body: I have the same error (zipimport.ZipImportError: can't find module 'encodings'). I think it has to do with Python 3.7 not supporting pyinstaller yet...
has comment: http://stackoverflow.com/comment/89998316
answers question: http://stackoverflow.com/q/48872724
has comment: http://stackoverflow.com/comment/90861623
has comment: http://stackoverflow.com/comment/90570943

http://stackoverflow.com/comment/84742871
has text: yep, added it in. Basically, any row of dayofweek that equals 5 or 6 needs to increase the value of dispatch_working_days by +1
comment on: http://stackoverflow.com/q/48869471
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48903988
accepted answer of: http://stackoverflow.com/q/48902391
upvote count: 4
downvote count: 0
score: 4
has body: Assuming that the line in your file is exactly like this: b'\xe7\x94\xb3\xe8\xbf\xaa\xe8\xa5\xbf\xe8\xb7\xaf255\xe5\xbc\x84660\xe5\x8f\xb7\xe5\x92\x8c665\xe5\x8f\xb7 \xe4\xb8\xad\xe5\x9b\xbd\xe4\xb8\x8a\xe6\xb5\xb7\xe6\xb5\xa6\xe4\xb8\x9c\xe6\x96\xb0\xe5\x8c\xba 201205' And reading the line from the file gives the output: &gt;&gt;&gt; line "b'\\xe7\\x94\\xb3\\xe8\\xbf\\xaa\\xe8\\xa5\\xbf\\xe8\\xb7\\xaf255\\xe5\\xbc\\x84660\\xe5\\x8f\\xb7\\xe5\\x92\\x8c665\\xe5\\x8f\\xb7 \\xe4\\xb8\\xad\\xe5\\x9b\\xbd\\xe4\\xb8\\x8a\\xe6\\xb5\\xb7\\xe6\\xb5\\xa6\\xe4\\xb8\\x9c\\xe6\\x96\\xb0\\xe5\\x8c\\xba 201205'"` You can try to use eval() function: with open(r"your_csv.csv", "r") as csvfile: for line in csvfile: # when you reach the desired line b = eval(line).decode('utf-8') Output: &gt;&gt;&gt; print(b) '申迪西路255弄660号和665号 中国上海浦东新区 201205'
has comment: http://stackoverflow.com/comment/84816239
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84816205
has comment: http://stackoverflow.com/comment/84816150
type: Answer
answers question: http://stackoverflow.com/q/48902391

http://stackoverflow.com/q/48833259
tagged with: django-rest-framework
score: 0
answer count: 1
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48836438
tagged with: django
tagged with: python
has title: How to do a Customer Logger for Django to Capture Response and Request
type: Question
has body: I'm looking into differen't ways to capture the response object, request object, and performance in Django to create a custom json elk logger that will build audit logs. I'm not sure what approach is best to take here. I was looking at custom middleware but I've never done that. I tried to look up if it was possible to use a decorator to do this but doesn't seem like it. Also, I use the django rest framework so I also have to figure out how to integrate the middleware if thats the route or whatever solution to DRF as well. Looking for suggestions.

http://stackoverflow.com/q/48946439
has body: 2 files have to be checked: File archive.txt includes archived usernames. File import.txt includes usernames that have to be checked with archive.txt. If the imported usernames are not included in archive.txt they should be saved to a third output file (new.txt) I found some interesting code snippet, but it only compares and writes new entries directly into the file. I can't manage to write it to a third file. Any ideas? with open('./export/import.txt', 'r') as infile, open('./process/new.txt', 'w') as outfile: seen = set() for line in infile: for word in line.split(): if word not in seen: seen.add(word) outfile.write('{}\n'.format(word))
score: 0
answer count: 1
has title: Compare two files for duplicates and send result to a third file
tagged with: python
has answer: http://stackoverflow.com/a/48946773
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48946773
tagged with: duplicates
type: Question

http://stackoverflow.com/a/48838085
has body: You made quite a few errors in your code. What is x+1? It will be x=x+1. Please go through the basics first. Why are you checking if x==0, right after assigning x=0? Don't you think the if will always be yes? Your code in a cleaned format. Hope this works. import random l1 = 'q w e r t y u i o p a s d f g h j k l z x c v b n m 1 2 3 4 5 6 7 8 9 0' l2 = l1.split() def genpass(n): x = 0 password = '' if n &lt; 100: while n &gt; x: password = password + random.choice(l2) x=x + 1 print(password) else: print ('Sorry, too long') print("Enter how long you want your password to be") genpass(int(input()))
answers question: http://stackoverflow.com/q/48838050
score: 0
type: Answer

http://stackoverflow.com/comment/84820591
type: Comment
type: QuestionComment
has text: I added a link to an image in the description. I apologize for not providing detailed information. This is my first time posting on stack overflow.
comment on: http://stackoverflow.com/q/48906828
score: 0

http://stackoverflow.com/comment/85032861
has text: Hi mao, thanks for your comment. I added the python version. Please pardon my naivety, but how do I determine (2) and (3) ?
type: Comment
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48954519

python-multiprocessing
tags question: http://stackoverflow.com/q/48935328
tags question: http://stackoverflow.com/q/48875601
tags question: http://stackoverflow.com/q/48842585
tags question: http://stackoverflow.com/q/48959987
type: Tag
tags question: http://stackoverflow.com/q/48845156
tags question: http://stackoverflow.com/q/48915440
tag name: python-multiprocessing
tags question: http://stackoverflow.com/q/48879277
tags question: http://stackoverflow.com/q/48841645
tags question: http://stackoverflow.com/q/48943211
tags question: http://stackoverflow.com/q/48913156
tags question: http://stackoverflow.com/q/48811375
tags question: http://stackoverflow.com/q/48838346
tags question: http://stackoverflow.com/q/48870608

http://stackoverflow.com/comment/84746399
has text: You are trying to use the *module* as a base class, not the class defined *in* the module.
comment on: http://stackoverflow.com/q/48871351
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48951112
has body: A problem is, even if you lock the test file down and even if you lock the .txt document down, the result can still be manipulated. E. g. in my variables submission I could do something like this: import filecmp filecmp.cmp = lambda x, y: True Adding this anywhere in the variables function, your test file would always pass. You probably want to completely isolate the student code when you execute it. Maybe you can use something like CodeJail to create a sandbox to execute student code and then separately compare the result.
answers question: http://stackoverflow.com/q/48950054
score: 0
type: Answer

http://stackoverflow.com/comment/84739948
comment on: http://stackoverflow.com/q/48867691
has text: One thing to point out: the labels (y_xxxx) should be in mnist.[train|test].labels, rather than mnist.[train|test].images
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84735601
score: 0
comment on: http://stackoverflow.com/q/48865972
type: QuestionComment
type: Comment
has text: @Slam what do you mean sorry ? they are values of 'ti' as you can see when you scroll down in the code provided. You can run the whole code in your envirnment

http://stackoverflow.com/comment/84766971
has text: Thank you for your example. I have tried it in pandas and dask. It works in pandas perfectly fine, but is not working in dask at all.
type: Comment
comment on: http://stackoverflow.com/a/48870412
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84798096
has text: Yes I have renamed the appname in the traceback and fixed the typo. The line of code `from appname.core.templatetags.customised_template_tags import absolute_static, alternative_file, file_url` is located in the `models.py` file.
comment on: http://stackoverflow.com/q/48896000
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48884734
score: 2
answers question: http://stackoverflow.com/q/48883647
has body: re._compile first checks if the argument is cached, and then if it's already compiled. So when you pass a compiled pattern to re.whatever it wastes some time computing and looking up a cache key which actually is never going to match. Repring the pattern and OrderedDict lookups are heavy operations that seem to explain the discrepancy you're observing. A possible rationale for this behaviour is that _compile is optimized for string patterns, which is its primary use case, and designed to return a cache hit as soon as possible. Here are some timings: from time import time import re import sys print(sys.version) pat = '\d{2}-\d{3,5}' loops = 1000000 re.purge() t = time() for _ in range(loops): re._compile(pat, 0) print('compile string ', time() - t) re.purge() rc = re._compile(pat, 0) t = time() for _ in range(loops): re._compile(rc, 0) print('compile compiled', time() - t) Results: $ python3 test.py 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] compile string 0.5387749671936035 compile compiled 0.7378756999969482 $ python2 test.py 2.7.12 (default, Nov 20 2017, 18:23:56) [GCC 5.4.0 20160609] ('compile string ', 0.5074479579925537) ('compile compiled', 1.3561439514160156)
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48883647
type: Answer
upvote count: 2

http://stackoverflow.com/comment/84642680
comment on: http://stackoverflow.com/q/48818561
has text: Please and Thank You.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/q/48826450
tagged with: python
has answer: http://stackoverflow.com/a/53880209
has body: I would like to add a new line to shopify liquid file (basically it's an HTML file with some variables) after I find a pattern I look for in the liquid string. As this is a valid HTML file by saying after I mean add a new line as a new element in the html in a way that doesn't break the layout of the html. I was thinking of using BeautifulSoap to load the string and do the manipulations, what do you think? Is there a better way? How would you do the above? Thanks
type: UnansweredQuestion
score: 1
has title: Shopify liquid pattern matching using Python
upvote count: 1
type: Question
answer count: 1
downvote count: 0
tagged with: shopify
favorite count: 0
tagged with: beautifulsoup

http://stackoverflow.com/q/48838533
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48838691
favorite count: 0
tagged with: python-3.x
type: Question
possible better answer: http://stackoverflow.com/a/48838691
answer count: 2
tagged with: python
tagged with: easy-install
score: -1
has body: I typed in this command in the terminal easy_install PIL The terminal said this: *error: can't create or remove files in install directory The following error occurred while trying to add or remove files in the installation directory: [Errno 13] Permission denied: '/Library/Python/2.7/site-packages/test-easy-install-639.pth' The installation directory you specified (via --install-dir, --prefix, or the distutils default setting) was: /Library/Python/2.7/site-packages/ Perhaps your account does not have write access to this directory? If the installation directory is a system-owned directory, you may need to sign in as the administrator or "root" account. If you do not have administrative access to this machine, you may wish to choose a different installation directory, preferably one that is listed in your PYTHONPATH environment variable. For information on other options, you may wish to consult the documentation at: https://pythonhosted.org/setuptools/easy_install.html Please make the appropriate changes for your system and try again.* How should I continue?
downvote count: 2
upvote count: 1
has answer: http://stackoverflow.com/a/48839281
linked to: http://stackoverflow.com/q/21055859
has title: I'm not able to install PIL. Terminal says access denied to directory. How to gain access to the directory
tagged with: python-imaging-library
accepted answer: http://stackoverflow.com/a/48839281
has comment: http://stackoverflow.com/comment/84681709
tagged with: python-2.7

http://stackoverflow.com/q/48815872
upvote count: 22
has answer: http://stackoverflow.com/a/48815977
answer count: 1
downvote count: 0
has title: testing postgres db python
favorite count: 0
tagged with: postgresql
tagged with: python
has body: I don't understand how to test my repositories. I want to be sure that I really saved object with all of it parameters into database, and when I execute my SQL statement I really received what I am supposed to. But, I cannot put "CREATE TABLE test_table" in setUp method of unittest case because it will be created multiple times (tests of the same testcase are runned in parallel). So, as long as I create 2 methods in the same class which needs to work on the same table, it won't work (name clash of tables) Same, I cannot put "CREATE TABLE test_table" setUpModule, because, now the table is created once, but since tests are runned in parallel, there is nothing which prevents from inserting the same object multiple times into my table, which breakes the unicity constraint of some field. Same, I cannot "CREATE SCHEMA some_random_schema_name" in every method, because I need to globally "SET search_path TO ..." for a given Database, so every method runned in parallel will be affected. The only way I see is to create to "CREATE DATABASE" for each test, and with unique name, and establish a invidual connection to each database.. This looks extreeeemly wasteful. Is there a better way? Also, I cannot use SQLite in memory because I need to test PostgreSQL.
type: AnsweredQuestion
score: 22
accepted answer: http://stackoverflow.com/a/48815977
tagged with: python-unittest
type: Question

http://stackoverflow.com/comment/84825680
comment on: http://stackoverflow.com/a/48894921
score: 0
type: Comment
has text: I really appreciate your help! the code worked flawlessly!
type: AnswerComment

http://stackoverflow.com/comment/84663287
type: Comment
score: 1
type: AnswerComment
has text: That only handles one file, OP wants multiple files
comment on: http://stackoverflow.com/a/48829267

http://stackoverflow.com/q/48930505
has body: I would like to be able to create an array, making it build half of the father and the half of the child, i tried something like this: NUM_PROC = 1 children = [] a = [] for process in range(NUM_PROC): pid = os.fork() if pid == 0: a.append(3) os._exit(0) else: a.append(2) for i, proc in enumerate(children): os.waitpid(proc, 0) print("Parent process is closing") but it does not work, how could I do?(the final order of array isn't important) the final result is : a = [2] i would like : a= [2,3]
answer count: 1
has comment: http://stackoverflow.com/comment/84867685
favorite count: 0
tagged with: fork
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84867908
downvote count: 1
has answer: http://stackoverflow.com/a/48936146
type: Question
has comment: http://stackoverflow.com/comment/84867744
has title: Python - how to combine the value of the child and the father in fork?
upvote count: 0
tagged with: arrays
score: -1

http://stackoverflow.com/q/48885804
tagged with: python
type: Question
has answer: http://stackoverflow.com/a/48885928
has title: Find architecture of a .so file (Python)
has answer: http://stackoverflow.com/a/48885936
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84776535
type: UnansweredQuestion
has body: I would like to find inside python for what architecture a file (in my case .so) has been build. I known that I can see this in the terminal with the 'file' command. Example: file libstuff.so gives as output: libstuff.so: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, BuildID[sha1]=3cac824147a873a51c2862fea4e83cfed46c8d9, not stripped I need this in my python script so I don't load the .so file if I running my program on a ARM aarch64 architecture. I seem to be unable to find anything on this matter... Is this not possible?

http://stackoverflow.com/comment/84927872
comment on: http://stackoverflow.com/q/48960699
has text: I did try what it suggests to do as I describe in the question. Unfortunately, it just doesn’t work. It would be nice if someone who does make this change successfully could share how they do.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84684091
type: QuestionComment
comment on: http://stackoverflow.com/q/48839155
type: Comment
score: 0
has text: Please provide a [mcve] that demonstrates your issue.

http://stackoverflow.com/a/48817979
type: Answer
has body: You can use some Numpy magic. Use count and broadcasting to compare each combination. from numpy.core.defchararray import count c1 = df.c1.values.astype(str) c2 = df.c2.values.astype(str) pd.Series( count(c1, c2[:, None]).sum(1), c2 ) han solo 2 r2d2 1 finn 1 the emporer 0 c3po 0 leia organa 1 darth vader 1 dtype: int64
has comment: http://stackoverflow.com/comment/84640101
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48817935
has comment: http://stackoverflow.com/comment/84640092
score: 3
answers question: http://stackoverflow.com/q/48817935
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84643327

http://stackoverflow.com/a/48865189
answers question: http://stackoverflow.com/q/48865040
accepted answer of: http://stackoverflow.com/q/48865040
type: AcceptedAnswer
type: Answer
downvote count: 0
has body: In Python 3 (introduced in 3.2, ability to pass the function added in 3.3) this is already implemented, in itertools.accumulate. Just use it like this: from itertools import accumulate list(accumulate([5, 4, 3, 2], lambda a, b: a*b)) # [5, 20, 60, 120] If you are using an earlier Python version, or want to implement it yourself, and you really want any arbitrary lambda (that takes two arguments) to work, then you could use the generator which is given in the documentation of the above: def accumulate(iterable, func=operator.add): 'Return running totals' # accumulate([1,2,3,4,5]) --&gt; 1 3 6 10 15 # accumulate([1,2,3,4,5], operator.mul) --&gt; 1 2 6 24 120 it = iter(iterable) try: total = next(it) except StopIteration: return yield total for element in it: total = func(total, element) yield total The usage is exactly the same as above. If you are using numpy, then there exists a faster solution, at least for all numpy.ufuncs. These include basically the same functions that the standard library module math provides, and then some. You can find a complete list here. Every numpy.ufunc has the accumulate method, so you can just do: import numpy as np np.multiply.accumulate([5, 4, 3, 2]) # array([ 5, 20, 60, 120])
score: 6
upvote count: 6

http://stackoverflow.com/q/48933553
tagged with: qtablewidget
score: 3
tagged with: qtablewidgetitem
upvote count: 3
answer count: 2
tagged with: pyqt
downvote count: 0
favorite count: 0
has title: PyQt QTableWidget setItem loop
has body: I've been able to use QTableWidget and QTableWidgetItem to populate info from our database into a QTableWidget based on the text returned in the search bar. While I'm able to get the searched item to populate all the info into a tablewidget, I am not able to continuely add products from the search bar into the tablewidget. Instead the result is just being overrode and replaced. Here's an example of my code. # Defines Search Bar Button def search_Bar(self): searchFor = self.searchBar.text() #print(searchFor) searchQ = c.execute(" SELECT * FROM databasetable WHERE title LIKE ('%' || ? || '%') ", (searchFor,)) self.tableWidget.setRowCount(0) for row_number, row_data in enumerate(searchQ): self.tableWidget.insertRow(row_number) for column_number, data in enumerate(row_data): self.tableWidget.setItem(row_number, column_number, QTableWidgetItem(str(data))) The above code will yield me the desired results however when I try to add multiple items to the QTableWidget it overwrites the previously selected item. Is it possible to setItem without having it override the previous selection? I'd like to be able to create a table of the desired search results. We'd like the option to clear the table as well if needed.
has answer: http://stackoverflow.com/a/48933916
type: UnansweredQuestion
tagged with: python
tagged with: qt
has answer: http://stackoverflow.com/a/62437742
type: Question

http://stackoverflow.com/a/48874604
type: Answer
accepted answer of: http://stackoverflow.com/q/48874411
answers question: http://stackoverflow.com/q/48874411
upvote count: 3
score: 3
has body: In your case (with only two pairs) - you can probably just groupby and transform based on the ID, and just reverse the order of the values in the group, eg: df.loc[:, 'partner_data'] = df.groupby('pair_ID').orig_data.transform(lambda L: L[::-1]) Which gives you: ind_ID pair_ID orig_data partner_ID 0 A 1 W X 1 B 1 X W 2 C 2 Y Z 3 D 2 Z Y 4 A 3 W X 5 C 3 X W 6 B 4 Y Z 7 D 4 Z Y
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84754502
has comment: http://stackoverflow.com/comment/84753431

http://stackoverflow.com/comment/84767737
type: Comment
type: QuestionComment
has text: @StanleyKirdey when I tried passing `arr` as an array and not integer it gave me TypeError: can only concate list (not "int") to list
comment on: http://stackoverflow.com/q/48881613
score: 0

http://stackoverflow.com/comment/84675676
has text: If you weren't writing your `MyList` class, and you just had a list you wanted to mutate to produce your desired end state, what code would you write to do that? Write that code in `slice_it`.
comment on: http://stackoverflow.com/q/48835428
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48845146
upvote count: 2
answers question: http://stackoverflow.com/q/48844919
has body: I think this is the method You are using in Python https://github.com/achillean/shodan-python/blob/master/shodan/client.py#L324 and it triggers: return self._request('/shodan/host/search', args) Shodan API documentation: https://developer.shodan.io/api check out /shodan/host/search API I just saw that the answer is in Your question but You ate one letter from location (ocation). Try this: print '%s' % result['location']['country_code'] So field You are looking for is there but it is in another dictionary. I would recommend to read API documentation well next time and as Nofal Daud said, Python error are self explanatory if You have KeyError on dict it means that field is not there. Next time listen to Python it will reveal the truth.
score: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84694568
type: Answer

http://stackoverflow.com/comment/84721162
comment on: http://stackoverflow.com/q/48858878
has text: Does your file actually say `return {"acc":round(acc,3)}`, or does it say `return float({"acc":round(acc,3)})`? The stack trace suggests the latter. Make sure you’re saving changes to the right file.
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84917281
type: QuestionComment
comment on: http://stackoverflow.com/q/48955218
type: Comment
score: 1
has text: It depends on what kind of input you are expecting. If the only apostrophes in the input are from contractions then you can replace `" ?' ?"` with `"'"`. However if the input involves apostrophes used as qoutes then it would be a much harder task to decide when an apostrophe should have spaces next to it or shouldn't.

http://stackoverflow.com/comment/84743284
type: QuestionComment
has text: Your initial guess for `fsolve` is an array of zeros. The constant function `u(x) = 0` is a solution to your equation.
comment on: http://stackoverflow.com/q/48857635
score: 0
type: Comment

core-bluetooth
tag name: core-bluetooth
type: Tag
tags question: http://stackoverflow.com/q/48958267

http://stackoverflow.com/comment/84757419
comment on: http://stackoverflow.com/a/48876624
type: AnswerComment
score: 0
has text: nvm that question, but i still seem to be getting the error
type: Comment

http://stackoverflow.com/comment/84612349
has text: I just posted another way of doing it
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48804756

http://stackoverflow.com/comment/84776991
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48836817
type: Comment
has text: Thanks Oisin, I actually went back to the documentation after you told me to do so and I was pretty helpful :)

http://stackoverflow.com/comment/85143636
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48807492
has text: This doesn't relate to my question in terms of how to deal with DRF serializers.
type: Comment

http://stackoverflow.com/a/48939217
has body: In machine learning it is a custom to keep the preprocessing pipeline in memory so that, after picking its hyperparameters and training the model, you can apply the same preprocessing on the test data. If all of that is run in the same python instance, as is common for small/middle size projects, then it means keeping your LabelEncoder online or not sending it to garbage collection. In case of running training and testing in different instances, I think the easiest solution is to store it on disk, and load it in the testing script. I advise you to use pickle. Here is an example.
downvote count: 0
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48938905
score: 1

http://stackoverflow.com/a/48913857
has comment: http://stackoverflow.com/comment/84842723
has comment: http://stackoverflow.com/comment/84856671
downvote count: 2
type: Answer
score: 1
upvote count: 3
answers question: http://stackoverflow.com/q/48913352
has body: Checkout Spacy library (see links). It doesn't have that functionality out of the box, as you need to build the rules, but the rules are very human readable, and there are many options you can feed in (POS tags, regex, lemma, or any combination of those, etc.) Of particular note are the sections on the PhraseMarker() class. Directly copied from the documentation is a code sample: import spacy from spacy.matcher import PhraseMatcher nlp = spacy.load('en') matcher = PhraseMatcher(nlp.vocab) terminology_list = ['Barack Obama', 'Angela Merkel', 'Washington, D.C.'] patterns = [nlp(text) for text in terminology_list] matcher.add('TerminologyList', None, *patterns) doc = nlp(u"German Chancellor Angela Merkel and US President Barack Obama " u"converse in the Oval Office inside the White House in Washington, D.C.") matches = matcher(doc)
has comment: http://stackoverflow.com/comment/84842758
has comment: http://stackoverflow.com/comment/84858806
has comment: http://stackoverflow.com/comment/84859785

http://stackoverflow.com/comment/84626973
type: Comment
type: QuestionComment
score: 0
has text: @hop I don't know too much Python. I was trying to emulate some kind of "variable declaration".
comment on: http://stackoverflow.com/q/48811568

function
tags question: http://stackoverflow.com/q/48936730
tags question: http://stackoverflow.com/q/48860068
tags question: http://stackoverflow.com/q/48957350
tags question: http://stackoverflow.com/q/48890043
tag name: function
tags question: http://stackoverflow.com/q/48958695
tags question: http://stackoverflow.com/q/48957645
tags question: http://stackoverflow.com/q/48896973
tags question: http://stackoverflow.com/q/48875678
tags question: http://stackoverflow.com/q/48939808
tags question: http://stackoverflow.com/q/48943468
tags question: http://stackoverflow.com/q/48958633
tags question: http://stackoverflow.com/q/48950073
tags question: http://stackoverflow.com/q/48898481
tags question: http://stackoverflow.com/q/48938522
tags question: http://stackoverflow.com/q/48831512
tags question: http://stackoverflow.com/q/48941928
tags question: http://stackoverflow.com/q/48930234
tags question: http://stackoverflow.com/q/48844846
tags question: http://stackoverflow.com/q/48836596
tags question: http://stackoverflow.com/q/48947026
tags question: http://stackoverflow.com/q/48817792
tags question: http://stackoverflow.com/q/48815486
tags question: http://stackoverflow.com/q/48913319
tags question: http://stackoverflow.com/q/48939473
tags question: http://stackoverflow.com/q/48905952
type: Tag
tags question: http://stackoverflow.com/q/48832690
tags question: http://stackoverflow.com/q/48873097
tags question: http://stackoverflow.com/q/48837146
tags question: http://stackoverflow.com/q/48864407
tags question: http://stackoverflow.com/q/48893689
tags question: http://stackoverflow.com/q/48932816
tags question: http://stackoverflow.com/q/48843147
tags question: http://stackoverflow.com/q/48956814
tags question: http://stackoverflow.com/q/48886320
tags question: http://stackoverflow.com/q/48849334
tags question: http://stackoverflow.com/q/48873686
tags question: http://stackoverflow.com/q/48822537
tags question: http://stackoverflow.com/q/48954479
tags question: http://stackoverflow.com/q/48918606
tags question: http://stackoverflow.com/q/48903934
tags question: http://stackoverflow.com/q/48929610
tags question: http://stackoverflow.com/q/48937219
tags question: http://stackoverflow.com/q/48844049
tags question: http://stackoverflow.com/q/48932007
tags question: http://stackoverflow.com/q/48892959

http://stackoverflow.com/comment/84910616
type: QuestionComment
has text: `a = math.tan(x)`. Now replace `math.tan(x)` by `a` in your formula: `return a / (1 - a*a)`
comment on: http://stackoverflow.com/q/48951973
score: 2
type: Comment

http://stackoverflow.com/comment/84902299
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48946713
has text: I made a work around by copying the basemap.interp function from the source code and making it into a standalone function. Thanks!
type: Comment

http://stackoverflow.com/comment/84720757
type: QuestionComment
has text: provide more lines of the error. which file is the error for, and which file is the contSearch function in?
comment on: http://stackoverflow.com/q/48858021
score: 0
type: Comment

http://stackoverflow.com/comment/85136511
has text: Let me extend my question, As Suggested, I declared the dictionary with provider_modules = {'bsnl':'bsnl_sms', 'airtel':'airtel_sms'}. But, in future if i want to add one more provider, then without touching the code, who can i do that?
comment on: http://stackoverflow.com/q/48928293
score: 0
type: Comment
type: QuestionComment

predict
tags question: http://stackoverflow.com/q/48883170
type: Tag
tag name: predict

http://stackoverflow.com/a/49069422
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
has body: There is indeed a limit to the queue size : in multiprocessing this limit in not reliable, and once reached, the queue.put is blocked until queue has been emptied. See the documentation for more informations : https://docs.python.org/2/library/multiprocessing.html#multiprocessing.Queue In you case, this is not the issue. You just have defined a bad condition to stop fetching results : while not output_queue.empty(): results += [output_queue.get()] In your case, if the writer is slower than the reader (and they will, from time to times), your queue might be empty for a brief moment, even if the writer has not finished sending everything. This is why you have an unstable number of reading. To confirm, I replace this condition by this : t0 = time.time() while time.time()-t0&lt;30: # seems to be enough to complete your loops, but it's just a demo condition, you should not use this try: results += [output_queue.get(timeout=1)] except Exception as expt: # the output_queue.get(timeout=1) will wait up to 1 second if the queue is momentarily empty. If the queue is empty for more than 1 sec, it raises an exception and it means the loop is complete. Again, this is not a good condition in real life, and this is just for testing. break
accepted answer of: http://stackoverflow.com/q/48841645
answers question: http://stackoverflow.com/q/48841645
upvote count: 1

http://stackoverflow.com/q/48841435
linked to: http://stackoverflow.com/q/48369043
upvote count: 0
has body: I am scraping some data from a website. I am writing a script that will automate it. In order to go to the next page I have to remove this disabled attribute from the button. I have tried many things, but nothing has helped me till now. Next Code: binary = FirefoxBinary('/usr/lib/firefox/firefox') driver = webdriver.Firefox(firefox_binary=binary) driver.get("https://example.com/example/example") my_url = Request('https://www.example.com/example/example', headers={'User-Agent': 'Mozilla/5.0'}) uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") user = raw_input("enter your starting point : ") user_box = driver.find_element_by_class_name("search") user_box.send_keys(user) #user_box.autocomplete = "on" #user_box.submit() login_button = driver.find_element_by_css_selector("button.proceed") #login_button.submit() #print (login_button.text)
has comment: http://stackoverflow.com/comment/84687005
answer count: 1
has answer: http://stackoverflow.com/a/48841545
favorite count: 0
type: UnansweredQuestion
tagged with: python
has title: Web scraping using python. Collecting data from a website
tagged with: selenium
tagged with: web-scraping
downvote count: 1
type: Question
score: -1

http://stackoverflow.com/q/48821402
downvote count: 0
has answer: http://stackoverflow.com/a/48821624
has comment: http://stackoverflow.com/comment/84646223
has answer: http://stackoverflow.com/a/48821633
accepted answer: http://stackoverflow.com/a/48821633
tagged with: python
has answer: http://stackoverflow.com/a/48821476
possible better answer: http://stackoverflow.com/a/48821624
type: AnsweredQuestion
score: 1
type: Question
upvote count: 1
favorite count: 0
has body: I'm new to python. We have to accept two lines of inputs according to one problem. The first line will tell how many numbers will be entered in the next line. Then the next line will have that many numbers and we need to perform some operations on those numbers. So, I know that accepting multiple inputs from a single line is fairly easy when you know how many numbers you are going to get. For example, if you know the user will enter 3 numbers, one can do this: a,b,c=map(int,input().split()) But what should one do when the number of inputs to be accepted is not known? Please excuse me if this question is a duplicate, but I couldn't find any solution for the same. Any help is appreciated. Many thanks.
answer count: 3
has title: What is the way to get variable number of inputs from user in one line in python?

scrapy
tags question: http://stackoverflow.com/q/48827311
tags question: http://stackoverflow.com/q/48846606
tags question: http://stackoverflow.com/q/48847375
tags question: http://stackoverflow.com/q/48806013
tags question: http://stackoverflow.com/q/48840526
tags question: http://stackoverflow.com/q/48891574
tags question: http://stackoverflow.com/q/48882651
tags question: http://stackoverflow.com/q/48874727
tags question: http://stackoverflow.com/q/48961297
tags question: http://stackoverflow.com/q/48827688
tags question: http://stackoverflow.com/q/48875911
tags question: http://stackoverflow.com/q/48812665
tags question: http://stackoverflow.com/q/48834251
tags question: http://stackoverflow.com/q/48856187
tags question: http://stackoverflow.com/q/48859820
tags question: http://stackoverflow.com/q/48923682
tags question: http://stackoverflow.com/q/48843260
tags question: http://stackoverflow.com/q/48906294
tags question: http://stackoverflow.com/q/48843728
tags question: http://stackoverflow.com/q/48946320
tags question: http://stackoverflow.com/q/48913525
tags question: http://stackoverflow.com/q/48916745
tags question: http://stackoverflow.com/q/48840623
tags question: http://stackoverflow.com/q/48951692
tags question: http://stackoverflow.com/q/48929331
tag name: scrapy
tags question: http://stackoverflow.com/q/48834080
tags question: http://stackoverflow.com/q/48858167
tags question: http://stackoverflow.com/q/48874341
tags question: http://stackoverflow.com/q/48961627
tags question: http://stackoverflow.com/q/48811766
tags question: http://stackoverflow.com/q/48805210
tags question: http://stackoverflow.com/q/48852029
tags question: http://stackoverflow.com/q/48945567
tags question: http://stackoverflow.com/q/48919935
type: Tag
tags question: http://stackoverflow.com/q/48910982
tags question: http://stackoverflow.com/q/48819761
tags question: http://stackoverflow.com/q/48941220
tags question: http://stackoverflow.com/q/48930987
tags question: http://stackoverflow.com/q/48917312
tags question: http://stackoverflow.com/q/48849183
tags question: http://stackoverflow.com/q/48927727

http://stackoverflow.com/a/48935447
score: 4
upvote count: 4
downvote count: 0
has body: You can do: # Save the range object for efficiency In [30]: nums = range(1, 101) # Dict comprehension to with zip to produce the desired dict In [31]: {f: r for f, r in zip(nums, nums[::-1])} Out[31]: {1: 100, 2: 99, ... 100: 1} # Or use the dict constructor directly on the iterator returned by zip In [32]: dict(zip(nums, nums[::-1])) Out[32]: {1: 100, 2: 99, ... 100: 1}
type: Answer
answers question: http://stackoverflow.com/q/48935409

http://stackoverflow.com/a/48930180
type: Answer
score: 1
upvote count: 1
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48893732
type: AcceptedAnswer
has body: Found an answer to my own question. The problem was that when I run an installation script I used sudo. After reinstalling Anaconda without superuser permissions everything was working as per SO answers referenced in the question: conda install nb_conda in root environment conda install ipykernel in any environment just once, other environments will be listed without separate installation
answers question: http://stackoverflow.com/q/48893732
has comment: http://stackoverflow.com/comment/90466481

http://stackoverflow.com/comment/84686247
type: AnswerComment
score: 0
type: Comment
has text: That is surely not an issue, Otherwise it would not work with python 2.7.12. There is something shaky happening with Anaconda and Tensforflow. Because import tensorflow as tf and from tensorflow... import ... are surely different statements
comment on: http://stackoverflow.com/a/48841012

http://stackoverflow.com/comment/84832777
has text: @RobG If password is incorrect it returns true and than it says that user is incorrect.
score: 0
comment on: http://stackoverflow.com/q/48912849
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84915196
type: Comment
has text: @Rookie_123 No worry about it , it is hard for me find the different as well.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48954119

http://stackoverflow.com/q/48948616
has answer: http://stackoverflow.com/a/48948737
favorite count: 0
upvote count: 3
accepted answer: http://stackoverflow.com/a/48948737
type: AnsweredQuestion
score: 3
has title: How to assign panda group data to a multi-index Dataframe?
type: Question
answer count: 1
downvote count: 0
has body: Aim I have an initial data frame that looks like this: Serial No. Data One Data Two 0 01 0.258625 0.667996 1 01 0.192356 0.723055 2 01 0.738066 0.266488 3 01 0.374525 0.059664 4 01 0.193977 0.104213 5 01 0.213749 0.366608 ⁞ 49 05 0.948550 0.823888 I want to rearrange it into a multi-index data frame with columns of data type and serial number: Data Data One Data Two Serial No. 01 02 03 04 05 01 02 03 04 05 Code To generate and fill the multi-index Data Frame I've written a small block of code: serial_numbers = ["01", "02", "03", "04", "05"] headings = ["Serial No.", "Data One", "Data Two"] arrays = [[], []] for ii, heading in enumerate(headings[1:]): arrays[0] += [heading]*len(serial_numbers) arrays[1] += serial_numbers index = pd.MultiIndex.from_tuples(list(zip(*arrays)), names=["Data", "Serial No."]) group = random_data.groupby(headings[0]) data = pd.DataFrame(np.zeros((len(group.get_group(serial_numbers[0])), len(index))), columns=index) for heading in headings[1:]: for serial_number in serial_numbers: data.loc[:, (heading, serial_number)] = group.get_group(serial_number).loc[:, heading] Problem The above code creates a Data Frame where the first serial number of each data type is filled with values and the rest are NaNs: Data Data One Data Two Serial No. 01 02 03 04 05 01 02 03 04 05 0 0.258625 NaN NaN NaN NaN 0.667996 NaN NaN NaN NaN 1 0.192356 NaN NaN NaN NaN 0.723055 NaN NaN NaN NaN 2 0.738066 NaN NaN NaN NaN 0.266488 NaN NaN NaN NaN 3 0.374525 NaN NaN NaN NaN 0.059664 NaN NaN NaN NaN 4 0.193977 NaN NaN NaN NaN 0.104213 NaN NaN NaN NaN 5 0.213749 NaN NaN NaN NaN 0.366608 NaN NaN NaN NaN 6 0.829126 NaN NaN NaN NaN 0.972882 NaN NaN NaN NaN 7 0.494763 NaN NaN NaN NaN 0.482118 NaN NaN NaN NaN 8 0.024283 NaN NaN NaN NaN 0.538428 NaN NaN NaN NaN 9 0.700613 NaN NaN NaN NaN 0.067831 NaN NaN NaN NaN Why does this work for the first serial number of each data type but not others? Appendix In the real world the input data comes from a CSV and pandas.read_csv but for the…
tagged with: pandas-groupby
tagged with: pandas
tagged with: python

http://stackoverflow.com/comment/84617615
type: Comment
comment on: http://stackoverflow.com/q/48806759
score: 0
has text: i guess there is no fix
type: QuestionComment

http://stackoverflow.com/comment/84885431
comment on: http://stackoverflow.com/q/48938991
score: 0
type: Comment
type: QuestionComment
has text: Please provide a [mcve]. Don't post your whole code, create a new minimal program that exhibits the same behavior.

http://stackoverflow.com/q/48806085
has comment: http://stackoverflow.com/comment/84615606
favorite count: 0
tagged with: cassandra
tagged with: python-2.7
accepted answer: http://stackoverflow.com/a/48806579
tagged with: python
downvote count: 0
has answer: http://stackoverflow.com/a/48806579
has title: Persisting a zip file in cassandra and reading it back
has body: I need to persist a zip file in cassandra data base. And I need to get it back in another program. For persisting it, I am using the following code- bin_data = open("Model-File.zip", 'rb').read() bin_data=bin_data.decode('latin-1').encode("utf-8") This bin_data I can persist to cassandra in string format- CQLString = "INSERT INTO testkeyspacenew.model (modelid, data) VALUES(%s,%s)" session.execute(CQLString, (model_id,bin_data)) However when reading it back, I am unable to get the bin_data in the format in which it was in the beginning. Hence unable to recreate the zip file. Please help. This is what I tried during reading- abc=session.execute(CQLString) for row in abc: data=row data=str(data) print (data.encode("utf-8").encode('latin-1')) The data I am printing while reading is not same as the bin_data I got from the zip file.
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84615219
score: 1
type: Question
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/84863403
comment on: http://stackoverflow.com/q/48928276
type: QuestionComment
type: Comment
score: 2
has text: You have to define your classes *before* you actually use them - which appears to be the line `kv = Builder.load_string(...`.

http://stackoverflow.com/q/48887475
has body: Hi I am a relatively new developer (about 1 year of java and just started working with python a few weeks ago) and am having trouble getting radio buttons to work on a toplevel window in python. I have searched through different questions and answers on here and tried several of them but none seemed to work. Here is the code that's relevant: class MPTest(TestBed.Frame): def __init__(self, master=NONE): TestBed.Frame.__init__(self, master) self.createWidgets() def createWidgets(self): ucThree = Button(root, text='Bids', font='Jokerman', fg='white', bg='royal blue', command=self.BidWindow) ucThree.grid(row=2) def BidWindow(self): t = TestBed.Toplevel(self) t.wm_title("Bid Info") t.configure(background="navy") v = IntVar() v2 = IntVar() bidtypelabel = Label(t, text='Bid Type: ', fg='white', bg='navy') bidtypelabel.grid(row=0) realtime = Radiobutton(t, text='Real Time', variable=v, value=1, fg='white', bg='navy') realtime.grid(row=1) priority = Radiobutton(t, text='Priority', variable=v, value=2, fg='white', bg='navy') priority.grid(row=2) listsearch = Radiobutton(t, text='List Search', variable=v, value=3, fg='white', bg='navy') listsearch.grid(row=3) bidactionlabel = Label(t, text='Action: ', fg='white', bg='navy') bidactionlabel.grid(row=0, column=1) acceptbid = Radiobutton(t, text='Accept Bid', variable=v2, value=1, fg='white', bg='navy') acceptbid.grid(row=1, column=1) rejectbid = Radiobutton(t, text='Reject Bid', variable=v2, value=2, fg='white', bg='navy') rejectbid.grid(row=2, column=1) submit = Button(t, text='Submit', fg='white', bg='royal blue') submit.grid(row=4, column=2) root = TestBed.Tk() root.configure(background="navy") root.rowconfigure((0, 1, 2, 3, 4, 5, 6, 7, 8, 9), weight=1, pad=50) root.columnconfigure(1, weight=1, pad=200) app = MPTest(master=root) app.mainloop() I have tried setting the variables equal to both 0 and 1, both inside the IntVar() and then also tried setting it after with a set on the next line. However, neither of these allow the R…
accepted answer: http://stackoverflow.com/a/48889015
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84780973
has comment: http://stackoverflow.com/comment/84781617
tagged with: tkinter
has comment: http://stackoverflow.com/comment/84780514
downvote count: 1
has comment: http://stackoverflow.com/comment/84780171
type: Question
has comment: http://stackoverflow.com/comment/84780285
has comment: http://stackoverflow.com/comment/84783306
has comment: http://stackoverflow.com/comment/84781295
upvote count: 0
score: -1
linked to: http://stackoverflow.com/q/29133741
has title: Tkinter Python RadioButton not selecting
has answer: http://stackoverflow.com/a/48889015
tagged with: toplevel
tagged with: radio-button
answer count: 1
duplicate of: http://stackoverflow.com/q/29133741
has comment: http://stackoverflow.com/comment/84780319
has comment: http://stackoverflow.com/comment/84780607
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84781577
tagged with: python

towers-of-hanoi
tag name: towers-of-hanoi
tags question: http://stackoverflow.com/q/48913319
type: Tag

http://stackoverflow.com/comment/84916892
score: 0
comment on: http://stackoverflow.com/a/48954904
type: Comment
has text: ah i see now, you just need to pass the df row to the read_corpus instead of just documents
type: AnswerComment

eclipse
tag name: eclipse
tags question: http://stackoverflow.com/q/48846671
type: Tag

http://stackoverflow.com/a/48843374
type: Answer
answers question: http://stackoverflow.com/q/48843149
has body: I'm so stupid v1list[i-1].set(UserName) v2list[i-1].set(UserAge) Would work for this.
score: 0

http://stackoverflow.com/q/48860388
tagged with: tensorflow
has answer: http://stackoverflow.com/a/48863496
upvote count: 4
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84725786
downvote count: 0
has title: keras: ValueError: Error when checking model target: expected activation_1 to have shape (None, 60) but got array with shape (10, 100)
tagged with: keras
favorite count: 0
accepted answer: http://stackoverflow.com/a/48863496
type: Question
tagged with: convolution
tagged with: python
has body: I'm trying to transplant RocAlphaGo to play Game of Amazons, and there are problems when trying to implement supervised policy trainer. from keras.models import Sequential, Model from keras.layers.core import Activation, Flatten from keras.layers import convolutional defaults = { "board": 10, "filters_per_layer": 128, "layers": 12, "filter_width_1": 5 } # copy defaults, but override with anything in kwargs params = defaults network = Sequential() # create first layer network.add(convolutional.Convolution2D( input_shape=(6, 10, 10), nb_filter=128, nb_row=5, nb_col=5, init='uniform', activation='relu', border_mode='same')) # create all other layers for i in range(2, 13): # use filter_width_K if it is there, otherwise use 3 filter_key = "filter_width_%d" % i filter_width = params.get(filter_key, 3) # use filters_per_layer_K if it is there, otherwise use default value filter_count_key = "filters_per_layer_%d" % i filter_nb = params.get(filter_count_key, 128) network.add(convolutional.Convolution2D( nb_filter=filter_nb, nb_row=filter_width, nb_col=filter_width, init='uniform', activation='relu', border_mode='same')) # the last layer maps each &lt;filters_per_layer&gt; feature to a number network.add(convolutional.Convolution2D( nb_filter=1, nb_row=1, nb_col=1, init='uniform', border_mode='same')) # reshape output to be board x board network.add(Flatten()) # softmax makes it into a probability distribution network.add(Activation('softmax')) keras 1.2.0 python 2.7 Gives the following exception: ValueError: Error when checking model target: expected activation_1 to have shape (None, 60) but got array with shape (10, 100) The training data set is a (10, 6, 10, 10) array, 10 x 6 layers , each layer is a 10x10 array(chess board), why model need (None, 60) ? if chagne input_shape=(6, 10, 10) to input_shape=(10, 10, 10), will get: ValueError: Error when checking model input: expected convolution2d_input_1 to have shape (None, 10, 10, 10) but got array with shape (10, 6, 10, 10) …
score: 4
answer count: 1

http://stackoverflow.com/a/48952659
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48952526
upvote count: 2
has comment: http://stackoverflow.com/comment/84912131
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48952526
has comment: http://stackoverflow.com/comment/84912450
has body: There are 4 components you are trying to install: Cuda Cudnn tensorflow keras they are not always synchronized, as of today tensorflow supports cuda 9.1 if you compile it yourself (like the guide you posted), the prebuilt binaries were compiled with cuda 9.0 and cudnn 7. I prefer using them so this is this is the cuda version I'm using. this is how you can install it: first, remove existing cuda installations: sudo apt-get remove --purge nvidia-* install ubuntu headers and cuda 9.0: sudo apt-get install linux-headers-$(uname -r) CUDA_REPO_PKG=cuda-repo-ubuntu1604_9.1.85-1_amd64.deb wget -O /tmp/${CUDA_REPO_PKG} http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/${CUDA_REPO_PKG} sudo dpkg -i /tmp/${CUDA_REPO_PKG} sudo apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/7fa2af80.pub rm -f /tmp/${CUDA_REPO_PKG} sudo apt-get update sudo apt-get install -y cuda-9-0 download cuDNN v7.0.5 Library for Linux from nvidia site, navigate to downloaded folder and install it: tar -xzvf cudnn-9.0-linux-x64-v7.tgz sudo cp cuda/include/* /usr/local/cuda/include/ sudo cp cuda/lib64/* /usr/local/cuda/lib64/ reboot your machine and check nvidia driver works using: nvidia-smi the output should look like this: +-----------------------------------------------------------------------------+ | NVIDIA-SMI 390.30 Driver Version: 390.30 | |-------------------------------+----------------------+----------------------+ | GPU Name Persistence-M| Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap| Memory-Usage | GPU-Util Compute M. | |===============================+======================+======================| | 0 GeForce GTX 105... Off | 00000000:04:00.0 On | N/A | | 0% 33C P8 N/A / 120W | 310MiB / 4038MiB | 0% Default | +-------------------------------+----------------------+----------------------+ +-----------------------------------------------------------------------------+ | Processes: GPU Memory | | GP…
type: Answer
has comment: http://stackoverflow.com/comment/84913370

http://stackoverflow.com/comment/84745268
has text: I've edited the answer above with more information. This works just like pandas groupby-apply.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48870412

http://stackoverflow.com/comment/84928357
has text: try this: import warnings; warnings.filterwarnings('ignore')
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48960544

http://stackoverflow.com/comment/84803796
score: 2
has text: Would this also show the numbers in the timestamp? Also where is number defined?
comment on: http://stackoverflow.com/a/48899231
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48843069
has answer: http://stackoverflow.com/a/48843378
has answer: http://stackoverflow.com/a/48843314
tagged with: numpy
tagged with: random
score: 2
type: AnsweredQuestion
downvote count: 0
accepted answer: http://stackoverflow.com/a/48843378
answer count: 3
type: Question
has body: I want to resample a sequence as follows: fastadict = {"seq1" : "ATGCAGTCACGT", "seq2" : "ATGTGTGTACG"} I wrote the following function: import sys import random def resampling_f(fastadict, seq, num): fastadict[seq] = fastadict[seq].replace("N","").replace("n","") l = [] new_seq = ''.join([random.choice(fastadict[seq]) for i in range(num)]) l.append(new_seq) return l # Run function for 20 replicates: for i in range(20): print resampling_f(fastadict, "seq1", 10) This works fine for a small sequence as in the example. In my work, I need to sample about 1 million letters (base of DNA, ACTG) for 10000 times. This function is too slow for this purpose. Is there a faster way of obtaining sampling with replacement with python?
tagged with: python
possible better answer: http://stackoverflow.com/a/48843675
favorite count: 0
has answer: http://stackoverflow.com/a/48843675
upvote count: 2
has title: Efficient resampling with Python

http://stackoverflow.com/q/48942393
favorite count: 0
tagged with: falcon
tagged with: rest
accepted answer: http://stackoverflow.com/a/48942911
tagged with: python
type: AnsweredQuestion
score: 2
has comment: http://stackoverflow.com/comment/84891466
upvote count: 2
type: Question
linked to: http://stackoverflow.com/q/32042323
has answer: http://stackoverflow.com/a/48942911
possible better answer: http://stackoverflow.com/a/48942704
tagged with: flask-restful
has comment: http://stackoverflow.com/comment/84891803
has body: I am creating a REST API. Basic idea is to send data to a server and the server gives me some other corresponding data in return. I want to implement this with SSL. I need to have an encrypted connection between client and server. Which is the best REST framework in python to achieve this?
has answer: http://stackoverflow.com/a/48942704
answer count: 2
downvote count: 0
has title: REST API in Python over SSL
has comment: http://stackoverflow.com/comment/84891625
tagged with: django-rest-framework

http://stackoverflow.com/comment/85274239
score: 0
type: Comment
has text: Firstly I wasn't really approaching this from the perspective that I would simply do this for you. Secondly you haven't really answered my question: which is correct? You say that the your code so far is correct but I am certain that it is not - I can't help further if we don't agree on that.
comment on: http://stackoverflow.com/a/49132293
type: AnswerComment

http://stackoverflow.com/comment/84747481
type: Comment
has text: @GergesDib if the OP were in fact using nested list objects, then there may be subtle ways this will not work as intended. Consider `(numpy.zeros_like([[1,2], [1]]))`
comment on: http://stackoverflow.com/q/48871785
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84724091
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48860428
score: 0
has text: Yeah I didn't say that well. What I read was there is an issue with seaborn not being able to plot pandas date objects.

http://stackoverflow.com/comment/84628579
score: 1
type: Comment
type: QuestionComment
has text: I've added `python` and `pandas` as tags here since this feels very much like the solution is in the `read_csv()` function of `pandas`. Specifically the `dtype` and `converters` parameters listed in the pandas `read_csv` [documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html).
comment on: http://stackoverflow.com/q/48811978

tcp
type: Tag
tags question: http://stackoverflow.com/q/48835714
tags question: http://stackoverflow.com/q/48856268
tags question: http://stackoverflow.com/q/48899303
tags question: http://stackoverflow.com/q/48844563
tags question: http://stackoverflow.com/q/48907608
tag name: tcp

http://stackoverflow.com/a/48942043
has body: To Parse Dates from dateutil.parser import parse date_array = np.array(['September 11, 2012', 'September 5, 2012']) [parse(x).date() for x in date_array] Output: [datetime.date(2012, 9, 11), datetime.date(2012, 9, 5)]
type: Answer
has comment: http://stackoverflow.com/comment/84927068
answers question: http://stackoverflow.com/q/48941807
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48941807

http://stackoverflow.com/comment/84744718
type: Comment
type: QuestionComment
has text: Its just a list of different colours.
score: 0
comment on: http://stackoverflow.com/q/48870161

c++
tags question: http://stackoverflow.com/q/48807959
tags question: http://stackoverflow.com/q/48829034
tags question: http://stackoverflow.com/q/48909544
tags question: http://stackoverflow.com/q/48838478
tags question: http://stackoverflow.com/q/48871099
tags question: http://stackoverflow.com/q/48918712
tags question: http://stackoverflow.com/q/48860835
tags question: http://stackoverflow.com/q/48867997
type: Tag
tags question: http://stackoverflow.com/q/48849047
tags question: http://stackoverflow.com/q/48835403
tags question: http://stackoverflow.com/q/48820375
tags question: http://stackoverflow.com/q/48813291
tags question: http://stackoverflow.com/q/48931077
tags question: http://stackoverflow.com/q/48926774
tags question: http://stackoverflow.com/q/48866543
tags question: http://stackoverflow.com/q/48839930
tags question: http://stackoverflow.com/q/48921541
tags question: http://stackoverflow.com/q/48899657
tags question: http://stackoverflow.com/q/48923810
tags question: http://stackoverflow.com/q/48853323
tags question: http://stackoverflow.com/q/48809816
tags question: http://stackoverflow.com/q/48831212
tags question: http://stackoverflow.com/q/48941451
tag name: c++
tags question: http://stackoverflow.com/q/48918530

http://stackoverflow.com/a/49225848
has comment: http://stackoverflow.com/comment/85469696
score: 3
accepted answer of: http://stackoverflow.com/q/48906486
type: AcceptedAnswer
downvote count: 0
has body: Use of the stop_filter command as specified here worked for me. I've duplicated HenningCash's code below for convenience: import time, threading from scapy.all import sniff e = threading.Event() def _sniff(e): a = sniff(filter="tcp port 80", stop_filter=lambda p: e.is_set()) print("Stopped after %i packets" % len(a)) print("Start capturing thread") t = threading.Thread(target=_sniff, args=(e,)) t.start() time.sleep(3) print("Try to shutdown capturing...") e.set() # This will run until you send a HTTP request somewhere # There is no way to exit clean if no package is received while True: t.join(2) if t.is_alive(): print("Thread is still running...") else: break print("Shutdown complete!") However, you still have to wait for a final packet to be sniffed, which might not be ideal in your scenario.
type: Answer
answers question: http://stackoverflow.com/q/48906486
upvote count: 3

http://stackoverflow.com/comment/84872213
has text: Is `type()` what you're looking for...?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48932685

http://stackoverflow.com/a/48865948
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48865455
upvote count: 1
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48865455
type: Answer
has body: currently, your code calls runRefresh just once after the mainloop . modify runRefresh to : def runRefresh(): print("Checking") connectStatus.config(bg="yellow", fg="#fff", width=28, height=2, text="Pending", font="Bahnscrift 10") attemptConnect() master.after(1000, runRefresh) so that runRefresh calls itself recursively every 1 second

http://stackoverflow.com/comment/84742748
has text: Could you post the results you want to see?
type: Comment
comment on: http://stackoverflow.com/q/48869471
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84683744
type: QuestionComment
has text: You’re right – that doesn’t sound accurate. (It originates from a comment by unseen_rider.)
type: Comment
comment on: http://stackoverflow.com/q/48839772
score: 0

http://stackoverflow.com/comment/84681384
has text: It will work, but seems like a terrible way to do it.
type: AnswerComment
comment on: http://stackoverflow.com/a/48837443
type: Comment
score: 1

http://stackoverflow.com/q/48875783
has answer: http://stackoverflow.com/a/62152957
tagged with: python
tagged with: jupyter
upvote count: 12
downvote count: 0
type: UnansweredQuestion
has body: I am working on a image segmentation machine learning project and I would like to test it out on Google Colab. For the training dataset, I have 700 images, mostly 256x256, that I need to upload into a python numpy array for my project. I also have thousands of corresponding mask files to upload. They currently exist in a variety of subfolders on Google drive, but I have been unable to upload them to Google Colab for use in my project. So far I have attempted using Google Fuse which seems to have very slow upload speeds and PyDrive which has given me a variety of authentication errors. I have been using the Google Colab I/O example code for the most part. How should I go about this? Would PyDrive be the way to go? Is there code somewhere for uploading a folder structure or many files at a time?
tagged with: machine-learning
has answer: http://stackoverflow.com/a/49887016
type: Question
has answer: http://stackoverflow.com/a/48969833
has answer: http://stackoverflow.com/a/52346280
answer count: 6
has answer: http://stackoverflow.com/a/57836020
has answer: http://stackoverflow.com/a/62189886
has title: How to Upload Many Files to Google Colab?
score: 12
tagged with: google-colaboratory
favorite count: 0

http://stackoverflow.com/a/48891948
answers question: http://stackoverflow.com/q/48879205
type: Answer
score: 0
has body: Try {% for trend in trends %} {{ trend }} {% endfor %}, because it looks like the data you are sending is a list
has comment: http://stackoverflow.com/comment/84858443

mininet
tag name: mininet
tags question: http://stackoverflow.com/q/48811721
type: Tag

setuptools
tags question: http://stackoverflow.com/q/48911094
tag name: setuptools
tags question: http://stackoverflow.com/q/48961076
tags question: http://stackoverflow.com/q/48884796
tags question: http://stackoverflow.com/q/48885331
tags question: http://stackoverflow.com/q/48857309
tags question: http://stackoverflow.com/q/48884766
tags question: http://stackoverflow.com/q/48912241
tags question: http://stackoverflow.com/q/48829372
tags question: http://stackoverflow.com/q/48952408
type: Tag
tags question: http://stackoverflow.com/q/48876814

http://stackoverflow.com/a/48838637
upvote count: 1
has body: I don't think you can loop on response.content.read return value I guess you are looping on the chunk there no? Maybe something like that would work chunk = await response.content.read(self.__chunk_size) While chunk: await fd.write(chunk) chunk = await response.content.read(self.__chunk_size)
answers question: http://stackoverflow.com/q/48838532
downvote count: 0
type: Answer
score: 1

http://stackoverflow.com/comment/84803428
type: Comment
comment on: http://stackoverflow.com/q/48891538
type: QuestionComment
score: 1
has text: You should have only used LabelBinarizer.transform() on the new data. Never fit(). Show the code and we will modify it suit the needs.

http://stackoverflow.com/comment/84641515
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48818779
has text: Thanks, almost there, the label assignment is well done, but the plotdict[label] comes up with errors. y = plotdict[label] NameError: name 'plotdict' is not defined
type: Comment

http://stackoverflow.com/a/48835163
score: 0
has body: This should give you an idea about how to handle it: def rename(name,suffix): """renames a file with one . in it by splitting and inserting suffix before the .""" a,b = name.split('.') return ''.join([a,suffix,'.',b]) # recombine parts including suffix in it def processFn(name): """Open file 'name', process it, save it under other name""" # scramble data by sorting and writing anew to renamed file with open(name,"r") as r, open(rename(name,"_mang"),"w") as w: for line in r: scrambled = ''.join(sorted(line.strip("\n")))+"\n" w.write(scrambled) # list of filenames, see link below for how to get them with os.listdir() names = ['fn1.txt','fn2.txt','fn3.txt'] # create demo data for name in names: with open(name,"w") as w: for i in range(12): w.write("someword"+str(i)+"\n") # process files for name in names: processFn(name) For file listings: see How do I list all files of a directory? I choose to read/write line by line, you can read in one file fully, process it and output it again on block to your liking. fn1.txt: someword0 someword1 someword2 someword3 someword4 someword5 someword6 someword7 someword8 someword9 someword10 someword11 into fn1_mang.txt: 0demoorsw 1demoorsw 2demoorsw 3demoorsw 4demoorsw 5demoorsw 6demoorsw 7demoorsw 8demoorsw 9demoorsw 01demoorsw 11demoorsw
answers question: http://stackoverflow.com/q/48834972
type: Answer

http://stackoverflow.com/q/48825775
tagged with: flask
linked to: http://stackoverflow.com/q/46019674
has answer: http://stackoverflow.com/a/58738219
has title: Failed To Deploy Flask App On Heroku [fatal error: mpfr.h: No such file or directory]
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84659126
accepted answer: http://stackoverflow.com/a/58738219
type: Question
tagged with: heroku
has comment: http://stackoverflow.com/comment/84658259
score: 0
answer count: 1
has body: I already made simple web app using Flask and wanted to deploy it at Heroku, but found this error when deploying : Complete output from command /app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-yc_idc80/gmpy2/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-dh_wvxtt-record/install-record.txt --single-version-externally-managed --compile: running install running build running build_ext building 'gmpy2' extension creating build creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/src gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -DWITHMPFR -DWITHMPC -I/app/.heroku/python/include/python3.6m -c src/gmpy2.c -o build/temp.linux-x86_64-3.6/src/gmpy2.o In file included from src/gmpy2.c:426:0: src/gmpy.h:252:20: fatal error: mpfr.h: No such file or directory compilation terminated. error: command 'gcc' failed with exit status 1 ----------------------------------------

http://stackoverflow.com/comment/84656878
comment on: http://stackoverflow.com/a/48825860
type: AnswerComment
score: 0
type: Comment
has text: ok, unless you provide your code and full traceback, I can't help further.

http://stackoverflow.com/comment/84890470
has text: this is an infinite loop do you realize that?
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48941783

http://stackoverflow.com/comment/85173921
score: 0
type: AnswerComment
has text: I want to install packages for global use only. Hence I like `pip install -t <direct directory> <package>`. But will I be able to copy this folder to a new Linux system? I can transfer the packages folder to new Linux system in R language ( https://www.r-project.org/ ) which avoids downloading on every system.
type: Comment
comment on: http://stackoverflow.com/a/49004696

http://stackoverflow.com/q/48874035
type: Question
tagged with: numpy
linked to: http://stackoverflow.com/q/48871285
has comment: http://stackoverflow.com/comment/84752097
has answer: http://stackoverflow.com/a/48875880
accepted answer: http://stackoverflow.com/a/48875880
has body: For ease of explanation I will be using 2-dimensional numpy arrays (I am using 3-dimensional arrays in my problem). I have 2 arrays, one records the odds of something occuring at those specific coordinates. The other array is a pre-generated matrix that is used to lower the values of the first array around a central point in a pre-determined radius. I want to automatically select points in the first matrix (henceforth A), and prevent the program to select another point that sits too close to previously selected points. So I want to multiply the values around the selected point related to the distance from said point. E.G.: Matrix A: [[0, 0, 0, 0, 0, 0], [0, 1, 2, 2, 1, 0], [0, 2, 4, 4, 2, 0], [0, 2, 4, 4, 2, 0], [0, 1, 2, 2, 1, 0], [0, 0, 0, 0, 0, 0]] Matrix B: [[ 1, 0.5, 1 ], [0.5, 0, 0.5], [ 1, 0.5, 1 ]] Now say that index [2, 1] is selected as a point of interest. B is multiplied with A, but only with the values in a 3*3 around [2, 1] Result: [[0, 0, 0, 0, 0, 0], [0, 0.5, 0, 1, 1, 0], [0, 2, 2, 4, 2, 0], [0, 2, 4, 4, 2, 0], [0, 1, 2, 2, 1, 0], [0, 0, 0, 0, 0, 0]] This should result in the points around [2, 1] not being valuable enough to be selected as points of interest, unless the conditions are high enough to be selected anyway, hence the multiplication. Now, I can't seem to figure out a way to perform this specific multiplication. numpy.multiply() would repeat B so that it gets applied over the entire matrix A while I only want to apply it on a small part of A. Another option would be looping over the affected section of Matrix A, but this requires an insane amount of time (especially in 3-dimensional matrices) In other words, I want to apply a convolution filter without summing up the multiplication results at the end, but apply them to the underlying values of the convolved matrix (A) Any insights on this issue are appreciated.
has comment: http://stackoverflow.com/comment/84752350
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84753059
favorite count: 0
tagged with: python-3.x
upvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84753519
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84752377
has title: Multiplying a numpy array with another numpy array at a specific index
score: 1
has comment: http://stackoverflow.com/comment/84752830
tagged with: simpleitk

http://stackoverflow.com/q/48941964
has body: I believe I answered my own question while trying to figure out how to ask it properly, but since I found the answer in Python's documentation to be rather opaque, I thought I'd still post the question here. While trying to understand the rules of single-line assignments in Python, I came across some examples that contradict the usual statement that "single-line assignments to multiple variables all take place at once". a = 0 # variable 'a' must be assigned first a, b = 1, a # a, b :: 1, 0 x = [2, 3, 4, 5, 6] i, x[i] = 4, 99 # i, x[4] :: 4, 99; variable 'i' does not need to have been previously assigned c = 8 # variable 'c' must be assigned first c, d = 9, print(c) # c, d :: 9, None; prints 8 My confusion had to do with the fact that Python reassigned 'i' (i.e., the list index) first, before assigning 99 to index 4 of list 'x'. While Python's documentation directly addresses this issue as following, Although the definition of assignment implies that overlaps between the left-hand side and the right-hand side are ‘simultaneous’ (for example a, b = b, a swaps two variables), overlaps within the collection of assigned-to variables occur left-to-right, sometimes resulting in confusion. I did not understand what it meant by "overlaps within the collection of assigned-to variables". I see now that the parser will check to see if the indexing value for a given List has been reassigned before it assigns a new value to that index of the list. Notes: This is confirmed by the fact that, in this case, 'i' did not need to be assigned first before it was used as a variable index, while for 'a' it was necessary (otherwise, Python would throw an error). For those curious, here's the <a href="http://pythontutor.com/visualize.html#code=a%20%3D%200%20%23%20variable%20'a'%20must%20be%20assigned%20first%0A%0Aa,%20b%20%3D%201,%20a%20%23%20a,%20b%20%3A%3A%201,%200%0A%0Ax%20%3D%20%5B2,%203,%204,%205,%206%5D%0A%0Ai,%20x%5Bi%5D%20%3D%204,%2099%20%23%20i,%20x%5B4%5D%20%3A%3A%204,%2099%0A%0Ac%…
answer count: 3
accepted answer: http://stackoverflow.com/a/48958339
downvote count: 0
favorite count: 0
has answer: http://stackoverflow.com/a/48942188
tagged with: variable-assignment
tagged with: python
possible better answer: http://stackoverflow.com/a/48942148
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48942148
tagged with: list
has title: Explain the difference between single-line assignment of integer x, item in list[x], and single-line assignments of inter-referencing variables
has answer: http://stackoverflow.com/a/48958339
upvote count: 1
type: Question
score: 1
linked to: http://stackoverflow.com/q/16409901

http://stackoverflow.com/q/48872795
has comment: http://stackoverflow.com/comment/84749673
answer count: 1
has answer: http://stackoverflow.com/a/48872896
favorite count: 0
tagged with: python-3.x
has title: Please explain these commands in the code
type: UnansweredQuestion
score: -3
tagged with: python
has comment: http://stackoverflow.com/comment/84749500
has body: n=int(input("Enter number of rows: ")) a=[] for i in range(n): a.append([]) a[i].append(1) for j in range(1,i): a[i].append(a[i-1][j-1]+a[i-1][j]) if(n!=0): a[i].append(1) for i in range(n): print(" "*(n-i),end=" ",sep=" ") for j in range(0,i+1): print('{0:6}'.format(a[i][j]),end=" ",sep=" ") print() my qestions: 1-please explain the 7th line's append index(I didnt undersand what did it try to say with a[i-1][j-1]+a[i-1][j] 2-why do we need to put an empty print at the end? print()
upvote count: 1
type: Question
downvote count: 4
tagged with: arrays

http://stackoverflow.com/comment/84832973
type: AnswerComment
has text: \@progmatico You can think they are separate function modules, `Example1` just the project name. Submodules underneath can be responded by different developers and be installed separatly. In this example, I'm trying to simulate this scenario, but in real project, each submodule might have it's own `setup.py`, so that means they will be packaged to different release packages just like two separate projects. I'm trying to hide detail structure in one module to an other one.
comment on: http://stackoverflow.com/a/48890910
type: Comment
score: 0

flask-restplus
tag name: flask-restplus
tags question: http://stackoverflow.com/q/48825957
type: Tag

http://stackoverflow.com/q/48916464
has title: python linear equation with Cramer's rule
has comment: http://stackoverflow.com/comment/84839433
has comment: http://stackoverflow.com/comment/84839648
answer count: 1
has comment: http://stackoverflow.com/comment/84839504
favorite count: 0
has comment: http://stackoverflow.com/comment/84839583
has body: I'm new to python and attempting to write a linear equation using Cramer's Rule. I've entered the formula and have code prompting user to enter a,b,c,d,e and f but my code is getting a syntax error. I'd like to fix the code and also have a system for researching and correcting future errors. a,b,c,d,e,f = float(input("Enter amount: ") a*x + by = e cx + dy = f x = ed-bf/ad-bc y=af-ed/ad-bc if (ad - bc == 0)print("The equation has no solution") else print ("x=" x, "y=" y,)
tagged with: python
has answer: http://stackoverflow.com/a/48916625
accepted answer: http://stackoverflow.com/a/48916625
has comment: http://stackoverflow.com/comment/84839528
type: AnsweredQuestion
downvote count: 2
has comment: http://stackoverflow.com/comment/84839552
upvote count: 1
has comment: http://stackoverflow.com/comment/84839390
type: Question
score: -1
tagged with: linear-algebra

http://stackoverflow.com/q/48862031
has comment: http://stackoverflow.com/comment/84733494
score: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/84734632
tagged with: python
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84732228
has comment: http://stackoverflow.com/comment/84732554
has comment: http://stackoverflow.com/comment/84729714
has comment: http://stackoverflow.com/comment/84730838
has title: Correct application of pd.rolling
type: Question
has comment: http://stackoverflow.com/comment/84727008
has body: For a time now I have found the usage of pd.rolling a bit strange. I previously used pd.rolling_mean but I think that's deprecated. Now I am using: df.A.rolling(window=[0.1, ...], win_type='boxcar'), so I want a custom window. In my understanding, which is also shown in the result, if I pass a custom window window type is not needed - but I get an error in that case saying that window needs to be an integer. But, as I said, I just expect win_type to have an influence if I pass a window size instead of an array. Am I wrong? Further, now I want to use that on groupby - but I just cant get it to run with a custom array. Example: Writing df.groupby('B').A.rolling(window=[0.1, ...], win_type='boxcar') again gives me the error: Window must be an integer. Could you help me? So in general I want to group my dataframe by some column (lets say B), and then apply a filter to some other column (lets say A). For the filter I need custom weights [a_1, ..., a_n], s.t. each value x_t = x_{t-1} * a_n + ... + x_{t-n} * a_1. Example what I want with window [0.5, 0.5]: B A Output 0 0 nan 0 1 0.5 0 2 1.5 1 4 nan 1 6 5

http://stackoverflow.com/comment/84688161
score: 1
type: AnswerComment
has text: No, you would do something like: `[i for i in csv_files if '2016' in i]`
comment on: http://stackoverflow.com/a/48841756
type: Comment

http://stackoverflow.com/q/48944802
score: -3
has body: The following code displays some output. From it, how to get the first row only? #!/usr/bin/env python # coding=utf-8 from bs4 import BeautifulSoup import requests url = u'https://ta.wikisource.org/w/index.php?title=அட்டவணை பேச்சு:நாடகக்கலை-2.pdf&amp;action=history' content = requests.get(url).content soup = BeautifulSoup(content,'lxml') #talkPage1 = soup.findAll(id='mw-content-text') talkPage2 = soup.findAll(id='mw-history-compare') for link in talkPage2: print(link.text) The output:- (நடப்பு | முந்திய) 05:56, 23 பெப்ரவரி 2018‎ Info-farmerBot (பேச்சு | பங்களிப்புகள்)‎ . . (வெற்று) (-4)‎ . . (-) (மீளமை) (அடையாளம்: Blanking) (நடப்பு | முந்திய) 05:55, 23 பெப்ரவரி 2018‎ Info-farmerBot (பேச்சு | பங்களிப்புகள்)‎ . . (4 எண்ணுன்மிகள்) (+4)‎ . . (gdeg) (மீளமை) . . . . (நடப்பு | முந்திய) 13:17, 28 ஜனவரி 2016‎ Info-farmer (பேச்சு | பங்களிப்புகள்)‎ . . (129 எண்ணுன்மிகள்) (+129)‎ . . (பகுப்பு:மின்னூல்கள்-பொதுகள உரிமம்-துப்புரவு‎) The output that we need only the first row as follows:- (நடப்பு | முந்திய) 05:56, 23 பெப்ரவரி 2018‎ Info-farmerBot (பேச்சு | பங்களிப்புகள்)‎ . . (வெற்று) (-4)‎ . . (-) (மீளமை) (அடையாளம்: Blanking)
favorite count: 0
has comment: http://stackoverflow.com/comment/84896210
tagged with: beautifulsoup
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48945896
possible better answer: http://stackoverflow.com/a/48945206
tagged with: python
has answer: http://stackoverflow.com/a/48945206
type: AnsweredQuestion
has title: How to complete the code to get the output's first row only from a wikipedia page?
downvote count: 3
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84896185
upvote count: 0
has comment: http://stackoverflow.com/comment/84896421
has answer: http://stackoverflow.com/a/48945896

http://stackoverflow.com/a/48826344
upvote count: 3
answers question: http://stackoverflow.com/q/48826080
score: 3
downvote count: 0
has body: Pandas merge could also works: df1.index = df2.index pd.merge(df1, df2, how='inner', left_index=True, right_index=True, sort=True, suffixes=('_x', '_y')) output : name_x tag_x x y name_y tag_y position1 position2 0 001_Dc F 243 567 jps_043 EW 908 219
type: Answer

http://stackoverflow.com/comment/84835662
comment on: http://stackoverflow.com/q/48914146
has text: 1) This is in it's naive form **unconstrained** optimization (with bounds). Much easier than constrained opt. 2) GA are just (personal opinion: dumb) incomplete heuristics without formal guarantees which only work in a limited a-priori analyzed domain while being highly tuned. 3) As this looks non-convex, you need to decide if local-opt solutions are okay (easy) or global-opts are needed (not so easy)
score: 1
type: Comment
type: QuestionComment

http://stackoverflow.com/a/48860713
has comment: http://stackoverflow.com/comment/105222853
has body: You need to convert your dates to floats, then format the x-axis to reinterpret and format the floats into dates. Here's how I would do this: import pandas import seaborn from matplotlib import pyplot, dates %matplotlib inline date = ['1975-12-03','2008-08-20', '2011-03-16'] value = [1,4,5] df = pandas.DataFrame({ 'date': pandas.to_datetime(date), # pandas dates 'datenum': dates.datestr2num(date), # maptlotlib dates 'value': value }) @pyplot.FuncFormatter def fake_dates(x, pos): """ Custom formater to turn floats into e.g., 2016-05-08""" return dates.num2date(x).strftime('%Y-%m-%d') fig, ax = pyplot.subplots() # just use regplot if you don't need a FacetGrid seaborn.regplot('datenum', 'value', data=df, ax=ax) # here's the magic: ax.xaxis.set_major_formatter(fake_dates) # legible labels ax.tick_params(labelrotation=45)
type: AcceptedAnswer
downvote count: 0
upvote count: 8
type: Answer
has comment: http://stackoverflow.com/comment/105219705
accepted answer of: http://stackoverflow.com/q/48860428
score: 8
answers question: http://stackoverflow.com/q/48860428

http://stackoverflow.com/a/48910570
answers question: http://stackoverflow.com/q/48910486
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/84831436
score: 2
has comment: http://stackoverflow.com/comment/84827367
upvote count: 2
has comment: http://stackoverflow.com/comment/109196254
has body: You need to simply pass a list of markers in your call to sns.lmplot: import seaborn as sns df = pd.DataFrame({'animals':pd.Series(['tiger','cheetah','lion','giraffe','elephant','gorilla']), 'weight': pd.Series([200,120,240,240,400,300]), 'meal': pd.Series([20,10,40,15,40,30]), 'region': pd.Categorical(["Asian","American","African","African",'Asian','American']), 'gender': pd.Categorical(["female","female","male","female",'male','male']), 'group': pd.Series([True, False, False, True, True, True])}) sns.lmplot(data = df, x = 'weight', y = 'meal', hue = 'region', palette = 'Dark2', fit_reg = False, scatter_kws={"s": 20}, size = 4, markers=["o","+","x"]) plt.show() Which gives:

http://stackoverflow.com/a/48948695
has comment: http://stackoverflow.com/comment/84938205
accepted answer of: http://stackoverflow.com/q/48948495
answers question: http://stackoverflow.com/q/48948495
score: 0
type: AcceptedAnswer
has body: seven_days is a list you are passing in HTML. Use for loop to display all items in list: Today's temperature:{{daytemp}} {% for temp in seven_days %} {{ temp }} {% end for %} Prague is the capital and largest city in the Czech Republic
type: Answer

http://stackoverflow.com/a/60456171
has body: The Conda-Cheatseet here lists these following commands. Save Environment: conda list --explicit &gt; my-env.txt Create Environment: conda env create --file my-env.txt
type: Answer
score: 3
answers question: http://stackoverflow.com/q/48871289
upvote count: 3
downvote count: 0

http://stackoverflow.com/q/48932839
type: UnansweredQuestion
has title: Can't see the django home page
tagged with: django
has comment: http://stackoverflow.com/comment/84872632
type: Question
has answer: http://stackoverflow.com/a/48933083
answer count: 1
has comment: http://stackoverflow.com/comment/84872597
score: 0
has body: I'm new to django, thus the question. I've a django project set up with two apps both of which seem to work fine. Just that I can't reach the homepage - which should be the default django page. I get the following error, Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/ Using the URLconf defined in core.urls, Django tried these URL patterns, in this order: admin/ ^aggregator/ ^bouncer/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. This is my urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^aggregator/', include('aggregator.urls')), url(r'^bouncer/', include('bouncer.urls')), ] What am I missing here?
tagged with: python
has comment: http://stackoverflow.com/comment/84872653

http://stackoverflow.com/comment/84828097
score: 0
type: Comment
has text: @JonSalji you are welcome. Please edit you post to add a sample of the `test_labels` variable as returned in your own initial code (or the `batch_labels` of my loop - they should be the same)
comment on: http://stackoverflow.com/a/48909971
type: AnswerComment

http://stackoverflow.com/comment/84643769
has text: Then you probably need to show how you have configured nginx to serve the static files as gunicorn doesn't do it for you. The only way to have gunicorn do it for you is to use WhiteNoise middleware.
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48813329

http://stackoverflow.com/comment/84928672
has text: Where do you expect your mouse click to be performed? Try printing the coordinates of the located window as well as the center of it.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48961099
type: QuestionComment

http://stackoverflow.com/a/48852013
has comment: http://stackoverflow.com/comment/84783009
type: AcceptedAnswer
has body: This took me a great deal of debugging to fix, haha. First of all, you are not escaping or updating in any of your while loops. Once the code enters your first while loop, nothing (the pygame.display) ever updates after that – resulting in your white-screen syndrome. In addition, please name your variables consistently and check for typos in your code. You created a blueSquareVy variable only to try to refer to it as blueSquareVY later, and you misspelled pygame.display.update() at the end of the code. Capitalization matters – and that's just a few of the typos! There are also logical errors within the code. You should not fill your window surface after your graphics have been drawn onto the screen. Looking at your variables, it seems that you would like the little squares to move. You would create the position variables outside of the while loop, as if you create them within the loop, they get recreated at their initial value every iteration of the loop. The annotated and bugfixed code: import pygame, sys, random import pygame.locals as GAME_GLOBALS import pygame.event as GAME_EVENTS pygame.init() windowWidth = 640 windowHeight = 480 surface = pygame.display.set_mode((windowWidth, windowHeight)) pygame.display.set_caption('Pygame Shapes!') # Renamed variables to be consistent # Moved variables out of the while loop greenSquareX = windowWidth / 2 greenSquareY = windowHeight / 2 blueSquareX = 0.0 blueSquareY = 0.0 blueSquareVX = 1 blueSquareVY = 1 # Joined the two while loops into one while True: surface.fill((200, 0, 0)) pygame.draw.rect(surface, (255, 0, 0), (random.randint(0, windowWidth), random.randint(0, windowHeight), 10, 10)) surface.fill((0, 0, 0)) pygame.draw.rect(surface, (0, 255, 0), (greenSquareX, greenSquareY, 10, 10)) greenSquareX += 1 greenSquareY += 1 pygame.draw.rect(surface, (0, 0, 255), (blueSquareX, blueSquareY, 10, 10)) blueSquareX += blueSquareVX blueSquareY += blueSquareVY blueSquareVX += 0.1 blueSquareVY += 0.1 # Do not capitalize the .get() …
has comment: http://stackoverflow.com/comment/84707631
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48851883
has comment: http://stackoverflow.com/comment/84707827
answers question: http://stackoverflow.com/q/48851883
has comment: http://stackoverflow.com/comment/84707667
score: 4

distinct
tag name: distinct
tags question: http://stackoverflow.com/q/48897401
type: Tag

http://stackoverflow.com/comment/84684168
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48839502
type: AnswerComment
has text: @Denis really? can you please provide me a link about using html forms and validating using forms?it is a great approach

http://stackoverflow.com/a/48950566
accepted answer of: http://stackoverflow.com/q/48950421
type: AcceptedAnswer
type: Answer
has body: You are looking at the wrong thing. rfe.ranking_ will always return the ranking of all the features. But the selected features have value 1 in ranking_ Print the ranking_ and see: ranking # Output: array([1, 1, 3, 2]) This means that 1st and 2nd features are selected.
answers question: http://stackoverflow.com/q/48950421
score: 0

http://stackoverflow.com/a/48864477
answers question: http://stackoverflow.com/q/48855198
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/84783755
has body: The problem is that there is a figure created which is supposed to be shown in the notebook. However, you do not want to show the mplleaflet figure as an interactive figure with the %matplotlib notebook backend. One idea is to not use the %matplotlib notebook such that the area where the figure mplleaflet figure would be placed is not filled with the unused figure. Alternatively use %%capture in order to suppress the output when using %matplotlib notebook. Then call mplleaflet.display in a new non-captured cell:
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48855198
type: Answer

http://stackoverflow.com/a/48924646
type: Answer
upvote count: 1
answers question: http://stackoverflow.com/q/48924491
score: 1
has body: def ith_element(d, i): return { k : v[i] for k, v in d.items() } Here is a little dict comprehesion that will do the job. You just go over all key-value pairs in the dictionary one at a time and do some transformation with it resulting as another dictionary with the same amount of pairs as an exisiting one. You can read more about list comprehensions here.
downvote count: 0

http://stackoverflow.com/q/48878188
score: -1
type: Question
has body: Is there anything prescriptive about which kind of preprocessing technique to use? For now, I am trying to perform a classification where the dataset comprises of categorical as well as numerical variables. My question is whether there is any recommendation as to when to use MinMaxScaler, StandardScaler, and Normalizer.
answer count: 1
has comment: http://stackoverflow.com/comment/84760464
tagged with: scikit-learn
favorite count: 0
has title: PreProcessing in Python - Classification Exercise
tagged with: python-3.x
upvote count: 0
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48881391
tagged with: python
has comment: http://stackoverflow.com/comment/84760375
downvote count: 1

http://stackoverflow.com/comment/84814251
comment on: http://stackoverflow.com/q/48903408
score: 0
type: Comment
type: QuestionComment
has text: I found the problem already. As you said the problem was in slash. Anyway can you post your answer as a post (not like a comment), I will mark it, bro ;)

http://stackoverflow.com/comment/84726948
score: 0
comment on: http://stackoverflow.com/q/48861126
type: Comment
type: QuestionComment
has text: As mentioned in [my answer](https://stackoverflow.com/a/48861282/1170207), `mask` needs to be 8-bit. Why do you want it to be 16 -bit? It's essentially just a boolean array, and since C doesn't have a boolean type, it is a "unsigned int 8" type `uint8_t`.

http://stackoverflow.com/q/48869032
tagged with: tensorflow
has comment: http://stackoverflow.com/comment/84742808
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84744268
has title: Tensorflow GPU installation error, Ubuntu
has comment: http://stackoverflow.com/comment/84742151
tagged with: python-3.x
type: Question
tagged with: pip
tagged with: python
score: 0
has body: I am trying to install Tensorflow GPU, when executed this command, pip3 install --upgrade tensorflow-gpu i get this error. Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 33, in vendored __import__(vendored_name, globals(), locals(), level=0) ImportError: No module named 'pip._vendor.pkg_resources' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/bin/pip3", line 9, in &lt;module&gt; from pip import main File "/usr/lib/python3/dist-packages/pip/__init__.py", line 13, in &lt;module&gt; from pip.exceptions import InstallationError, CommandError, PipError File "/usr/lib/python3/dist-packages/pip/exceptions.py", line 6, in &lt;module&gt; from pip._vendor.six import iteritems File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 75, in &lt;module&gt; vendored("pkg_resources") File "/usr/lib/python3/dist-packages/pip/_vendor/__init__.py", line 36, in vendored __import__(modulename, globals(), locals(), level=0) File "&lt;frozen importlib._bootstrap&gt;", line 969, in _find_and_load File "&lt;frozen importlib._bootstrap&gt;", line 958, in _find_and_load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 664, in _load_unlocked File "&lt;frozen importlib._bootstrap&gt;", line 634, in _load_backward_compatible File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2927, in &lt;module&gt; File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2913, in _call_aside File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2952, in _initialize_master_working_set File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 956, in subscribe File "/usr/share/python-wheels/pkg_resources-0.0.0-py2.py3-none-any.whl/pkg_resources/__init__.py", line 2952, in &lt…
has comment: http://stackoverflow.com/comment/84742172

http://stackoverflow.com/q/48824628
tagged with: python
answer count: 4
has body: Why assignment fails at else part ? I was trying to increment two variables based on a condition in below one line . &gt;&gt;&gt; a=0 &gt;&gt;&gt; b=0 &gt;&gt;&gt; a+=1 if True else b &gt;&gt;&gt; a &gt;&gt;&gt; 1 &gt;&gt;&gt; a if True else b+=1 File "&lt;input&gt;", line 1 SyntaxError: can't assign to conditional expression &gt;&gt;&gt; a if False else b+=1 File "&lt;input&gt;", line 1 SyntaxError: can't assign to conditional expression &gt;&gt;&gt; a+=1 if False else b &gt;&gt;&gt; a &gt;&gt;&gt; 1 &gt;&gt;&gt; a+=1 if True else b+=1 File "&lt;input&gt;", line 1 a+=1 if True else b+=1 ^ SyntaxError: invalid syntax
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48824818
has comment: http://stackoverflow.com/comment/84652841
downvote count: 1
possible better answer: http://stackoverflow.com/a/48825267
type: Question
has answer: http://stackoverflow.com/a/48824771
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48825267
has title: python assignment fails in else part of conditional operation
has answer: http://stackoverflow.com/a/48824680
has comment: http://stackoverflow.com/comment/84653303
favorite count: 0
accepted answer: http://stackoverflow.com/a/48824680

http://stackoverflow.com/q/48833644
has answer: http://stackoverflow.com/a/48836241
has title: How to wait for asynchronous callback in the background (i.e. not invoked by us)
type: UnansweredQuestion
has body: Goal is to allocate a thread and wait for the callback. Single thread is going to run the while loop forever. Difficulty here is that we are not directly calling or controlling the callback and we do not know in advance how long it will takes to the remote server to invoke callback. I've tried to look for a solution in the asyncio module using asyncio.Future but unsuccessfully. from a_module import Server # &lt;a_module&gt; is fictitious import random import time class App(Server): def __init__(self): self.response = None def send_requests(self): """Send request to remote server""" self.send_number_to_server(42) # inherited from Server # This is going to loop forever. We should "suspend" the # current thread, allocate a new thread to wait for the # callback and then comeback here to return the (not None) # response. while self.response is None: # Wait for the callback before terminating this method. time.sleep(1) # seconds return self.response def callback(self, message): """Inherited form parent class 'Server'. When the request sent with App.send_req has been processed by the remote server, this function is invoked in the background.""" self.response = message if __name__ == '__main__': app = App() response = app.send_requests() print(response)
downvote count: 0
score: 1
tagged with: asynchronous
tagged with: callback
favorite count: 0
type: Question
tagged with: python-asyncio
has comment: http://stackoverflow.com/comment/84672121
tagged with: python
tagged with: tws
upvote count: 1
answer count: 1

http://stackoverflow.com/comment/84721930
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48858913
type: Comment
has text: Your example does work, and one I did with a small set of values manually entered, also worked. For some unknown reason, when I went back to my actual (larger) files, it did not work. The actual file has 40 different values to compare against a list with 550 values. After running it, some of the 40 (df7) were still found in the list of 550 (df6).

http://stackoverflow.com/comment/84657827
comment on: http://stackoverflow.com/a/48824046
score: 0
type: AnswerComment
type: Comment
has text: Changed in version 3.3: tm_gmtoff and tm_zone attributes are available on platforms with C library supporting the corresponding fields in struct tm. [link](https://docs.python.org/3.5/library/time.html#time.strptime). Also my plattform doesn t support it.

http://stackoverflow.com/q/48958708
has answer: http://stackoverflow.com/a/49483349
has title: Pandas error: Can only use .str accessor with string values, which use np.object_ dtype in pandas
score: 0
has body: I have data in my .txt file as below: 029070 ***** 190101010600 270 36 OVC ** 0.0 ** ** I want to extract 190101 from the column 3, I am getting AttributeError: Can only use .str accessor with string values, which use np.object_ dtype in pandasbelow is my python pandas. Below is my code import pandas as pd import numpy as np import re data = pd.read_csv('dummy.txt', sep=" ", low_memory=False, header=None) data.columns = ["a", "b", "c","d","e","f","g","h","i","j"] print(data.c.str[0:6])
answer count: 1
favorite count: 0
tagged with: pandas
has comment: http://stackoverflow.com/comment/106894415
tagged with: python
type: UnansweredQuestion
upvote count: 1
downvote count: 1
linked to: http://stackoverflow.com/q/52065909
type: Question

http://stackoverflow.com/a/48938445
has comment: http://stackoverflow.com/comment/84884419
score: 0
type: Answer
has body: Update: Thanks for clarifying it further. However, with the requirements and approach you just mentioned, you are going to end up reinventing multi-threading. I suggest you avoid the multiple script calls and have all control inside your loop(s) (like the one in my original response). You are probably looking for querying the memory usage of the processes (like this). One particular component that might help you here is setting priority of the individual tasks (mentioned here). You may find this link particularly useful for scheduling priority of tasks. Infact, I recommend using threading2 package here, since it has inbuilt features on priority control. Original Response: Since you have roughly identified which parts require how much memory, you may employ multithreading pretty easily. import threading thread1 = threading.Thread(target=process1 , args=(yourArg1,)) # process1 takes 1 GB thread2 = threading.Thread(target=process2 , args=(yourArg1,)) # process2 takes 1 GB threadList1 = [thread1,thread2] thread3 = threading.Thread(target=process3 , args=(yourArg1,)) # process3 takes 0.5 GB thread4 = threading.Thread(target=process4 , args=(yourArg1,)) # process4 takes 0.5 GB threadList2 = [thread3,thread4] # Batch1 : for thread in threadList1: thread.start() for thread in threadList1: thread.join() # Batch2 : for thread in threadList2: thread.start() for thread in threadList2: thread.join()
answers question: http://stackoverflow.com/q/48937669
upvote count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/84884616
has comment: http://stackoverflow.com/comment/84887482
has comment: http://stackoverflow.com/comment/84886048

http://stackoverflow.com/comment/84886598
type: Comment
has text: I'm expecting N_i to be {0: 3, 1: 4, 2: 3} did I get the idea wrong? Then how does it display the count?
type: QuestionComment
comment on: http://stackoverflow.com/q/48939750
score: 0

http://stackoverflow.com/comment/84905029
score: 0
has text: If you have a problem with matplotlib please post a https://stackoverflow.com/help/mcve only related to the issue. No need for all the other stuff. Just add some example data that has the same format as what you expect.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48940407

http://stackoverflow.com/comment/84617904
type: Comment
has text: It's been too long since I set it up, but I quickly googled it and here's a way to set it up : https://pypi.python.org/pypi/PyAutoIt/0.3
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48807149

http://stackoverflow.com/q/48925555
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84864513
tagged with: pyqt5
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84865108
has answer: http://stackoverflow.com/a/48937422
has body: While working on an app for scientific purposes, I struggled to add items to QListWidget. I did not find any documentation for PyQt5, so decided to ask here. I am not directly sure if the usage of QListWidget is right, so correct me if I'm wrong. UPD: Next iteration. What I have done. I got names and paths of a folder's content into an array. Where in the first column I get names of files and in second theirs paths. sample_directory = [] sample_files = [] for (dirpath, dirnames, filenames) in walk('./Samples'): sample_files.extend(filenames) break paths = [] for i in range(len(sample_files)): path = os.path.realpath(sample_files[i]) paths.append(path) sample_directory.append(sample_files) sample_directory.append(paths) [['exmpl1.xlsx', 'exmpl2.xlsx'], ['/Users/Graygood/Desktop/Science comput/Application/exmpl1.xlsx', '/Users/Graygood/Desktop/Science comput/Application/exmpl2.xlsx']] Next, I added the first column of sample_directory to QListWidget self.sampleChoose_list.addItems(sample_directory[0]) What I need now. On button click, when file is chosen, the path to the file should be given to the process function. How can I do it? How can I call the chosen file? Process function is the function, that gets the path of chosen item, reads it with pandas.read_excel(sample_directory[0][0]) and makes some work with array. Something like: def process(self): sample = pd.read_excel(path_of_a_chosen_file) #Where path_of_a_chosen_file is sample_directory[1][i] and i - index of chosen file list_of_index = [] for i in range(len(sample.columns)): sample2 = sample.iloc[:, lambda sample: [i]] sample2 = sample2.columns[0] list_of_index.append(sample2) list_of_index return self.list_of_index
has comment: http://stackoverflow.com/comment/84865145
upvote count: 0
score: -1
has title: Get the name of a chosen item in QListWidget PyQt5
has comment: http://stackoverflow.com/comment/84861903
has comment: http://stackoverflow.com/comment/84858825
tagged with: pyqt
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48937422
has comment: http://stackoverflow.com/comment/84858887
tagged with: python
has comment: http://stackoverflow.com/comment/84857994
has comment: http://stackoverflow.com/comment/84863990
has comment: http://stackoverflow.com/comment/84861812

http://stackoverflow.com/q/48905837
answer count: 1
has answer: http://stackoverflow.com/a/48917872
favorite count: 0
has comment: http://stackoverflow.com/comment/84821763
has comment: http://stackoverflow.com/comment/84817770
has comment: http://stackoverflow.com/comment/84817426
upvote count: 2
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84817446
has comment: http://stackoverflow.com/comment/84819201
downvote count: 2
tagged with: python
has body: Sorry for bothering you guys again, but I am not able to solve this problem by myself. I need to do unittesting with the outputs of several functions. My (simplified) functions look like this: def myfunc1(input1,input2,input3): # processing the inputs ... # new values are then saved in dictionaries mat = {'mat1': mat1, 'mat2': mat2, 'mat3': mat3} kat = {'kat1': kat1, 'kat2': kat2, 'kat3': kat3} # and are returned return mat, kat def myfunc2(input4,input5,input6): # processing the inputs ... # new values are then saved in dictionaries tra = {'tra1': tra1, 'tra2': tra2, 'tra3': tra3} lala = {'lala1': lala1, 'lala2': lala2, 'lala3': lala3} # and are returned return tra, lala How can I now test the following? test whether 'mat' and 'tra' have the same dimensions test whether 'lala1' and 'kat1' have the same dimensions EDIT: This would be a first approach of my unittesting script (: import unittest from funcscript import * # my example class myTests(unittest.TestCase): # test whether the size of the first dimension of two dictionary elements are the same def test_comparing(self): self.assertEqual(**WHAT TO DO HERE?**,**AND HERE?**, msg ='') if __name__ == "__main__": unittest.main()
has comment: http://stackoverflow.com/comment/84821383
has comment: http://stackoverflow.com/comment/84817975
tagged with: unit-testing
type: Question
has title: Unittesting the outputs of several functions
has comment: http://stackoverflow.com/comment/84818417
has comment: http://stackoverflow.com/comment/84822547
score: 0
has comment: http://stackoverflow.com/comment/84817628

http://stackoverflow.com/comment/84863186
type: QuestionComment
has text: You have some serious problems there, for instance you are escaping some letters like `L`, `F`,`N` that do not need to be escaped while others like `\S` do mean sth. different than `S`. Your [**expression does not even match the line**](https://regex101.com/r/xTFu4U/1). Additionally, `\A` matches the very beginning of a string not the letter `A`.
type: Comment
comment on: http://stackoverflow.com/q/48928355
score: 0

http://stackoverflow.com/a/48888523
upvote count: 6
has comment: http://stackoverflow.com/comment/84806751
has comment: http://stackoverflow.com/comment/116986429
has body: You can use: df = case_claim_type.groupby(by=("case_type", "claim_type"))["case_type"].count() print (df) case_type claim_type chargeback local_charges 1 service 1 service service 2 supplier_service 1 Name: case_type, dtype: int64 You can create new DataFrame by aggregate sum and add MultiIndex by MultiIndex.from_tuples: df1 = df.sum(level=0) #same as #df1 = df.groupby(level=0).sum() new_cols= list(zip(df1.index.get_level_values(0),['total'] * len(df.index))) df1.index = pd.MultiIndex.from_tuples(new_cols) print (df1) chargeback total 2 service total 3 Name: case_type, dtype: int64 Then concat together and last sort_index: df2 = pd.concat([df,df1]).sort_index() print (df2) case_type claim_type chargeback local_charges 1 service 1 total 2 service service 2 supplier_service 1 total 3 Name: case_type, dtype: int64
answers question: http://stackoverflow.com/q/48888302
type: Answer
has comment: http://stackoverflow.com/comment/116986343
has comment: http://stackoverflow.com/comment/116986242
has comment: http://stackoverflow.com/comment/84806802
downvote count: 0
score: 6
has comment: http://stackoverflow.com/comment/116986052

http://stackoverflow.com/comment/84697882
comment on: http://stackoverflow.com/a/48819829
score: 0
type: Comment
type: AnswerComment
has text: Thank you, that's a very Pythonic answer.

http://stackoverflow.com/a/48841162
upvote count: 3
answers question: http://stackoverflow.com/q/48839171
has comment: http://stackoverflow.com/comment/84706843
has body: You can try to separate the different issues into dictionaries and then get the permutations: &gt;&gt;&gt; df Issue Options Points 0 Bonus 10 4000 1 Bonus 8 3000 2 Bonus 6 2000 3 Bonus 4 1000 4 Bonus 2 0 5 Assignment A 0 6 Assignment B -600 7 Assignment C -1200 8 Assignment D -1800 9 Assignment E -2400 10 Leave 35 1600 11 Leave 30 1200 12 Leave 25 800 13 Leave 20 400 14 Leave 15 0 Now let's create a dictionary with all the possible issues as keys and as values, a dictionary with all the possible rows this way: &gt;&gt;&gt; d = {issue: df[df['Issue']==issue].copy().drop('Issue', axis=1).to_dict(orient='records') for issue in df['Issue'].unique()} &gt;&gt;&gt; d {'Assignment': [{'Options': 'A', 'Points': 0}, {'Options': 'B', 'Points': -600}, {'Options': 'C', 'Points': -1200}, {'Options': 'D', 'Points': -1800}, {'Options': 'E', 'Points': -2400}], 'Bonus': [{'Options': '10', 'Points': 4000}, {'Options': '8', 'Points': 3000}, {'Options': '6', 'Points': 2000}, {'Options': '4', 'Points': 1000}, {'Options': '2', 'Points': 0}], 'Leave': [{'Options': '35', 'Points': 1600}, {'Options': '30', 'Points': 1200}, {'Options': '25', 'Points': 800}, {'Options': '20', 'Points': 400}, {'Options': '15', 'Points': 0}]} And next we can get all the permutations between the dictionarties this way: &gt;&gt;&gt; from itertools import product &gt;&gt;&gt; combinations = [dict(zip(d, v)) for v in product(*d.values())] &gt;&gt;&gt; combinations [{'Assignment': {'Options': 'A', 'Points': 0}, 'Bonus': {'Options': '10', 'Points': 4000}, 'Leave': {'Options': '35', 'Points': 1600}}, {'Assignment': {'Options': 'A', 'Points': 0}, 'Bonus': {'Options': '10', 'Points': 4000}, 'Leave': {'Options': '30', 'Points': 1200}}, {'Assignment': {'Options': 'A', 'Points': 0},...] For the first combination we can obtain: &gt;&gt;&gt; issues = df['Issue'].unique() &gt;&gt;&gt; issues array(['Bonus', 'Assignment', 'Leave'], dtype=object) &gt;&gt;&gt; c1 = ' + '.join([issue + ' %s'%combinations[0][issue]['Options'] for i…
accepted answer of: http://stackoverflow.com/q/48839171
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84706928
downvote count: 0
has comment: http://stackoverflow.com/comment/84700863
type: Answer
score: 3

http://stackoverflow.com/a/48830127
downvote count: 0
has body: The Python operator | is not a logical or. Try using (1==1 or 2==1) instead.
upvote count: 2
type: Answer
score: 2
answers question: http://stackoverflow.com/q/48830065

http://stackoverflow.com/a/48938697
has comment: http://stackoverflow.com/comment/84884330
type: Answer
accepted answer of: http://stackoverflow.com/q/48938632
answers question: http://stackoverflow.com/q/48938632
has comment: http://stackoverflow.com/comment/84884402
score: 1
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: &gt;&gt;&gt; from __future__ import division ... ... result = [] ... text = "20 7/8 16 1/4" ... for num in text.split(): ... try: ... numerator, denominator = (int(a) for a in num.split('/')) ... result.append(numerator / denominator) ... except ValueError: ... result.append(int(num)) ... &gt;&gt;&gt; result [20, 0.875, 16, 0.25]

http://stackoverflow.com/a/48895852
accepted answer of: http://stackoverflow.com/q/48895811
score: 3
has comment: http://stackoverflow.com/comment/84797541
upvote count: 3
has comment: http://stackoverflow.com/comment/84797520
answers question: http://stackoverflow.com/q/48895811
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: You can first compare your entire df with -999, then count the number of none zero columns. df.eq(-999).any().sum() Out[302]: 2 A bit explanation: df.eq(-999) gives a True/False matrix, indicating if the element is equal to -999: Out[308]: A B C 1/2/2007 False False False 1/3/2007 False False False 1/4/2007 False False False 1/5/2007 True False False 1/6/2007 False True False 1/7/2007 False False False 1/8/2007 False True False .any() checks if any element in a column is True, which returns: Out[309]: A True B True C False dtype: bool In this example, Column A and B are true since they have at least one Trues. Finally, .sum() counts the number of Trues, (True is automatically cast to 1 and False to 0 in a sum operation)

http://stackoverflow.com/a/48940137
has comment: http://stackoverflow.com/comment/84889173
answers question: http://stackoverflow.com/q/48939280
accepted answer of: http://stackoverflow.com/q/48939280
upvote count: 1
type: AcceptedAnswer
has body: You can't use the class before it has been defined. And you can't use symbol and id yet, even though the names can be correctly resolved from within the class block itself, because the ORM hasn't had a chance to prepare the columns yet. This is one of tasks of declarative Base, and Foo will inherit a metaclass which needs to prepare the model. Assuming you set up the session correctly, you should be able to dynamically contribute this attribute on the class outside of the class definition block: class Foo(Base): __tablename__ = 'currency' id = Column(Integer, primary_key=True) name = Column(String(40), nullable=False, unique=True) symbol = Column(String(4), nullable=False, unique=True) Foo.l = session.query(Foo.symbol, Foo.id).all()
type: Answer
downvote count: 0
score: 1

http://stackoverflow.com/comment/84646457
comment on: http://stackoverflow.com/q/48821518
type: Comment
type: QuestionComment
score: 3
has text: "Also as dictionaries are not iterable" not sure were you got this from. You can always iterate a dictionary `for key in mongo` or `for key, value in mongo.iteritems()`

http://stackoverflow.com/a/66140324
has body: I have a similar issue and after searching and testing for almost entire day the this solution https://stackoverflow.com/a/48237220 works for me very well. We need to install and configure X window with virtual screen on headless server and then run our python script which initiate tkinter. In this way, the modification of code is not necessary, yeah.
answers question: http://stackoverflow.com/q/48924590
type: Answer
score: 0

http://stackoverflow.com/q/48883792
accepted answer: http://stackoverflow.com/a/48884145
has comment: http://stackoverflow.com/comment/84772858
type: Question
has comment: http://stackoverflow.com/comment/84772668
has answer: http://stackoverflow.com/a/48884759
downvote count: 0
has body: I want to create a python list with regular gaps. I have a general idea of how I can do it, but is there a short way to do it or an inbuilt function to do this. Suppose I want to create a list from 1 to 200, with gaps of 50. The list would be [1,..,50,101,..,150], i.e the sequence from 51 to 100 and 151 to 200 is not in the list. def create_list_step(start,end,step): result = [] current = start while current &lt; end: smallinterval = current + step result = result + list(range(current, smallinterval)) current = smallinterval + step return result
favorite count: 0
possible better answer: http://stackoverflow.com/a/48883878
has comment: http://stackoverflow.com/comment/84772057
has answer: http://stackoverflow.com/a/48883878
has answer: http://stackoverflow.com/a/48884331
has title: Python, list with regular gaps
tagged with: python
has answer: http://stackoverflow.com/a/48884145
answer count: 4
has comment: http://stackoverflow.com/comment/84772055
score: 2
tagged with: list
upvote count: 2
type: AnsweredQuestion

http://stackoverflow.com/a/48914476
score: 2
upvote count: 2
has comment: http://stackoverflow.com/comment/116989810
answers question: http://stackoverflow.com/q/48887547
has body: The equivalent of np.digitize method is called bucketize in TensorFlow, quoting from this api doc: Bucketizes 'input' based on 'boundaries'. Summary For example, if the inputs are boundaries = [0, 10, 100] input = [[-5, 10000] [150, 10] [5, 100]] then the output will be output = [[0, 3] [3, 2] [1, 3]] Arguments: scope: A Scope object input: Any shape of Tensor contains with int or float type. boundaries: A sorted list of floats gives the boundary of the buckets. Returns: Output: Same shape with 'input', each value of input replaced with bucket index. (numpy) Equivalent to np.digitize. I'm not sure why but, this method is hidden in TensorFlow (see the hidden_ops.txt file). So I wouldn't count on it even if you can import it by doing: from tensorflow.python.ops import math_ops math_ops._bucketize
accepted answer of: http://stackoverflow.com/q/48887547
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/48916718
answers question: http://stackoverflow.com/q/48913757
downvote count: 0
has body: Additionally, as commented, since you are not pivoting values to new columns in a wide format, consider simply using groupby(). And re-consider reindex() for custom January-December order, specifying the level and interfacing with python's built-in calendar module. import calendar ... grp_df = df.groupby(['client', 'month']).agg({'hours': 'sum'})\ .reindex(level=1, labels=calendar.month_name) # hours # client month # A January 11.25 # February 16.25 # April 11.25 # August 11.25 # December 16.25 # B January 11.25 # February 16.25 # April 8.25 # August 11.25 # December 16.25 # C January 11.25 # February 16.25 # April 14.25 # August 11.25 # December 16.25
type: Answer
score: 1
upvote count: 1

subprocess
tags question: http://stackoverflow.com/q/48910693
tag name: subprocess
tags question: http://stackoverflow.com/q/48895686
tags question: http://stackoverflow.com/q/48814481
tags question: http://stackoverflow.com/q/48859616
tags question: http://stackoverflow.com/q/48910093
tags question: http://stackoverflow.com/q/48874946
tags question: http://stackoverflow.com/q/48895468
tags question: http://stackoverflow.com/q/48950477
tags question: http://stackoverflow.com/q/48956583
tags question: http://stackoverflow.com/q/48930011
tags question: http://stackoverflow.com/q/48949468
tags question: http://stackoverflow.com/q/48813627
tags question: http://stackoverflow.com/q/48958814
tags question: http://stackoverflow.com/q/48931155
tags question: http://stackoverflow.com/q/48834036
tags question: http://stackoverflow.com/q/48837685
tags question: http://stackoverflow.com/q/48869803
type: Tag
tags question: http://stackoverflow.com/q/48866500
tags question: http://stackoverflow.com/q/48813083
tags question: http://stackoverflow.com/q/48813957
tags question: http://stackoverflow.com/q/48808035
tags question: http://stackoverflow.com/q/48862112
tags question: http://stackoverflow.com/q/48947895
tags question: http://stackoverflow.com/q/48890238
tags question: http://stackoverflow.com/q/48849044
tags question: http://stackoverflow.com/q/48923946
tags question: http://stackoverflow.com/q/48872847
tags question: http://stackoverflow.com/q/48836746
tags question: http://stackoverflow.com/q/48962019

http://stackoverflow.com/comment/84912697
comment on: http://stackoverflow.com/a/48952900
score: 0
type: AnswerComment
type: Comment
has text: Gee, that works, even if I do not understand it! Care to explain? (I swear I won't tell.) And, is the val = val - 9223372036854775808 really repeated twice?

http://stackoverflow.com/comment/84918870
score: 0
type: AnswerComment
type: Comment
has text: I put soup properties on all my Page Objects for just this reason :) Grab once with the webdriver, parse the tree. Fast, elegant, avoids mutiple selenium calls.
comment on: http://stackoverflow.com/a/48934192

http://stackoverflow.com/comment/84778246
comment on: http://stackoverflow.com/a/48886459
score: 0
type: Comment
has text: ya how can I pass this r'\bROAD\b' as a parameter(pattern) to that subst function?
type: AnswerComment

http://stackoverflow.com/a/48861787
upvote count: 5
has body: Series pd.Series({k: v[k].to_dict() for k, v in s.groupby(level=0)}) a {1: 'value_1', 2: 'value_2', 3: 'value_3'} b {2: 'value_4', 4: 'value_5', 5: 'value_6'} c {1: 'value_7', 5: 'value_8', 9: 'value_9'} dtype: object Dictionary {k: v[k].to_dict() for k, v in s.groupby(level=0)} {'a': {1: 'value_1', 2: 'value_2', 3: 'value_3'}, 'b': {2: 'value_4', 4: 'value_5', 5: 'value_6'}, 'c': {1: 'value_7', 5: 'value_8', 9: 'value_9'}}
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48861697
has comment: http://stackoverflow.com/comment/84727501
type: Answer
accepted answer of: http://stackoverflow.com/q/48861697
score: 5

http://stackoverflow.com/a/48844602
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48844489
type: Answer
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84711127
has body: You could try something of the form [(l2[0][i], l2[1][i]) == l1[i] for i in range(len(l1))] The question is a little vague about the comparison you would like to make, but I can infer (I hope correctly) that the idea is to take the two lists and "stack" them side by side so they look comparable to the list of tuples. Then, I assume you want to perform an equality check. Here, the equality check performed is an exact match on tuple. This could be incorrect. If so, I can revise my answer. I assume you are writing this as a python question, but tags would be useful here. The code I've supplied takes the first element of the second list you've provided (a list) and the second list you've provided (another list). It then creates a tuple based on the index and compares it to the matching element from the list of tuples. This returns a list of booleans: true if there is an identical tuple, false if there is no identical tuple at that index. The length of the list should be the same as the length of the list of tuples you've provided. If I've interpreted your question correctly, the output is as expected [False, False, False, False] When asking a question like this, it is really useful to specify what you have already tried and why your code produces outputs that you don't expect. Makes it easier for folks to understand the issue and give useful answers! Comment and edit the question to clarify. BEFORE EDITS (Feb. 17) AFTER EDITS (Feb. 18) I'll preserve the above in case people end up having a similar question. Your question has been edited. Let's see if this addresses the question. You want to know the number of times a tuple's elements are ALL contained in a list of lists. This is a perfect application of sets. lists_to_sets = [set(l) for l in X] tuples_to_sets = [set(t) for t in o] Now you want to count the number of times a subset is a member of a superset, so: [sum([t_set.issubset(l_set) for l_set in lists_to_sets]) for t_set in tuples_to_sets] For each of the tuples, …
accepted answer of: http://stackoverflow.com/q/48844489

http://stackoverflow.com/comment/84704831
score: 0
type: AnswerComment
has text: @S.Avenci You can loop over them but you can't access them out of order. But what you describe is easy. If `f` is your score function taking a permutation as its single argument and returning a number you could simply do `min(result, key=f)` to obtain the optimal permutation. One gotcha if you are new to generators: You can only use them once, after that they are used up.
comment on: http://stackoverflow.com/a/48850397
type: Comment

http://stackoverflow.com/q/48877620
upvote count: 1
tagged with: yaml
tagged with: string
favorite count: 0
accepted answer: http://stackoverflow.com/a/48877733
tagged with: python
tagged with: dictionary
has answer: http://stackoverflow.com/a/48877733
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: pyyaml
has title: How to change a KEY in yaml data
type: Question
answer count: 1
has body: I have below yaml file as a template. From another python program I am fetching the name of the device, assume deviceB is the name of the new device. Can someone show how to replace the deviceA with deviceB using python (replace the mapping KEY but not the VALUE)? The place holder for the device is fixed & does not vary. Yaml Data: testbed: name: "boot-ios" devices: deviceA: type: IOS connections: defaults: class: a: protocol: telnet ip: port:
has comment: http://stackoverflow.com/comment/84761519

http://stackoverflow.com/comment/84851633
has text: you probably want to create celery task in Djnago signal `post_save` and you can pass the time to celery task there. Models are loaded after settings.py in django so waht you want is not feasible at all i think.
type: Comment
comment on: http://stackoverflow.com/q/48915146
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84876183
comment on: http://stackoverflow.com/a/48923478
has text: thanks so mucho, it was a syntax problem in my text editor
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84678252
comment on: http://stackoverflow.com/a/48836651
type: AnswerComment
score: 0
type: Comment
has text: **Yes!!** That's amazing. I am super new to Pandas, but it looks like the `Latitude` in `df.Latitude` is not a set method/word in Pandas, but is the literal header in the file, yes? So if I also had, say, states in there under "State", I could do `zip(df.State,df.Latitude,df.Longitude)`, yeah? There's a lot going on in those three lines, I'll have to study, but great post/answer, thanks!

http://stackoverflow.com/comment/84626628
type: QuestionComment
type: Comment
has text: are you running it using Python 2?
comment on: http://stackoverflow.com/q/48811568
score: 2

http://stackoverflow.com/comment/84885206
has text: Can you print out the error and weights at each step? Is the error increasing or decreasing; are the weights getting closer to their expected values?
comment on: http://stackoverflow.com/q/48862451
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84891905
has text: post the complete traceback of the error
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48942624

http://stackoverflow.com/a/48943805
has body: This should work: string = 'J Antimicrob Chemother. 2012 Dec;67(12):2843-7. doi: 10.1093/jac/dks319. Epub 2012 Aug 14' subString = string[string.index(";")+1::] subString = subString[0:subString.index(".")] Let me know how you get on.
answers question: http://stackoverflow.com/q/48943640
has comment: http://stackoverflow.com/comment/84899921
score: 0
type: Answer

http://stackoverflow.com/q/48840810
accepted answer: http://stackoverflow.com/a/48841494
tagged with: django
tagged with: python
type: AnsweredQuestion
has body: I am new at Django and I'm making a demo chat website through Django 2.0. My motive here is to save people's photos when they sign up, and run a face authentication python script on the backend (which I have already done, through the open source face_recognition library on Python) to recognise user's when they login. My script uses cv2 right now to click a photo and sends it over to the face recognition engine. I have to save the photos of the users in a directory on the server-side, with the name of the image as the Name of the user when they sign up, so I can run a face authenticator to for-loop over the list of faces in my folder to find the matching face. And when it finds that, I can return the name to query over my database and create a session for that particular User. (I know it is time taking and resource intensive, but since it is a demo, I think i can get by it. Also kindly suggest if there can be a faster way for face based authentication) My User Model looks like this class User(models.Model): username = models.CharField(max_length=100) name = models.CharField(max_length=100) age = models.CharField(max_length=100) image = models.ImageFile() Can anybody experienced in Django guide me the pathway and required steps through which I can do this?
has answer: http://stackoverflow.com/a/48841494
upvote count: 2
score: 1
downvote count: 1
tagged with: face-recognition
type: Question
tagged with: opencv
tagged with: javascript
answer count: 1
favorite count: 0
has title: Using face as password for chat site
linked to: http://stackoverflow.com/q/20659698

http://stackoverflow.com/comment/84640151
score: 1
comment on: http://stackoverflow.com/q/48817017
type: Comment
type: QuestionComment
has text: How much time is it taking?

http://stackoverflow.com/a/48930769
answers question: http://stackoverflow.com/q/48930451
score: 0
has comment: http://stackoverflow.com/comment/84958554
has body: Looks like your Arduino is sending a blank line after the stop, which your script is not expecting - your script expects that every line will either have 'start', 'stop', or a list element. You can either look into what's happening on the Arduino and fix that, or update your script to ignore empty lines - after the val = ... line, add if len(val) == 0: continue
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84868200
has comment: http://stackoverflow.com/comment/84869396
type: Answer
has comment: http://stackoverflow.com/comment/84894846
has comment: http://stackoverflow.com/comment/84868417
accepted answer of: http://stackoverflow.com/q/48930451

http://stackoverflow.com/a/48879848
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84764465
type: Answer
score: 2
downvote count: 0
has body: If want add only one row is possible use setting with enlargement: df.loc[0.0] = np.nan print (df) a1 idx 0.1 4.0 0.2 6.0 0.3 8.0 0.4 10.0 0.0 NaN
accepted answer of: http://stackoverflow.com/q/48879813
answers question: http://stackoverflow.com/q/48879813

http://stackoverflow.com/a/48921357
answers question: http://stackoverflow.com/q/48919882
score: 0
type: Answer
has body: Do not use list comprehension if you want to print. Use simple for loop. In [12]: A = [(2, 'two', '2nd', 'second')] In [13]: B = ['two'] In [14]: for tup in A: ...: if B[0] in tup: ...: print(tup[0]) If you want final list try list comprehension. You can index tuple. No need to unpack the entire tuple. In [15]: [tup[0] ...: for tup in A ...: if B[0] in tup] Out[15]: [2]

http://stackoverflow.com/q/48826099
tagged with: hex
type: AnsweredQuestion
downvote count: 0
score: 1
type: Question
has body: I have a program, which is returning strings like : b'\\xfe\\xff\\x000\\x008\\x00/\\x001\\x002\\x00/\\x001\\x009\\x009\\x003' How can I convert this to a readable string. The value of this should be 08/12/1993 so imagine i have something like this a = "b'\\xfe\\xff\\x000\\x008\\x00/\\x001\\x002\\x00/\\x001\\x009\\x009\\x003'" print(a.convert())
tagged with: encoding
upvote count: 1
has answer: http://stackoverflow.com/a/48826207
accepted answer: http://stackoverflow.com/a/48826207
answer count: 1
favorite count: 0
has title: how to convert "b'\\xfe\\xff\\x002\\x000\\x001\\x009'" to character in python
tagged with: python

http://stackoverflow.com/a/49098325
type: Answer
upvote count: 0
score: -1
has body: > For non-alphabetical characters (except for digits) Suppose s is your string. from string import punctuation St=(s.strip(punctuation))
answers question: http://stackoverflow.com/q/48846953
downvote count: 1

http://stackoverflow.com/comment/84698957
has text: Do you really want to start multiple processes on your Jupyter server? They may be hard to kill.
type: Comment
comment on: http://stackoverflow.com/q/48846085
score: 0
type: QuestionComment

http://stackoverflow.com/a/48872354
has comment: http://stackoverflow.com/comment/84749962
score: 0
has comment: http://stackoverflow.com/comment/84748697
has comment: http://stackoverflow.com/comment/84748903
type: Answer
has body: your first if conditional needs to be more specific: if hours &gt; base_hours and hours &lt; 60: Otherwise, as long as hours are above base hours, then the first conditional will be met at 1.5 times the rate Full code below: base_hours = 40 xtra_hours = 60 over_time = 1.5 xover_time = 2.0 hours = float(input('Enter the amount of hours worked: ')) pay_rate = float(input('Enter the hourly pay rate: ')) if (hours &gt; base_hours) and (hours &lt; 60): overtime_hours = hours - base_hours overtime_pay = overtime_hours * pay_rate * over_time gross_pay = base_hours * pay_rate + overtime_pay elif hours &gt; 60: overtime_hours = hours - base_hours overtime_pay = overtime_hours * pay_rate * xover_time gross_pay = base_hours * pay_rate * overtime_pay else: gross_pay = hours * pay_rate print 'The gross pay is', gross_pay
answers question: http://stackoverflow.com/q/48872296

http://stackoverflow.com/comment/84919513
type: AnswerComment
comment on: http://stackoverflow.com/a/48941918
type: Comment
has text: @Aphid I tried measuring the time between navigating to the page and when the last element loads. It get pretty good approximation of real loading time when doing this from browser console. For some reason when running same js commands from Selenium (with caching disabled) I am getting ridiculously fast loading times (10-20 times faster than what I witness when visiting website myself).
score: 0

http://stackoverflow.com/comment/84844818
has text: Okay. It seems that output_dict['detection_boxes'] contains all the overlapping boxes, and that's why there are so many arrays.Thank you!
type: Comment
comment on: http://stackoverflow.com/a/48915493
score: 2
type: AnswerComment

buttonclick
type: Tag
tags question: http://stackoverflow.com/q/48827148
tag name: buttonclick

http://stackoverflow.com/comment/84929691
score: 1
comment on: http://stackoverflow.com/a/48866484
type: AnswerComment
has text: @AntonvBR - Not sure if possible boost it. In my opinion `regex` solution should failed, because too many values.
type: Comment

http://stackoverflow.com/comment/84870817
has text: python tutorial please
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48932007

http://stackoverflow.com/comment/84873199
comment on: http://stackoverflow.com/a/48932435
score: 0
has text: @DannM check this answer: https://stackoverflow.com/a/15322459/641249 you need to check if files exist.
type: Comment
type: AnswerComment

http://stackoverflow.com/a/48941152
upvote count: 1
score: 1
answers question: http://stackoverflow.com/q/48940588
type: AcceptedAnswer
downvote count: 0
has body: Split the directory from your file name and then give your out a new directory : for excel in excel_files: folder = r'C:\ASeparateFolder\' out = folder + excel.split('\\')[-1].split('.')[0]+'.csv' df = pd.read_excel(excel, 'ResourceProDailyDataset') # if the sheet name is always the same. df.to_csv(out) Note I used '\\' to split, it seems to be the common splitting point for glob whether you use '\' or '/' for your initial excel_file directory.
type: Answer
accepted answer of: http://stackoverflow.com/q/48940588
has comment: http://stackoverflow.com/comment/84889931

http://stackoverflow.com/comment/84631585
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48813906
has text: @pault do you want me reopen ?
score: 0

http://stackoverflow.com/q/48872581
score: 5
upvote count: 6
has title: Empty dict as default value of dict.get()
answer count: 1
downvote count: 1
has comment: http://stackoverflow.com/comment/135982200
tagged with: default
favorite count: 0
accepted answer: http://stackoverflow.com/a/48872630
linked to: http://stackoverflow.com/q/5772148
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
has body: I am attempting to pass an empty dictionary as the default return value of a call to .get()on another dictionary. queryStringParameters = event.get('queryStringParameters', ({}) size = queryStringParameters.get('size', 25) However, queryStringParameters.get(...) throws an error saying that queryStringParameters is None. 'NoneType' object has no attribute 'get': AttributeError Traceback (most recent call last): File "/var/task/api/game.py", line 13, in all size = queryStringParameters.get('size', 25) AttributeError: 'NoneType' object has no attribute 'get' Is this not possible, or am I doing something wrong? I have tried the following as well: queryStringParameters = event.get('queryStringParameters', dict())
has answer: http://stackoverflow.com/a/48872630
has comment: http://stackoverflow.com/comment/84749264
type: Question

http://stackoverflow.com/a/48892861
has comment: http://stackoverflow.com/comment/84794807
has comment: http://stackoverflow.com/comment/85165299
answers question: http://stackoverflow.com/q/48891277
has comment: http://stackoverflow.com/comment/84794369
has comment: http://stackoverflow.com/comment/84794707
has body: It could be that you scaled your dynos to zero, try the following command to set dynos to one heroku ps:scale web=1 you can find more info here https://devcenter.heroku.com/articles/error-codes
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84794719

http://stackoverflow.com/a/48820848
has comment: http://stackoverflow.com/comment/84645412
answers question: http://stackoverflow.com/q/48820586
has comment: http://stackoverflow.com/comment/84645694
score: 4
has body: You are looking at the docs for 1.X while using 2.X. Unfortunately the search engine ranking is higher for the 1.X documentation. In networkx 2.X isolates is a generator object. The current stable docs will add list() to the example code. https://networkx.github.io/documentation/stable/reference/algorithms/generated/networkx.algorithms.isolate.isolates.html In [107]: nx.isolates(G) Out[107]: &lt;generator object isolates.&lt;locals&gt;.&lt;genexpr&gt; at 0x7fa499cd8e60&gt; The migration guide may help out if you are expecting 1.X behavior too. https://networkx.github.io/documentation/stable/release/migration_guide_from_1.x_to_2.0.html
upvote count: 4
downvote count: 0
type: Answer

http://stackoverflow.com/q/48816636
answer count: 3
tagged with: calculator
has title: Subtracting more than 2 numbers in Python
has comment: http://stackoverflow.com/comment/84637518
tagged with: python
has answer: http://stackoverflow.com/a/62817869
has answer: http://stackoverflow.com/a/48816675
accepted answer: http://stackoverflow.com/a/48816675
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/62817869
has answer: http://stackoverflow.com/a/74589540
type: Question
has comment: http://stackoverflow.com/comment/84637277
has body: I am little bit new to the programming. I am learning Python, version 3.6. print("1.+ \n2.-\n3.*\n4./") choice = int(input()) if choice == 1: sum = 0 print("How many numbers you want to sum?") numb = int(input()) for i in range(numb): a = int(input(str(i+1)+". number ")) sum+=a print("Result : "+str(sum)) For improving myself i am trying to build a calculator but first i am asking how many numbers user want to calculate. You can see this in code above, but when it is comes to subtracting or dividing or multiplying i have no idea what to do. My reason to do it like this i want to do the calculator like in real time calculators.
score: 0

http://stackoverflow.com/q/48945112
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/85138879
accepted answer: http://stackoverflow.com/a/48945134
score: -1
has body: So I want to delete the first and third column of this text file my text file Looks like this: 1 2 3 4 5 6 And I want to delete the first column and third column with python. My Code Looks like this: f = open("5.txt", "r") g = open("datafile_fixed.txt", "w") for line in f: if line.strip(): g.write("\t".join(line.split()[1:]) + "\n") f.close() g.close() but I can only delete the first column. How do I delete the first and third?
has title: how to delete the first and third column from a text file in python
has answer: http://stackoverflow.com/a/48945134
answer count: 1
favorite count: 0
tagged with: python
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/85013347
downvote count: 2

http://stackoverflow.com/comment/84690026
type: AnswerComment
has text: How would I do it?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48842615

http://stackoverflow.com/a/53310579
has body: Below is a recursive and equivalent iterative solution. The stack saves the order of the calls and their state. In this case there is one state on the stack. #recursive solution def tower(numRings): def tower1(numRings,fromPeg,toPeg,usePeg): if numRings &gt; 0: #A tower1(numRings-1,fromPeg,usePeg,toPeg) #B result.append((fromPeg,toPeg)) #C tower1(numRings-1,usePeg,toPeg,fromPeg) #D result = [] tower1(numRings,0,1,2) return result #iterative solution def tower(numRings): result = [] stk = [] def tower1(numRings): In, To = 0, 1 stk.append((In,numRings,0,1,2)) while stk: state,numRings,fromPeg,toPeg,usePeg = stk.pop() if state == In: if numRings != 0: #push down to 1 numRing #A stk.append((To,numRings,fromPeg,toPeg,usePeg)) #B save state stk.append((In,numRings-1,fromPeg,usePeg,toPeg)) elif state == To: result.append((fromPeg,toPeg)) #C stk.append((In,numRings-1,usePeg,toPeg,fromPeg)) #D else: print 'Error: logic' return result tower1(numRings) return result a = [1,2,3,4] for n in a: print 'rings',n print tower(n)
answers question: http://stackoverflow.com/q/48913319
score: 0
type: Answer

http://stackoverflow.com/q/48883329
favorite count: 0
has comment: http://stackoverflow.com/comment/84771276
has comment: http://stackoverflow.com/comment/84770883
has comment: http://stackoverflow.com/comment/84771090
has comment: http://stackoverflow.com/comment/84777047
score: 0
has comment: http://stackoverflow.com/comment/84771301
has title: Encoding two numbers in a 4-bit binary string
has comment: http://stackoverflow.com/comment/84772575
has comment: http://stackoverflow.com/comment/84771932
tagged with: python
has comment: http://stackoverflow.com/comment/84778696
has comment: http://stackoverflow.com/comment/84771106
has comment: http://stackoverflow.com/comment/84772283
has comment: http://stackoverflow.com/comment/84773171
has comment: http://stackoverflow.com/comment/84776218
has answer: http://stackoverflow.com/a/48884100
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84771309
upvote count: 1
downvote count: 1
type: Question
has body: For example, I have two numbers ranging from 0 to 15. And I wonder if there is any way to encode these two numbers in just 4-bit binary string (or possibly 5-bit)? It is known that 4 bits are needed to represent any single number from 0 to 15, but maybe you could think of your own operation on binary strings, and then recover the input numbers back from the result. For example, if I add 0010 + 1011 as standard, I get1101. But with the result of adding it is impossible to predict the components of the sum completely and unambiguously. Cases would have to be considered. But maybe some other own defined action? Was anyone wondering about something like that? I know that the above question may not meet some portal conditions, but treat this question purely abstractly :)
has comment: http://stackoverflow.com/comment/84771155
tagged with: algorithm
tagged with: operation
answer count: 2
has answer: http://stackoverflow.com/a/48886815
has comment: http://stackoverflow.com/comment/84771795
has comment: http://stackoverflow.com/comment/84788863
has comment: http://stackoverflow.com/comment/84773502
has comment: http://stackoverflow.com/comment/84771376

http://stackoverflow.com/comment/84858007
type: Comment
score: 0
type: AnswerComment
has text: @pylearner - Because if remove it, get a bit different output.
comment on: http://stackoverflow.com/a/48922383

http://stackoverflow.com/q/48959731
type: Question
has title: numpy indexing operations for 3D matrix
tagged with: numpy
score: 0
answer count: 1
has answer: http://stackoverflow.com/a/48960388
accepted answer: http://stackoverflow.com/a/48960388
has body: Is there an elegant/quick way to reproduce this without the for loops? I'm looking to have a 3D matrix of values, and and 2D matrix that gives the indices for which to copy the 3rd dimensions' values while creating a new 3D matrix of the same shape. Here is an implementation with a lot of loops. np.random.seed(0) x = np.random.randint(5, size=(2, 3, 4)) y = np.random.randint(x.shape[1], size=(3, 4)) z = np.zeros((2, 3, 4)) for i in range(x.shape[0]): for j in range(x.shape[1]): z[i, j, :] = x[i, y[i, j], :]
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/q/48916154
has comment: http://stackoverflow.com/comment/84839059
has comment: http://stackoverflow.com/comment/84840475
has body: I have a for loop running that creates a new list of select Unix times from elements of another list containing multiple Unix times, the index of those elements is in turn given by another list. My problem is that within this for loop the append function is not working and I have no idea why as I get no errors. The print function is simply ignored after the for loop. I'm not sure what I'm doing wrong. Could someone help me out? Here is my code: adjusted_exc_pass_numbers = [0, 6, 9, 16, 19, 22, 25, 32, 35, 41, 48] processed_start_times = [1519275660, 1519287600, 1519325040, 1519336920, 1519360080, 1519365900, 1519371900, 1519409400, 1519415340, 1519421280, 1519450260, 1519456200, 1519499700, 1519534680, 1519540560, 1519546620, 1519584060, 1519596000, 1519619160, 1519624920, 1519630920, 1519668420, 1519674360, 1519680360, 1519709340, 1519715220, 1519758720, 1519793760, 1519799580, 1519805700, 1519843080, 1519855020, 1519878180, 1519884000, 1519890000, 1519927500, 1519939380, 1519968360, 1519974300, 1520017800, 1520052780, 1520058660, 1520064720, 1520102160] ppst = [] for element in range(len(adjusted_exc_pass_numbers)): ppst.append(processed_start_times[int(adjusted_exc_pass_numbers[element])]) print(ppst) When I run this, print is ignored and the rest of the code executes as if the statement was not there. I don't understand why it is not appending or printing. Thank you for your time.
tagged with: python
has comment: http://stackoverflow.com/comment/84839882
has comment: http://stackoverflow.com/comment/84840503
has comment: http://stackoverflow.com/comment/84840093
tagged with: append
has answer: http://stackoverflow.com/a/48916230
type: AnsweredQuestion
tagged with: list
has comment: http://stackoverflow.com/comment/84838773
has comment: http://stackoverflow.com/comment/84839033
accepted answer: http://stackoverflow.com/a/48916230
has comment: http://stackoverflow.com/comment/84838777
has comment: http://stackoverflow.com/comment/84840086
downvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84838812
score: -1
has comment: http://stackoverflow.com/comment/84840320
has title: append function not working in for loop Python 3
tagged with: for-loop
has comment: http://stackoverflow.com/comment/84839724
upvote count: 0
answer count: 1
has comment: http://stackoverflow.com/comment/84839742
favorite count: 0
tagged with: python-3.x

http://stackoverflow.com/comment/84811021
has text: Thank you for your answer! I tried using aiohttp and the speed gains have blown me away. Although I knew this was a problem beforehand, it's unbelievable how much time my app was taking up just by sitting around.
comment on: http://stackoverflow.com/a/48900261
score: 1
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/84631570
type: Comment
type: QuestionComment
score: 2
has text: Please copy-paste the entire error message, including any backtrace.
comment on: http://stackoverflow.com/q/48813922

http://stackoverflow.com/q/48899303
type: Question
tagged with: implementation
has body: I built a machine learning model of binary classification in python. It works on my laptop (e.g. command line tool). Now I want to deploy it in production on a separate server in my company. It has to take inputs from another server (C# application), make some calculations and return outputs back to it. My question is what are the best practices of doing such thing in production? As I know it can be done through TCP/IP connection. I am new in this field and I don't know the terms used here. So can anybody guide me? Thanks.
has title: Model implementation in production with python
score: 0
answer count: 1
type: UnansweredQuestion
tagged with: python
linked to: http://stackoverflow.com/q/645312
tagged with: tcp
tagged with: machine-learning
has answer: http://stackoverflow.com/a/48899515

http://stackoverflow.com/q/48808568
favorite count: 0
has body: how generate and print the qr code with the data above the button after pressing "Print qr code"?
type: UnansweredQuestion
tagged with: django
tagged with: python
has answer: http://stackoverflow.com/a/48809003
score: 1
type: Question
upvote count: 2
tagged with: django-admin
has title: QR code generate django-admin
answer count: 1
downvote count: 1

http://stackoverflow.com/q/48906386
has answer: http://stackoverflow.com/a/48906753
has title: Splitting a single column in python into multiple separate columns
tagged with: dataframe
tagged with: pandas
answer count: 1
has comment: http://stackoverflow.com/comment/84818642
linked to: http://stackoverflow.com/q/39943147
has comment: http://stackoverflow.com/comment/84850378
type: UnansweredQuestion
tagged with: python
score: 0
has comment: http://stackoverflow.com/comment/84818559
has comment: http://stackoverflow.com/comment/84818526
has body: There is a similar question than mine but the requirement was to do it in the "R" language. My knowledge of R is still in kindergarten stage and I cannot translate the answer from R to Python. So here goes. I have a data frame with two columns - IAGSTNO and Quals: IAGSTNO QUALS 215299035 204212 BC:0 OT:VF #Subj:10 ||DI0430 BC:0 OT:VF #Subj:0 216034361 208086 BC:1 OT:VF #Subj:2 ||DI0800 BC:1 OT:VF #Subj:5 216138396 208382 BC:1 OT:VF #Subj:2 ||208082 BC:1 OT:WI #Subj:1 216139376 208383 BC:1 OT:VF #Subj:0 ||208388 BC:1 OT:VF #Subj:4 216149959 204179 BC:0 OT:HP #Subj:0 ||DI0420 BC:0 OT:HP #Subj:7 217028330 DI0800 BC:1 OT:HF #Subj:0 ||DI0824 BC:1 OT:HF #Subj:4 ||DI0825 BC:1 OT:HF #Subj:3 This was specifically extracted in this format to make it easier for the human audience it was intended for. The data frame is about students that are registered for more than one qualification. The QUALS column contains a maximum of three qualification groupings and the format is like this: qual_code BC:1 OT:VF #Subj:3 || where qual_code is the code of the qualification BC:1 is an indication of the semester OT:VF an indication if the student is full time/part time hash (#)Subj:3 indicates the number of subjects the student is registered for the qualification. The double pipe symbol '||' is the separator for the three groups of qualification I want to do the following: I want to create a new data frame with the IAGSTNO and three more columns (Qual_1, Qual_2 and Qual_3) with the string representing the three qualification attributes - the full set of data with the STNO must be in this df I then want to create a third data frame to split the three individual Qual columns into its respective attribute columns - the full set of data with the IAGSTNO must be in this df. Even only a pointer will be very helpful. Thanks in advance, Phlip The expected outcome: Dataframe2 should look like: Stno Qual 1 Qual 2 Qual 3 217028330 DI0800 BC:1 OT: HF #Subj: 0 DI0824 BC:1 OT: HF #Subj: 2 DI0825 BC:1 OT: …
type: Question

http://stackoverflow.com/q/48821347
has comment: http://stackoverflow.com/comment/84647243
possible better answer: http://stackoverflow.com/a/48822594
type: Question
has body: I am trying to scrape data on car model, price, mileage, location, etc using beautifulsoup. However, the return result only reports data on one random car. I want to be able to collect data on all cars advertised on the site to date. My python code is below. How can I modify my code to retrieve data such that each day I have information on car model, price, mileage, location, etc? Example: Car model price mileage location date Toyota Corrola $4500 22km Accra 16/02/2018 Nissan Almera $9500 60km Tema 16/02/2018 etc import requests from bs4 import BeautifulSoup import pandas import csv from datetime import datetime for i in range(300): url = "https://tonaton.com/en/ads/ghana/cars?".format(i) r = requests.get(url) soup = BeautifulSoup(r.content, "html.parser") print soup.prettify() data = soup.find(class_='item-content') for tag in data: item_title = data.find("a",attrs={"class":"item-title h4"}) model = item_title.text.encode('utf-8').strip() item_meta = data.find("p",attrs={"class":"item-meta"}) mileage = item_meta.text.encode('utf-8').strip() item_location = data.find("p",attrs={"class":"item-location"}) location = item_location.text.encode('utf-8').strip() item_info = data.find("p",attrs={"class":"item-info"}) price = item_info.text.encode('utf-8').strip() with open('example.csv', 'a') as csv_file: writer = csv.writer(csv_file) writer.writerow([model, price, mileage, location, datetime.now()])
tagged with: python
has comment: http://stackoverflow.com/comment/84646185
has title: how to loop using beautifulsoup
has comment: http://stackoverflow.com/comment/84646561
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84646399
linked to: http://stackoverflow.com/q/32814578
has answer: http://stackoverflow.com/a/48822131
has comment: http://stackoverflow.com/comment/84647031
has comment: http://stackoverflow.com/comment/84680500
has answer: http://stackoverflow.com/a/48822594
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84647786
accepted answer: http://stackoverflow.com/a/48822131

http://stackoverflow.com/comment/84877140
has text: that's looks great !
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48933977
type: Comment

http://stackoverflow.com/comment/84858055
has text: Please first show the complete use case you want in detail. Current code you have shown dont show what you want to do.
type: Comment
comment on: http://stackoverflow.com/q/48925311
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84715324
comment on: http://stackoverflow.com/q/48845663
score: 0
type: QuestionComment
type: Comment
has text: @Paul So if I’m understanding that correctly, I would need to store ```ndvi_array != -9999``` as a variable and type that, as well as ```field_array = field_id```?

http://stackoverflow.com/q/48831346
type: UnansweredQuestion
tagged with: python
has body: I have 2 books in txt format (6000+ lines). I would like to associate, using Python, to each word its relevance (using td idf algorithm) and order them in descending order. I tried this code #- * -coding: utf - 8 - * - from __future__ import division, unicode_literals import math from textblob import TextBlob as tb def tf(word, blob): return blob.words.count(word) / len(blob.words) def n_containing(word, bloblist): return sum(1 for blob in bloblist if word in blob) def idf(word, bloblist): return math.log(len(bloblist) / (1 + n_containing(word, bloblist))) def tfidf(word, blob, bloblist): return tf(word, blob) * idf(word, bloblist) document1 = tb("" "FULL BOOK1 TEST" "") document2 = tb("" "FULL BOOK2 TEST" "") bloblist = [document1, document2] for i, blob in enumerate(bloblist): with open("result.txt", 'w') as textfile: print("Top words in document {}".format(i + 1)) scores = { word: tfidf(word, blob, bloblist) for word in blob.words } sorted_words = sorted(scores.items(), key = lambda x: x[1], reverse = True) for word, score in sorted_words: textfile.write("Word: {}, TF-IDF: {}".format(word, round(score, 5)) + "\n") that I found here https://stevenloria.com/tf-idf/ with some changes, but it takes a lot of time and after some minutes, it crashes saying TypeError: coercing to Unicode: need string or buffer, float found. Why? I also tried to call this Java program through python https://github.com/mccurdyc/tf-idf/. The program works, but the output is incorrect: there are a lot of words that should have a high relevance level that are instead categorized with 0 relevance. Is there a way to fix that Python code? Or, can you suggest me another tf-idf implementation that does correctly what I want?
answer count: 0
downvote count: 0
score: 1
tagged with: java
type: Question
has title: Tf Idf over a set of documents to find words relevance
tagged with: tfidfvectorizer
upvote count: 1
tagged with: words
favorite count: 0
tagged with: tf-idf

http://stackoverflow.com/comment/84686803
score: 0
type: Comment
type: QuestionComment
has text: `eval` is a to use , no for avoiding! it has proplems but when need must use it ,
comment on: http://stackoverflow.com/q/48838289

http://stackoverflow.com/a/55842578
downvote count: 0
type: Answer
has comment: http://stackoverflow.com/comment/125688336
has body: This has changed now that I created colabctl. You can use colabctl to run your Google Colaboratory notebooks from the CLI, on a schedule if you wish. Simply add colabctl.py to a cron job. Note: If you want to run it on a headless server, you will first need to run it once from your desktop to save your login cookie to the pickle file and then upload that pickle to your server along with colabctl.
score: 10
upvote count: 10
answers question: http://stackoverflow.com/q/48940197

http://stackoverflow.com/q/48806594
has comment: http://stackoverflow.com/comment/84621896
has answer: http://stackoverflow.com/a/48861511
type: Question
answer count: 2
has title: Maya python launch
has body: so I am trying to launch Maya using Python 2.7 as subprocess. My goal for now is to fire it up and hand over some variables. Launching is working, but it does throw errors I do not have when launching via a bat file. The process is currently Windows 10 only and I am using Maya 2018 latest update. Seems like PyQT is not getting loaded this way: Autodesk/Maya2018/scripts/startup/initMainWindow.mel line 178: ImportError: file ######\Maya2018\Python\lib\site-packages\maya\app\general\mayaMixin.py line 35: DLL load failed: The specified module could not be found., No module named PyQt4.QtCore // I tried launching using os.system as well as subprocess.Popen both resulting in the same error. My current launch command is a simple call to the exe with no additional parameters. Do I maybe have to source PyQt myself if run via python call? command used is: subprocess.Popen([r"C:/Program Files/Autodesk/Maya2018/bin/maya.exe"]) Thanks Thomas
score: 0
tagged with: pyqt
has comment: http://stackoverflow.com/comment/84633098
has answer: http://stackoverflow.com/a/48823759
tagged with: maya
accepted answer: http://stackoverflow.com/a/48861511
possible better answer: http://stackoverflow.com/a/48823759
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/a/65430306
downvote count: 0
type: Answer
has body: In this case, operator 'in' calls the __contains__() of python´s built-in list object which then calls the __eq__() of your object, so make sure that the __eq__() dunder method in your obj-class is properly implemented.
score: 5
accepted answer of: http://stackoverflow.com/q/48856989
upvote count: 5
answers question: http://stackoverflow.com/q/48856989
type: AcceptedAnswer

http://stackoverflow.com/q/48819238
has comment: http://stackoverflow.com/comment/84642572
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84643117
has comment: http://stackoverflow.com/comment/84643373
has title: Having trouble successfully unit testing my Python program: No such file or directory....0 of 1 tests passed
tagged with: python
has comment: http://stackoverflow.com/comment/84642617
tagged with: unit-testing
has body: I forked a repository from Github that contains a data engineering project. From the repository, I have created a Python script that works as it's supposed to on my local machine. Basically, the program is supposed to read in an input .txt file, perform some clean-up and calculations on the file, and return an output .txt file. The repository also has the code written to test the program. However, I'm still in the process of learning how to correctly compile and execute my code, and I'm running into problems with the unit testing. From the command line, I run the file './test_run.sh' and the test shows that my program is correctly reading in my input file AND it is successfully creating a test directory for my output, including an "output" directory. The problem is that the program is supposed to create an output file 'data_output.txt" inside the output directory, but this is not happening. Here is the error message I'm getting: $ ./test_run.sh diff: ./test_output/output/data_output.txt: No such file or directory [FAIL]: test_1 diff: ./test_output/output/data_output.txt: No such file or directory [Thu Feb 15 20:56:11 EST 2018] 0 of 1 tests passed What would I need to change so that my program creates the data_output.txt file and writes my program output to this file?
type: Question
has comment: http://stackoverflow.com/comment/84642484
tagged with: compilation
score: 0
has comment: http://stackoverflow.com/comment/84642604

http://stackoverflow.com/q/48928672
downvote count: 0
has title: Selenium Python 2.7: how to fill in the gaps?
has body: everyone! I'm new to coding and I'm trying to write a webcrawler using Selenium with Python 2.7. I'm still on an early stage, however I've been having problems filling in the gaps of the website. It's https://comtrade.un.org/data/ from the UN. I've already tried inspecting the webpage elements and using different methods (find_element_by_id, find_element_by_class, find_element_by_name, send_keys, etc.), but none seems to work. Here's my code thus far: import selenium.webdriver.support.ui as ui from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC HEADER = 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36' BASE_URL = 'https://comtrade.un.org/data/' def initialize_webdriver(): profile = webdriver.Chrome() profile.set_preference("general.useragent.override", HEADER) driver = webdriver.Chrome(profile) # driver.implicitly_wait(30) driver.set_window_size(1180, 980) return driver def main(): # driver = initialize_webdriver() driver = webdriver.Chrome() driver.get(BASE_URL) for period in driver.find_element_by_class('s2id_periods'): period.clear() period.send_keys('2013') Can anyone help me out? Thanks in advance!
favorite count: 0
has comment: http://stackoverflow.com/comment/84867947
type: UnansweredQuestion
tagged with: python
answer count: 0
score: 1
tagged with: selenium
upvote count: 1
type: Question
has comment: http://stackoverflow.com/comment/84865113

http://stackoverflow.com/comment/84778772
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48872896
has text: its not multiplication, but rather a coordinate, for example a[1][3] is the value for (1,3) in the array.
type: AnswerComment

http://stackoverflow.com/a/48858655
accepted answer of: http://stackoverflow.com/q/48856372
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: You don't need to switch to the modal dialog, you can access it just like you would any other HTML on the page. You can simplify your code to browser.get('https://www.google.com/maps/place/%s?hl=en'%(code)) browser.find_element_by_xpath("//button/div[.='SHARE']").click() url = browser.find_element_by_id("last-focusable-in-modal").text print(url) But... if you read the dialog, you will see that it states You can also copy the link from your browser's address bar. so the URL you are navigating to in the first line is what you are going to copy from the Share link so there's really no point. You already have the URL.
downvote count: 0
answers question: http://stackoverflow.com/q/48856372
score: 1

http://stackoverflow.com/q/48844009
possible better answer: http://stackoverflow.com/a/48844075
accepted answer: http://stackoverflow.com/a/48844073
has answer: http://stackoverflow.com/a/48844075
has comment: http://stackoverflow.com/comment/84692359
has body: I'm a little bit confused about the behavior of the bitwise xor operator. Why, if xor is possible only with binary data, am I able to use xor with decimal numbers? For example: fs='a' sn='k' ord(fs) ^ ord(sn) ord(fs) gives me an ASCII code that is not binary.
type: Question
answer count: 2
score: 0
has answer: http://stackoverflow.com/a/48844073
tagged with: python-3.x
tagged with: python
tagged with: bitwise-xor
type: AnsweredQuestion
has title: Python xor binary data with decimal value

http://stackoverflow.com/q/48899041
tagged with: pandas
answer count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84803512
tagged with: regex
has comment: http://stackoverflow.com/comment/84803908
upvote count: 2
has title: Separate letters and digits using regex with pandas
has body: I have a column called 'value' from a pandas dataframe, df, that has a mixture of numbers and words. It looks something like this: VALUE 0 done 1 Yes 2 3.45 3 2bc I want to split the column up to 2 columns where the left one only has letters and the right one only numbers. Ideally, the result should be: 0 1 0 done NaN 1 Yes NaN 2 NaN 3.45 3 bc 2 I tried using the .str.extract pandas function like so: df['value'].str.extract('([A-Za-z]+)?([0-9]*[.]?[0-9]+)') The result I get is similar to the following: 0 1 0 NaN NaN 1 NaN NaN 2 NaN 3.45 3 NaN NaN where the words do not show up in column 0 as they should. Does anyone know the reason why or a better way to do such an operation in pandas/python?
score: 2
type: AnsweredQuestion
type: Question
downvote count: 0
has answer: http://stackoverflow.com/a/48899124
accepted answer: http://stackoverflow.com/a/48899124
tagged with: string
favorite count: 0

http://stackoverflow.com/q/48866770
type: AnsweredQuestion
downvote count: 0
score: 1
tagged with: matplotlib
type: Question
has title: show deviation using a line between two points using matplotlib
upvote count: 1
answer count: 1
favorite count: 0
has body: There are say 4 points ( xy coordinates ) in my dataset coordinates = [[1,2], [10,11], [3,4], [14,15]] Now, plotting them is easy using matplotlib. But I would like to show them as a deviation between the first and the second point. It should look like this 1,2 --- 10,11 3,4 --- 14,15 The --- is a dotted line. fig2 = plt.figure() shapeplot1 = fig2.add_subplot(111) coordinates = [[1,2], [10,11], [3,4], [14,15]] data = np.array(coordinates) x1, y1 = data.T shapeplot1.scatter(x1,y1, color='red') plt.show()
has answer: http://stackoverflow.com/a/48866996
accepted answer: http://stackoverflow.com/a/48866996
tagged with: python

http://stackoverflow.com/comment/84833157
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48913382
has text: This has nothing to do with pandas. Jus try to change the test append to the following: `test.append(os.path.join(i,ii))`
score: 0

http://stackoverflow.com/comment/84653246
type: AnswerComment
has text: Thanks for the clarification, Just confused when `a+=1` worked at `if` part. But actually worked because of parsing as you explained.
comment on: http://stackoverflow.com/a/48824680
type: Comment
score: 0

http://stackoverflow.com/comment/84922611
type: AnswerComment
has text: iterate over columns, select only able to convert to int, apply on df
type: Comment
comment on: http://stackoverflow.com/a/48957782
score: 1

http://stackoverflow.com/a/48847664
accepted answer of: http://stackoverflow.com/q/48847533
score: 0
type: AcceptedAnswer
has body: As @georg suggested, you should use *args to specify a function can take a variable number of unnamed arguments. args feeds the function as a tuple. As an iterable, this can be accepted directly by Python's built-in sum. For example: def sum_it_up(*args): print('The total is {0}'.format(sum(args))) sum_it_up(1,4,7,10) # The total is 22 sum_it_up(1,2,0,0) # The total is 3
type: Answer
answers question: http://stackoverflow.com/q/48847533

http://stackoverflow.com/a/48919495
has comment: http://stackoverflow.com/comment/84886494
has comment: http://stackoverflow.com/comment/84845599
accepted answer of: http://stackoverflow.com/q/48919331
score: 4
upvote count: 4
type: AcceptedAnswer
downvote count: 0
has body: If you want sentence tokenization, nltk is probably the quickest way to do so. http://www.nltk.org/api/nltk.tokenize.html#module-nltk.tokenize.punkt Will get you pretty far. i.e. code from docs &gt;&gt;&gt; import nltk.data &gt;&gt;&gt; text = ''' ... Punkt knows that the periods in Mr. Smith and Johann S. Bach ... do not mark sentence boundaries. And sometimes sentences ... can start with non-capitalized words. i is a good variable ... name. ... ''' &gt;&gt;&gt; sent_detector = nltk.data.load('tokenizers/punkt/english.pickle') &gt;&gt;&gt; print('\n-----\n'.join(sent_detector.tokenize(text.strip()))) Punkt knows that the periods in Mr. Smith and Johann S. Bach do not mark sentence boundaries. ----- And sometimes sentences can start with non-capitalized words. ----- i is a good variable name.
has comment: http://stackoverflow.com/comment/84846713
has comment: http://stackoverflow.com/comment/84890528
has comment: http://stackoverflow.com/comment/84890337
answers question: http://stackoverflow.com/q/48919331
type: Answer
has comment: http://stackoverflow.com/comment/84859264
has comment: http://stackoverflow.com/comment/84858946

http://stackoverflow.com/q/48851342
type: Question
type: AnsweredQuestion
tagged with: python
favorite count: 0
score: -1
has body: I have a polar axis plot that looks like this: I want 190 degrees to be at the top part of the plot, instead of 180, what can I do to change the plot? In my script, the relevant segment reads: ax.set_theta_zero_location("S") ax.set_theta_direction(-1) This allows me to get a plot facing south, and also having the ticks (degrees) set out in the opposite direction. I now want to slightly refine my plot, by turning the plot a little bit, so that 190 degrees is the top part of the plot. How can I do that? I've tried to add this line: ax.set_theta_offset(-np.pi/18) and when that did not work, I tried to add: ax.set_theta_offset(-10) But either of these two lines seem to shift the plot a lot, rather than the 10 degrees I am trying to get. Any thoughts on this?
accepted answer: http://stackoverflow.com/a/48851476
has title: Defining the offset of polar axis plot
answer count: 1
downvote count: 1
tagged with: matplotlib
upvote count: 0
has answer: http://stackoverflow.com/a/48851476

http://stackoverflow.com/a/48846964
has body: You may use re.sub with \[WIKI_LINK:[^][]*@([^]]+)] See the regex demo Details \[WIKI_LINK: - a literal substring [WIKI_LINK: [^][]* - any 0+ chars othert than [ and ] @ - a @ char ([^]]+) - Group 1 (referred to with \1 backreference from the replacement pattern): any 1+ chars other than ] ] - a literal ] char. See the Python demo: import re text = 'Text [WIKI_LINK: Example@Whatever] text [WIKI_LINK: Example@Whatever]' p_wiki_link = re.compile(r'\[WIKI_LINK:[^][]*@([^]]+)]') print(p_wiki_link.sub(r'\1', text)) # =&gt; Text Whatever text Whatever
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48846950
has comment: http://stackoverflow.com/comment/84698074
answers question: http://stackoverflow.com/q/48846950
score: 3
has comment: http://stackoverflow.com/comment/84700811
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84704915
upvote count: 3
type: Answer

http://stackoverflow.com/q/48884058
has body: I'm performing the following query in my Django project: for obj in Path.objects.filter(Q(server_name__exact=name), Q(keywords__overlap=all_words)): The field keywords is an ArrayField and I'm using the overlap filter which is equivalent to something like following in python: keywords.intersection(all_words) # if keywords is a set Now the problem is that when all_words is a small list, less than 10, it does the job very fast but when all_words is a larger array, more than 20-30, it takes so much time. Is there any way around this? I tested other ways like the following but it's didn't make any different. for obj in Path.objects.filter(server_name=name): if all_words.intersection(obj.keywords):
tagged with: django-models
has title: PostgreSQL ArrayField is too slow in Django
downvote count: 0
favorite count: 0
tagged with: postgresql
tagged with: query-optimization
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84778590
has comment: http://stackoverflow.com/comment/84783485
tagged with: django
tagged with: python
score: 3
answer count: 0
upvote count: 3
type: Question

http://stackoverflow.com/a/48913242
accepted answer of: http://stackoverflow.com/q/48912989
type: Answer
has body: Using replace form dataframe df.replace({',':''},regex=True) Out[1280]: 0 1 2 3 4 5 6 7 8 9 0 4 x x1 x2 x3 x4 x5 x6 x7 x8 1 6 y y1 y2 y3 y4 y5 y6 y7 NaN 2 9 z z1 z2 NaN NaN NaN NaN NaN NaN
type: AcceptedAnswer
score: 0
answers question: http://stackoverflow.com/q/48912989

http://stackoverflow.com/comment/84744174
has text: @KaramJaber, you need to disable 2-factor authentication for logging in and getting cookies. After that, you can enable it.
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48870021

http://stackoverflow.com/comment/91931679
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48827395
type: Comment
has text: In the above example how do i add a header for the key too?

http://stackoverflow.com/q/48843237
type: UnansweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84690880
has title: Python string to unicode fails
has comment: http://stackoverflow.com/comment/84691033
has body: I have a file with the following line: raúl fernando sendic rodríguez is the leader of uruguay . I am reading the file doing: l = open(file_name).read().split() And I get: ['ra\xc3\xbal', 'fernando', 'sendic', 'rodr\xc3\xadguez', 'is', 'the', 'leader', 'of', 'uruguay', '.'] I want to convert it to a unicode string with the u in the begining, but so far I tried: print list(map(lambda a: unicode(a, "utf-8"), l)) print list(map(lambda a: a.decode('utf-8'), l)) And got (same for both): [u'ra\xfal', u'fernando', u'sendic', u'rodr\xedguez', u'is', u'the', u'leader', u'of', u'uruguay', u'.'] How can I properly decode that string as unicode? Note: This is python 2.7
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84690983
tagged with: python
duplicate of: http://stackoverflow.com/q/1436703
answer count: 0

http://stackoverflow.com/a/48845736
has comment: http://stackoverflow.com/comment/84695590
downvote count: 0
has comment: http://stackoverflow.com/comment/84695561
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/84695615
has comment: http://stackoverflow.com/comment/84695580
accepted answer of: http://stackoverflow.com/q/48845652
upvote count: 3
answers question: http://stackoverflow.com/q/48845652
has body: Your request is unsuccessful, which is why you're not finding the right tag. The returned content is an error page. You can bypass this error by changing your User-Agent header to that of a browser: import requests from bs4 import BeautifulSoup url = 'https://cazana.com/uk/car/RA51GZJ' headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)' 'AppleWebKit/537.36 (KHTML, like Gecko)' 'Chrome/64.0.3282.167 Safari/537.36' } result = requests.get(url, headers=headers) soup = BeautifulSoup(result.content, 'html.parser') match = soup.find('meta', name='description') if match: print(match.attrs['content']) else: print('Request unsuccessful') Note that too many requests at once can also trigger an unsuccessful request.
has comment: http://stackoverflow.com/comment/84695677
has comment: http://stackoverflow.com/comment/84695670
type: AcceptedAnswer

http://stackoverflow.com/comment/84676733
type: AnswerComment
has text: Wow! I never thought to tackle it like this. Would I be able to just store the result in another variable and be fine?
type: Comment
score: 2
comment on: http://stackoverflow.com/a/48835896

http://stackoverflow.com/q/48895468
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/89228
has comment: http://stackoverflow.com/comment/84797829
has body: So, I have a legacy script ts, that I need to call in a loop using several string arguments: #User supplied ts = '/d1/user/script.py' adir = '/d1/user/adir' mfile = '/d1/user/script.nc' outdir = '/d1/user/park/' metens = glob.glob(adir + '/*.nc') #reads all files for count, value in enumerate(metens): runcom = [ts, mfile, metens[count], outdir + os.path.basename(metens[count])] runcom = " ".join(runcom) #This creates a string of CL arguments subprocess.call(['python2.7', runcom], shell=True) Now, when I run it, it calls python2.7 and opens the Python shell instead of running it as python2.7 runcom. How can I make it run as a script instead of opening the shell?
has title: Why does subprocess.call(['python', argsStr]) fail both with or without shell=True?
has comment: http://stackoverflow.com/comment/84796843
has answer: http://stackoverflow.com/a/48896163
accepted answer: http://stackoverflow.com/a/48896163
score: 0
has comment: http://stackoverflow.com/comment/84797858
has comment: http://stackoverflow.com/comment/84796878
has comment: http://stackoverflow.com/comment/84797810
has comment: http://stackoverflow.com/comment/84797765
has comment: http://stackoverflow.com/comment/84796801
has comment: http://stackoverflow.com/comment/84797242
has answer: http://stackoverflow.com/a/48895997
has comment: http://stackoverflow.com/comment/84797349
tagged with: python
has comment: http://stackoverflow.com/comment/84797875
possible better answer: http://stackoverflow.com/a/48895997
type: AnsweredQuestion
tagged with: subprocess
has comment: http://stackoverflow.com/comment/84796934
has comment: http://stackoverflow.com/comment/84797830

http://stackoverflow.com/a/48940334
upvote count: 3
answers question: http://stackoverflow.com/q/48939823
has body: mypy does not run Python code at all. It is strictly a static analysis program. So there is no such thing as "run[ning] the tests twice" in this case. That is, you won't have to wait for your tests to run to get results from mypy. Just run mypy over the test package or module like you would with non-test code (for simple cases, mypy test_foo.py, for more complex cases, see the mypy documentation).
score: 3
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48939823
type: Answer

http://stackoverflow.com/comment/84730669
type: Comment
comment on: http://stackoverflow.com/a/48863163
has text: @vittorio yeah like the same `a = numpy.matrix(l)[:x,:y]`
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84744878
has text: I'd guess because `tree_` isn't an attribute of that class.
type: Comment
type: QuestionComment
score: 2
comment on: http://stackoverflow.com/q/48870380

http://stackoverflow.com/comment/84819201
has text: What I mean is doing something like this `mat, kat = myfunc1(1, 2, 3)`. And same for the myfunc2. And then assert that what you want to verify :)
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48905837
type: QuestionComment

http://stackoverflow.com/a/49111853
upvote count: 1
type: Answer
downvote count: 0
has body: You can use a short regex [^/]*$ Code: import re s = [{"url": "http://res1.icourses.cn/share/process17//mp4/2017/3/17/6332c641-28b5-43a0-894c-972bd804f4e1_SD.mp4", "name": "1-课程导学"}, {"url": "http://res2.icourses.cn/share/process17//mp4/2017/3/17/a21902b6-8680-4bdf-8f47-4f99d1354475_SD.mp4", "name": "2-计算机网络的定义与分类"}] filenames = [re.findall('[^/]*$', i['url'])[0] for i in s] print(filenames)` Output: ['6332c641-28b5-43a0-894c-972bd804f4e1_SD.mp4', 'a21902b6-8680-4bdf-8f47-4f99d1354475_SD.mp4'] Check the regex - https://regex101.com/r/k9VwC6/30
score: 1
answers question: http://stackoverflow.com/q/48927604

http://stackoverflow.com/a/48873803
downvote count: 0
has comment: http://stackoverflow.com/comment/84753329
answers question: http://stackoverflow.com/q/48873781
type: Answer
has comment: http://stackoverflow.com/comment/84759888
accepted answer of: http://stackoverflow.com/q/48873781
has body: You need to break out of your loop. while x == y: print("You Won 50$") break That said, a while loop is a bad way to do this. I would use an if statement: if x == y: print("You Won 50$") Then no break is needed. Additionally, don't set anything equal to print, and make the values the same type. curSum = 50 def gamble(): global curSum dice = [1,2,3,4,5,6] x = input('what is the number ') x = int(x) secure_random = rm.SystemRandom() y = int(secure_random.choice(dice)) print(y) if x == y : # Change + 1 to whatever amount you want to add curSum = curSum + 1 print("You Won %d $" % curSum) for i in range(3): gamble()
upvote count: 1
has comment: http://stackoverflow.com/comment/84760487
score: 1
type: AcceptedAnswer

django-rest-framework
tags question: http://stackoverflow.com/q/48808282
tags question: http://stackoverflow.com/q/48813029
tags question: http://stackoverflow.com/q/48852092
tags question: http://stackoverflow.com/q/48804687
tags question: http://stackoverflow.com/q/48880466
tags question: http://stackoverflow.com/q/48927439
tags question: http://stackoverflow.com/q/48835946
tags question: http://stackoverflow.com/q/48849610
tags question: http://stackoverflow.com/q/48833259
tags question: http://stackoverflow.com/q/48805477
type: Tag
tags question: http://stackoverflow.com/q/48901934
tags question: http://stackoverflow.com/q/48887001
tags question: http://stackoverflow.com/q/48903357
tags question: http://stackoverflow.com/q/48911345
tags question: http://stackoverflow.com/q/48944619
tags question: http://stackoverflow.com/q/48813033
tags question: http://stackoverflow.com/q/48832536
tags question: http://stackoverflow.com/q/48907523
tags question: http://stackoverflow.com/q/48884153
tags question: http://stackoverflow.com/q/48829378
tags question: http://stackoverflow.com/q/48943331
tags question: http://stackoverflow.com/q/48864107
tags question: http://stackoverflow.com/q/48902303
tags question: http://stackoverflow.com/q/48905974
tags question: http://stackoverflow.com/q/48940669
tag name: django-rest-framework
tags question: http://stackoverflow.com/q/48942393
tags question: http://stackoverflow.com/q/48806770
tags question: http://stackoverflow.com/q/48851471
tags question: http://stackoverflow.com/q/48857762
tags question: http://stackoverflow.com/q/48870065
tags question: http://stackoverflow.com/q/48895975
tags question: http://stackoverflow.com/q/48946729
tags question: http://stackoverflow.com/q/48850125
tags question: http://stackoverflow.com/q/48805703
tags question: http://stackoverflow.com/q/48885254
tags question: http://stackoverflow.com/q/48869303
tags question: http://stackoverflow.com/q/48922079
tags question: http://stackoverflow.com/q/48861168

http://stackoverflow.com/comment/84789045
type: QuestionComment
comment on: http://stackoverflow.com/q/48891714
score: 1
has text: try to uninstall and reinstall with `pip install --no-cache-dir tweepy`. let me know if that solves the problem.
type: Comment

http://stackoverflow.com/comment/84772984
type: QuestionComment
comment on: http://stackoverflow.com/q/48884147
has text: But `len(L1) > len(L2)` !
score: 0
type: Comment

http://stackoverflow.com/comment/84926815
has text: Thank you, I didn’t notice this in the API!
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48956844

http://stackoverflow.com/comment/85154617
comment on: http://stackoverflow.com/a/48956246
type: Comment
has text: @Vishal "My question is that how do I verify if the exception caught in the response is actually a 400 status code so that I can handle it accordingly." I answered that question. I am saying validating against status 400 is a bad idea, because multiple problems cause status 400.
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84794051
comment on: http://stackoverflow.com/a/48881972
has text: Thanks for the answer. I like the use of generators and the overall readability. This code is much cleaner than mine
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48823400
answer count: 1
downvote count: 0
favorite count: 0
linked to: http://stackoverflow.com/q/38840319
tagged with: python
has body: So, I used the answer from Put a 2d Array into a Pandas Series to put 2D numpy array to pandas series. In short, it is a = np.zeros((5,2)) s = pd.Series(list(a)) Now, what is the cheapest way to convert that pandas Series back to 2D array? If I try s.values, I get array of arrays with object dtype. So far I tried np.vstack(s.values) but it copies the data, of course.
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48823420
has title: Pandas series to 2d array
type: Question
linked to: http://stackoverflow.com/q/29759883
accepted answer: http://stackoverflow.com/a/48823420
score: 12
upvote count: 12
tagged with: pandas

http://stackoverflow.com/a/48833470
answers question: http://stackoverflow.com/q/48812740
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48812740
has comment: http://stackoverflow.com/comment/84901638
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: I can reproduce the error with: python3 setup.py register -r myserver In request.log: 10.255.0.3 - - [16/Feb/2018:19:12:51 +0000] "POST /nexus/repository/pypi/ HTTP/1.1" 401 0 3 "Python-urllib/3.6" Mind the second - should be the username but NONE gets there. Output example using curl: curl -u admin -X POST https://my_awesome_nexus_server/nexus/repository/pypi/: 10.255.0.3 - admin [16/Feb/2018:19:14:45 +0000] "POST /nexus/repository/pypi/ HTTP/1.1" 500 1948 15 "curl/7.55.1" Tested on Docker Container, latest (3.8), and 3.7. It seems to me that problem is at client side instead. UPDATE: Managed to make it work with twine (in a virtualenv): python3 setup.py build twine upload -r myserver dist/mypackage-0.1.0.tar.gz And it is available at Nexus3 (3.7).

http://stackoverflow.com/comment/84793413
type: QuestionComment
comment on: http://stackoverflow.com/q/48876631
type: Comment
has text: Part of the problem is that you do not clearly specify when you want the value of `self.day` to revert. Is it in the `getday` method (which should probably be a property BTW)? Is it when *any* attribute is accessed?
score: 0

http://stackoverflow.com/a/48827294
has body: You need to create a group and quantify it: import re my_str = 'my example example string contains example some text' my_str = re.sub(r'\b(example)(?:\s+\1)+\b', r'\1', my_str) print(my_str) # =&gt; my example string contains example some text # To build the pattern dynamically, if your word is not static word = "example" my_str = re.sub(r'(?&lt;!\w)({})(?:\s+\1)+(?!\w)'.format(re.escape(word)), r'\1', my_str) See the Python demo I added word boundaries as - judging by the spaces in the original code - whole word matches are expected. See the regex demo here: \b - word boundary (replaced with (?&lt;!\w) - no word char before the current position is allowed - in the dynamic approach since re.escape might also support "words" like .word. and then \b might stop the regex from matching) (example) - Group 1 (referred to with \1 from the replacement pattern): the example word (?:\s+\1)+ - 1 or more occurrences of \s+ - 1+ whitespaces \1 - a backreference to the Group 1 value, that is, an example word \b - word boundary (replaced with (?!\w) - no word char after the current position is allowed). Remember that in Python 2.x, you need to use re.U if you need to make \b word boundary Unicode-aware.
upvote count: 4
type: AcceptedAnswer
score: 3
type: Answer
has comment: http://stackoverflow.com/comment/84658886
accepted answer of: http://stackoverflow.com/q/48827207
answers question: http://stackoverflow.com/q/48827207
downvote count: 1

pysnmp
tags question: http://stackoverflow.com/q/48837417
tag name: pysnmp
type: Tag
tags question: http://stackoverflow.com/q/48814708

http://stackoverflow.com/comment/84802022
comment on: http://stackoverflow.com/q/48898216
type: Comment
type: QuestionComment
has text: @CKHuang but why would you do this? Why wouldn't you use a well-supported serialization format, rather than cooking up your own?
score: 0

http://stackoverflow.com/q/48889756
answer count: 0
type: UnansweredQuestion
tagged with: django
has comment: http://stackoverflow.com/comment/84793516
has body: I'm new to Django and I'm trying to write a project where employers can post job vacancies. I want to be able to save the job description as a model using a model-form but I also want to allow the user to specify how many requirements there are for a job. So one job might specify 4 job requirements while another might specify 6. So saved models will vary depending on how much requirements were specified. Is there anyway to create a dynamic model-form where the user can specify how many fields there are in the form and model? I've been researching this for a while but yet to find a simple explanation.
has title: How to create a dynamic model-form?
tagged with: django-models
tagged with: django-forms
type: Question
has comment: http://stackoverflow.com/comment/84785647
score: 0
tagged with: python

http://stackoverflow.com/a/48853990
type: AcceptedAnswer
type: Answer
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48853947
answers question: http://stackoverflow.com/q/48853947
score: 4
has body: From the docs Test method names or function names should start with “test_”, as in test_example. Methods with names that don’t match this pattern won’t be executed as tests. So in your case you can rename your test method to def test_first_name(self):

http://stackoverflow.com/a/58772266
has body: Change to imageio will fix the problem imread is deprecated! imread is deprecated in SciPy 1.0.0, and will be removed in 1.2.0. Use imageio.imread instead
downvote count: 2
upvote count: 0
answers question: http://stackoverflow.com/q/48923151
type: Answer
score: -2

http://stackoverflow.com/q/48932283
type: Question
answer count: 2
downvote count: 0
possible better answer: http://stackoverflow.com/a/48932572
has answer: http://stackoverflow.com/a/48932572
has answer: http://stackoverflow.com/a/53548929
score: 3
has comment: http://stackoverflow.com/comment/87585097
favorite count: 0
has body: I'm currently going through the book Fundamentals of Deep Learning by Nikhil Buduma and it appears there's an error in one of the scripts it provides. The script is meant to provide an introduction into sessions in Tensorflow and is as follows: import tensorflow as tf from read_data import get_minibatch x = tf.placeholder(tf.float32, name="x", shape=[None, 784]) w = tf.Variable(tf.random_uniform([784,10], -1, 1), name = "w") b = tf.Variable(tf.zeroes([10]), name = "biases") output = tf.matmul(x,w) + b init_op = tf.initialize_all_variables() sess = tf.Session() sess.run(init_op) feed_dict = {"x" : get_minibatch()} sess.run(output, feed_dict=feed_dict) The problem I'm having is that I receive the error ModuleNotFoundError: No module named 'read_data'. The original script also had empty parenthesis after line 2's get_minibatch but I removed them to remove a different error. Do I have to externally download this library or something?
tagged with: python
has title: Why does from read_data import get_minibatch() return ModuleNotFoundError: No module named 'read_data'
accepted answer: http://stackoverflow.com/a/53548929
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84871369
upvote count: 3
tagged with: tensorflow

http://stackoverflow.com/comment/84658228
type: AnswerComment
has text: haha it works for me...Actually, in my real function, I have many calculations so I have defined function to plot..anyways thanks a lot :)
type: Comment
comment on: http://stackoverflow.com/a/48827201
score: 1

http://stackoverflow.com/comment/84691354
has text: Depending on the value of `k` this will be formatted into for example `S10` which is interpreted here as a numpy dtype. 'S' stands for string, 10 is the maximum length. Note that this applies for Python2. In 3 you would use 'U' for unicode.
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48843378

http://stackoverflow.com/a/48834580
has comment: http://stackoverflow.com/comment/86329994
type: Answer
upvote count: 6
has body: (Spyder maintainer here) This bug was introduced by the latest update to Pyzmq (17.0.0). The easiest way to solve this is to downgrade to Pyzmq 16.0.4 until a new version of Ipykernel is released (most probably 4.8.2).
downvote count: 1
score: 5
answers question: http://stackoverflow.com/q/48831091

http://stackoverflow.com/comment/84711878
has text: Thank you both :)
score: 0
comment on: http://stackoverflow.com/q/48854234
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84791090
has text: That implementation looks fine to me - you should not need a transform (which sometimes makes sampling easier - for example, allowing you to sample from all the reals instead of just the positives). Is something going wrong with it? I have posted an alternative as an answer.
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48857941

http://stackoverflow.com/comment/84846268
has text: show how you run your module. Print sys.executable from your module before the import. Compare results.
score: 0
comment on: http://stackoverflow.com/q/48919965
type: Comment
type: QuestionComment

http://stackoverflow.com/a/68556981
upvote count: 2
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48925318
type: Answer
has body: If this error happens when you try to run your app into an uwsgi environment such us: uwsgi -w myfile:app\ --http11-socket 127.0.0.1:3333\ --enable-threads\ --threads 4\ --logformat '%(addr) - %(user) [%(ltime)] "%(method) %(uri) %(proto)" %(status) %(size) "%(referer)" "%(uagent)"' where myfile.py contains the application: import socketio import eventlet from engineio.async_drivers import gevent from flask import Flask sio = socketio.Server(async_mode="gevent_uwsgi", cors_allowed_origins='*', engineio_logger=True) app = Flask(__name__) # this generates the uwsgi-runnable application my_wsgi = socketio.WSGIApp(sio) app = socketio.Middleware(sio, my_wsgi) If you have errors installing gevent by pip3 install gevent probably pip will try to install some of the last gevent versions: 21.1.0, 21.1.1, 21.1.2 This may lead to installing errors depending the operative system you use (some issues with darwin). To overcome these errors, it also works using simpler, older versions of gevent: pip3 install gevent==1.5.0

loops
tags question: http://stackoverflow.com/q/48921509
tags question: http://stackoverflow.com/q/48825070
tags question: http://stackoverflow.com/q/48827306
tags question: http://stackoverflow.com/q/48844421
tags question: http://stackoverflow.com/q/48836565
tags question: http://stackoverflow.com/q/48855674
tags question: http://stackoverflow.com/q/48898704
tags question: http://stackoverflow.com/q/48882293
tags question: http://stackoverflow.com/q/48823387
tags question: http://stackoverflow.com/q/48815486
tags question: http://stackoverflow.com/q/48887198
tags question: http://stackoverflow.com/q/48810749
tags question: http://stackoverflow.com/q/48840881
type: Tag
tags question: http://stackoverflow.com/q/48823024
tags question: http://stackoverflow.com/q/48864197
tags question: http://stackoverflow.com/q/48957150
tags question: http://stackoverflow.com/q/48884965
tags question: http://stackoverflow.com/q/48847632
tags question: http://stackoverflow.com/q/48822061
tags question: http://stackoverflow.com/q/48935409
tags question: http://stackoverflow.com/q/48838481
tags question: http://stackoverflow.com/q/48856359
tags question: http://stackoverflow.com/q/48921736
tags question: http://stackoverflow.com/q/48876888
tags question: http://stackoverflow.com/q/48886320
tags question: http://stackoverflow.com/q/48862435
tags question: http://stackoverflow.com/q/48917967
tags question: http://stackoverflow.com/q/48918739
tag name: loops
tags question: http://stackoverflow.com/q/48810726
tags question: http://stackoverflow.com/q/48944185
tags question: http://stackoverflow.com/q/48879615
tags question: http://stackoverflow.com/q/48843120
tags question: http://stackoverflow.com/q/48849428
tags question: http://stackoverflow.com/q/48913382
tags question: http://stackoverflow.com/q/48957769
tags question: http://stackoverflow.com/q/48929610
tags question: http://stackoverflow.com/q/48810947
tags question: http://stackoverflow.com/q/48864433
tags question: http://stackoverflow.com/q/48945506
tags question: http://stackoverflow.com/q/48958379
tags question: http://stackoverflow.com/q/48951727
tags question: http://stackoverflow.com/q/48884926
tags question: http://stackoverflow.com/q/48897760
tags question: http://stackoverflow.com/q/48924123
tags question: http://stackoverflow.com/q/48943285
tags question: http://stackoverflow.com/q/48859027
tags question: http://stackoverflow.com/q/48891471
tags question: http://stackoverflow.com/q/48941307
tags question: http://stackoverflow.com/q/48837733
tags question: http://stackoverflow.com/q/48953331

http://stackoverflow.com/a/48867559
has comment: http://stackoverflow.com/comment/84738348
score: 1
has comment: http://stackoverflow.com/comment/84742418
accepted answer of: http://stackoverflow.com/q/48867518
answers question: http://stackoverflow.com/q/48867518
has body: First in pandas the best is not used loops, because slow (apply are loops under the hood) and rather use vectorized solutions. Use extract and replace by regex join all values by | and use word boundary for exact match: gender_list=['woman', 'man', 'baby', 'unisex'] #exact match is not important #pat = '|'.join(gender_list) pat = '|'.join(r"\b{}\b".format(x) for x in gender_list) print (pat) \bwoman\b|\bman\b|\bbaby\b|\bunisex\b df['gender'] = df['query'].str.extract('('+ pat + ')', expand=False) df['query'] = df['query'].str.replace(pat, '').str.strip() print (df) query gender 0 handbag woman 1 shoe man 2 t-shirt baby 3 watch unisex 4 dress NaN Differences: print (df) query 0 handbag woman 1 shoe many &lt;-man change to many 2 t-shirt baby 3 watch unisex 4 dress gender_list=['woman', 'man', 'baby', 'unisex'] pat = '|'.join(r"\b{}\b".format(x) for x in gender_list) df['gender'] = df['query'].str.extract('('+ pat + ')', expand=False) df['query'] = df['query'].str.replace(pat, '').str.strip() print (df) query gender 0 handbag woman 1 shoe many NaN &lt;-many not extracted 2 t-shirt baby 3 watch unisex 4 dress NaN gender_list=['woman', 'man', 'baby', 'unisex'] pat = '|'.join(gender_list) df['gender'] = df['query'].str.extract('('+ pat + ')', expand=False) df['query'] = df['query'].str.replace(pat, '').str.strip() print (df) query gender 0 handbag woman 1 shoe y man &lt;-stay y from many 2 t-shirt baby 3 watch unisex 4 dress NaN Timings: df = pd.DataFrame({'query': ['handbag woman', 'shoe man', 't-shirt baby', 'watch unisex', 'dress', 'manpower']}) print (df) df = pd.concat([df] * 10000, ignore_index=True) In [299]: %%timeit ...: pat = '|'.join(r"\b{}\b".format(x) for x in gender_list) ...: df['gender'] = df['query'].str.extract('('+ pat + ')', expand=False) ...: df['query'] = df['query'].str.replace(pat, '').str.strip() ...: ...: 1 loop, best of 3: 143 ms per loop In [300]: %%timeit ...: gender_set = set(gender_list) ...: ...: def gender_sep(row): ...: lst = row['query'…
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer

http://stackoverflow.com/a/48886960
downvote count: 0
has body: Use this: import requests from bs4 import BeautifulSoup r = requests.get('http://www.rushmore.tv/schedule') soup = BeautifulSoup(r.text, "html.parser") for row in soup.find('ul', id='myUL').findAll('li'): print(row.text) Partial Output: 10:30 - 13:30 Olympics: Women's Curling, Canada vs China (CA Coverage) - Channel 21 10:30 - 11:30 Olympics: Freestyle, Men's Half Pipe (US Coverage) - Channel 34 11:30 - 14:45 Olympics: BBC Coverage - Channel 92 11:30 - 19:30 Olympics: BBC Red Button Coverage - Channel 103 11:30 - 13:30 Olympics: Women's Curling, Great Britain vs Japan - Channel 105 13:00 - 15:30 Olympics: Men's Ice Hockey: Slovenia vs Norway - Channel 11 13:30 - 15:30 Olympics: Men's Ice Hockey: Slovenia vs Norway (JIP) - Channel 21 13:30 - 21:30 Olympics: DE Coverage - Channel 88 14:45 - 18:30 Olympics: BBC Coverage - Channel 91
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48885995
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48885995
type: Answer
score: 2

http://stackoverflow.com/a/48959757
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/140248392
has body: You can form the sorted series by sorting the values that aren't 'a' and then appending all the 'a' values. sorted_series = ser[ser != 'a'].append(ser[ser == 'a'])
upvote count: 1
type: Answer
answers question: http://stackoverflow.com/q/48959662

http://stackoverflow.com/q/48876520
has answer: http://stackoverflow.com/a/48877900
has body: How can I implement infinite scrolling using GAE's "cursor" feature and Jinja2? For example, say that I retrieve all users not named John (say, 5000 users) Python users = User.query(User.name != "John") user_cursor = memcache.get('user_cursor') if user_cursor: users.with_cursor(start_cursor=user_cursor) self.render('templates/front.html', users = users) And then I want to display the 5000 users, 3 at a time, and if the viewer scrolls to the bottom or clicks "Load More" the next three come up. HTML {% for row in users | batch(3) %} {% for u in row %} {{u.firstname}} {% endfor %} {% endfor %} What is the best (easiest) way to implement this? Actual code would be much appreciated, I've been trying to do this for a day now, and haven't made much progress. Thanks in advance!
has comment: http://stackoverflow.com/comment/84759839
tagged with: infinite-scroll
has title: How to implement Infinite Scrolling using GAE "Cursor" and Jinja2?
type: Question
tagged with: google-app-engine
tagged with: python
answer count: 1
score: 0
tagged with: jinja2
tagged with: jquery
type: UnansweredQuestion

http://stackoverflow.com/a/48827822
answers question: http://stackoverflow.com/q/48827752
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84659419
type: Answer
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48827752
has body: This is a classic python gotcha to do with the fact that all python objects are references. In your case this means that matrix[0] is matrix[1] is matrix[2] since is is True if two objects are the same thing in memory. Do this instead matrix = [[0]*6 for _ in range(3)] Now matrix[0] is matrix[1] is matrix[2] returns False. Alternatively, use numpy which was made for manipulating numerical arrays without these issues.

http://stackoverflow.com/a/48892356
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48892145
has comment: http://stackoverflow.com/comment/84790318
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/84790325
has body: Are you doing conn.commit() after the insert to commit the transaction? Also you'll need cur.close() conn.close() at some point to close things cleanly. You can also use autocommit mode. And as the comment by Jared points out it would be cleaner to use a context manager in stead of try/catch. with psycopg2.connect("dbname='token_generator' user='token_generator' host='myip' password='mypass'") as conn: conn.autocommit = True with conn.cursor() as cur: try: cur.execute("INSERT ...") except Exception as exc: print("Error executing SQL: %s"%exc)
upvote count: 5
answers question: http://stackoverflow.com/q/48892145

http://stackoverflow.com/a/48978704
answers question: http://stackoverflow.com/q/48948290
upvote count: 1
type: AcceptedAnswer
downvote count: 0
type: Answer
score: 1
has comment: http://stackoverflow.com/comment/84981475
accepted answer of: http://stackoverflow.com/q/48948290
has body: If you transpose z grid, you will have the contours rotated. In last two lines change z to z.T: CS=plt.contour(xi, yi, zi.T,colors='k', norm=plt.Normalize(vmax=abs(zi).max(), vmin=-abs(zi).max())) CS = plt.contourf(xi, yi, zi.T,15,cmap=plt.cm.jet) Remember that in images X axis is horizontal and Y is vertical, but for matrices 1st dimension (X) is vertical and 2nd (Y) is horizontal.

http://stackoverflow.com/q/48938717
tagged with: dataframe
has title: Pandas DataFrame.resample monthly offset from particular day of month
type: Question
tagged with: pandas
downvote count: 0
has comment: http://stackoverflow.com/comment/84884669
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: resampling
tagged with: python
score: 2
has body: I have a DataFrame df with sporadic daily business day rows (i.e., there is not always a row for every business day.) For each row in df I want to create a historical resampled mean dfm going back one month at a time. For example, if I have a row for 2018-02-22 then I want rolling means for rows in the following date ranges: 2018-01-23 : 2018-02-22 2017-12-23 : 2018-01-22 2017-11-23 : 2017-12-22 etc. But I can't see a way to keep this pegged to the particular day of the month using conventional offsets. For example, if I do: dfm = df.resample('30D').mean() Then we see two problems: It references the beginning of the DataFrame. In fact, I can't find a way to force .resample() to peg itself to the end of the DataFrame – even if I have it operate on df_reversed = df.loc[:'2018-02-22'].iloc[::-1]. Is there a way to "peg" the resampling to something other than the earliest date in the DataFrame? (And ideally pegged to each particular row as I run some lambda on the associated historical resampling from each row's date?) It will drift over time, because not every month is 30 days long. So as I go back in time I will find that the interval 12 "months" prior ends 2017-02-27, not 2017-02-22 like I want. Knowing that I want to resample by non-overlapping "months," the second problem can be well-defined for month days 29-31: For example, if I ask to resample for '2018-03-31' then the date ranges would end at the end of each preceding month: 2018-03-01 : 2018-03-31 2018-02-01 : 2018-02-28 2018-01-01 : 2018-02-31 etc. Though again, I don't know: is there a good or easy way to do this in pandas? tl;dr: Given something like the following: someperiods = 20 # this can be a number of days covering many years somefrequency = '8D' # this can vary from 1D to maybe 10D rng = pd.date_range('2017-01-03', periods=someperiods, freq=somefrequency) df = pd.DataFrame({'x': rng.day}, index=rng) # x in practice is exogenous data from pandas.tseries.offsets import * df['MonthPrior'] = df.index.to_…
answer count: 0

subplot
tags question: http://stackoverflow.com/q/48818535
tag name: subplot
type: Tag

http://stackoverflow.com/q/48853436
has answer: http://stackoverflow.com/a/48853695
possible better answer: http://stackoverflow.com/a/48854144
has title: How to run class in separated thread Python?
has comment: http://stackoverflow.com/comment/84713335
score: 0
upvote count: 1
downvote count: 1
tagged with: python
has comment: http://stackoverflow.com/comment/84713307
favorite count: 0
tagged with: python-3.x
linked to: http://stackoverflow.com/q/15365406
type: AnsweredQuestion
has body: I have two classes in Python script. One of is Main() and the second is Loading() class Main: pass class Loading: pass At first, works Main() that return was filled dictionary Then is created instance of Loading() that iterates all images and downloads them: ## LOAD IMAGES ## imageLoader = Loading() imageLoader.save() So, the problem is when I call this script it creates one major thread that is waiting for the end of imageLoader = Loading(). As a result, a major thread works so long, it invokes 502 Server error. How to run imageLoader = Loading() in a separate background thread that to release major thread? What will be launched first in this code: LOADED_IMAGES = {} IMAGES_ERRORS = [] IMAGES = {"A": "https://images.aif.ru/009/299/3378e1a1ab2d1c6e6be6d38253dd3632.jpg", "B": "http://static1.repo.aif.ru/1/77/623957/b99ee5f894f38261e4d3778350ffbaae.jpg"} excel = Excel() excel.readExcel(file_path, 'Main') imageLoader = ImageLoader() Thread(target=imageLoader.run().save()).start() Does it work line by line or Thread will be created immediately? **This is full code:** class ImageLoader: def run(self): for article, image in IMAGES.items(): if image is None or image == '': continue LOADED_IMAGES[article] = self.loadImage(self.replaceHttpsProtocol(image), '/home/o/oliwin4/jara/public_html/image/catalog/s/') def replaceHttpsProtocol(self, url): return url.replace("https:", "http:") def nameNameGenerate(self): return int(round(time.time() * 1000)) def extention(self, path): ext = path.split(".")[-1] return '.' + ext if ext else "jpg" def save(self): for article, image in LOADED_IMAGES.items(): self.add(article, image) def add(self, article, image): Products.update(image=image).where(Products.sku == article).execute() def loadImage(self, path, path_folder): try: filename = str(self.nameNameGenerate()) + str(self.extention(path)) wget.download(url=path, out=path_folder + filename) return 'catalog/s/' + filename except BaseException as e: IMAGES_ERRORS.append(str(e)) Using: def …
accepted answer: http://stackoverflow.com/a/48853695
has answer: http://stackoverflow.com/a/48854144
type: Question
answer count: 2

http://stackoverflow.com/comment/84643494
type: AnswerComment
type: Comment
has text: @ikel you can check https://stackoverflow.com/questions/19798153/difference-between-map-applymap-and-apply-methods-in-pandas
comment on: http://stackoverflow.com/a/48819843
score: 0

http://stackoverflow.com/comment/84932740
type: Comment
type: QuestionComment
has text: Welcome to StackOverflow. Please take the time to read this post on [how to provide a great pandas example](http://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) as well as how to provide a [minimal, complete, and verifiable example](http://stackoverflow.com/help/mcve) and revise your question accordingly. These tips on [how to ask a good question](http://stackoverflow.com/help/how-to-ask) may also be useful.
score: 0
comment on: http://stackoverflow.com/q/48963258

http://stackoverflow.com/a/48879590
has body: On Windows. os.system("C:/Program Files (x86)/VideoLAN/VLC/vlc.exe") #Or mention your vlc.exe path Using subprocess to open vlc player p = subprocess.Popen(["C:/Program Files (x86)/VideoLAN/VLC/vlc.exe"]) #Or mention your vlc.exe path
score: 0
answers question: http://stackoverflow.com/q/48878203
type: Answer

http://stackoverflow.com/comment/84646575
comment on: http://stackoverflow.com/q/48812532
score: 0
type: Comment
type: QuestionComment
has text: It doesn't login. It redirects to this page >>> print (r.url) http://210.212.227.210/tkmce/Apperror.aspx

http://stackoverflow.com/a/68402701
type: Answer
score: 2
has body: You can use pprint module from python library. It works well from colab. However, colab prints output in limited number of line such as 5,000 lines on screen if it exceeds output limit. from pprint import pprint printable = 'long statement' pprint(printable)
upvote count: 2
answers question: http://stackoverflow.com/q/48906481
downvote count: 0

http://stackoverflow.com/a/48960613
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48960009
accepted answer of: http://stackoverflow.com/q/48960009
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: As already mentioned you need to define the STATIC_ROOT variable in your settings.py in order to make collectstatic work. The absolute path to the directory where collectstatic will collect static files for deployment. Example: "/var/www/example.com/static/" You may want to define STATICFILES_DIRS too. The nginx.conf from the tutorial you have posted expects to serve your collected static files from /home/boards/staticfiles/. Since the tutorial deploys everything on a single, monolithic server which hosts the database (postgres), web server (nginx) and the application (django) you can set it as follows: STATIC_ROOT = '/home/boards/staticfiles/'

http://stackoverflow.com/comment/84674459
score: 1
type: AnswerComment
type: Comment
has text: I think he wants to get rid of any `[...]`, not just those specific strings.
comment on: http://stackoverflow.com/a/48834918

http://stackoverflow.com/q/48886085
has comment: http://stackoverflow.com/comment/84777505
tagged with: python-3.x
tagged with: tkinter
tagged with: python
downvote count: 1
has comment: http://stackoverflow.com/comment/84777521
has title: I can't Manage to close from in Python 3 with tkinter
has body: I am trying to build a xml parser in python, i start to build gui framework, and here i need to create some forms to save some settings values. I manage to make it work and save some values to txt files for startup. But what ever i tried i can't manage to close the settings form when i click button. i need to close it with the x on the window. i can't find the root of the issue. what i am trying to do is, when i click Cancel, form will be closed. if i click Save, form will first save data then close. thanks a lot for your supports. my code is as follows: try: # for Python2 print ("Importing for py2"); from Tkinter import * ## notice capitalized T in Tkinter import tkFileDialog except ImportError: # for Python3 print ("Importing for py2 Failed !!!!"); print ("Importing for py3"); from tkinter import * from tkinter import filedialog from tkinter.scrolledtext import ScrolledText from tkinter import messagebox mainform = Tk() mainform.minsize(300,100) mainform.geometry('{}x{}'.format(800, 600)) mainform.title("OVF Template Parser - By Gurhan Cagin (R) 2018") textPad = ScrolledText(mainform, width=100, height=80) textPad.pack() ## functions and procdures def donothing(): x = 0 def quit(): if messagebox.askokcancel("Quit", "Do you really want to quit?"): exit() def about_command(): label = messagebox.showinfo("About", "Nokia OVF Template Parser \nCopyright 2018 \nNo rights left to reserve") def open_command(): file = filedialog.askopenfile(parent=mainform, mode='rb', title='Select a file') if file != None: contents = file.read() textPad.insert('1.0',contents) file.close() def SettingsFormFxn(): settingsForm = Tk() settingsForm.minsize(300,100) settingsForm.geometry('{}x{}'.format(750, 550)) settingsForm.title("Settings for the devault values") ## Frames top_frame = Frame(settingsForm, width = 740, height = 50, pady = 3) bottom_frame = Frame(settingsForm, width = 740, height = 50, pady = 3) settingsForm.grid_rowconfigure(1, weight=1) settingsForm.grid_columnconfigure(0, we…
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48886756
score: -1
type: Question
upvote count: 0
accepted answer: http://stackoverflow.com/a/48886756
answer count: 1
favorite count: 0

http://stackoverflow.com/q/48874207
has body: I've been messing around for a few hours now and I'm a bit baffled on how I can 1. Add user data to an existing FBX file using python, and 2. Get known user data from and FBX file using python? import os import sys import FbxCommon import fbx f = "C:\Users\john\test.fbx" def fbx_user_data(filepath): fbxManager, fbxScene = FbxCommon.InitializeSdkObjects() FbxCommon.LoadScene(fbxManager, fbxScene, filepath) sceneInfo = fbxScene.GetSceneInfo() ......
downvote count: 0
score: 1
has comment: http://stackoverflow.com/comment/84752424
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0
upvote count: 1
type: Question
tagged with: fbx
has title: How to add and retrieve user data from FBX using python

http://stackoverflow.com/q/48883750
has title: Iterate and Filter Python dictionary
score: 0
has body: I have parsed a XML file into dictionary where I have {'NY240': {'Enable_Notifications': 'Enabled', 'Interface': 'LAN 1/3/2', 'ID': '5058', 'Location': 'NY240' 'Speed': '0', 'Validity': '1', 'updateDate': '2018-02-05 14:02:57'}, 'SF440': {'Enable_Notifications': 'Enabled', 'Interface': 'WAN 1/2/2', 'ID': '6353', 'Location': 'SF440' 'Speed': '1', 'Validity': '1', 'updateDate': '2018-02-08 16:02:57'}, ...} I get that with: import xml.etree.ElementTree as ET tree = ET.parse('data_file.xml') root = tree.getroot() dict_s = {} for child in root: for key in child: td={} for k in key: td.update({k.tag: k.text}) if k.tag=='Location': dict_s.update({k.text:td}) else: pass I know I didn't paste XML file here but I think there is no need, it's simple XML file, anyone who is even a little better than me with python dictionary iterations can start from here. What I need is select just those keys (and values of them) where the value of inner key 'Interface' contain 'WAN' (not 'startswith'). In this case that will be a second one, SF440. I have solved that this way, separatly: new_td = {} for key, value in dict_s.iteritems(): for k, v in value.iteritems(): if k=='Interface' and 'WAN' in v: new_td.update({key: value}) But I'm looking for solution implemented in the top code block, not separated if it's possible?
answer count: 1
tagged with: elementtree
type: UnansweredQuestion
tagged with: python
tagged with: dictionary
type: Question
has answer: http://stackoverflow.com/a/48884414

http://stackoverflow.com/comment/84750226
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48872847
score: 1
has text: 1. Get a recent version of Python. 2. Put it somewhere in your home. 3. Get the newest version of `pip`. 4. Create a virtual environment in your home. 5. Install all libs you need in the environment with `pip`. 6. Be more happy.

http://stackoverflow.com/comment/84785872
type: Comment
has text: It is still not clear what is going on here... For smaller arrays that fit into cache, e.g., `(10,1000,10)`, I get the following timings: method1 - 61.1 µs, method2 - 88.4 µs, and your method2 (==method3): 25.6 µs. So, pre-creating arrays seems to speed up things and also makes you method fastest. Then I tried pre-creating constant arrays in method1 (I call it method1b) and it is much slower (cache problems???) With very large arrays (last dim=10000) I get method1b extremely slow 1.2s, method1 - 208ms, method2 - 178ms, method3 - 100ms.
comment on: http://stackoverflow.com/a/48888971
score: 0
type: AnswerComment

http://stackoverflow.com/a/48876559
has comment: http://stackoverflow.com/comment/84790144
answers question: http://stackoverflow.com/q/48873995
score: 2
has comment: http://stackoverflow.com/comment/84784890
downvote count: 0
has body: This, surprising to me, is slower, but for whatever it's worth, here is a c++ solution that does what you were pointing at - hash each row as a set of bytes. The 'trick' is taking the address of an element &lt;char*&gt;&amp;a[i, 0] - most everything else is book-keeping. I may be doing some obviously sub-optimal and/or performance is likely better with a different hash table impl. Edit: re: how to create a string from a row I think the best you could do is this - construct a bytes object from the pointer. This does necessarily involve a copy of the row see c api docs. %%cython from numpy cimport * cimport numpy as np import numpy as np from cpython.bytes cimport PyBytes_FromStringAndSize def unique_int_string(ndarray[np.int64_t, ndim=2] a): cdef int i, len_before cdef int nr = a.shape[0] cdef int nc = a.shape[1] cdef set s = set() cdef ndarray[np.uint8_t, cast = True] idx = np.zeros(nr, dtype='bool') cdef bytes string for i in range(nr): len_before = len(s) string = PyBytes_FromStringAndSize(&lt;char*&gt;&amp;a[i, 0], sizeof(np.int64_t) * nc) s.add(string) if len(s) &gt; len_before: idx[i] = True return idx // timing In [9]: from unique import unique_ints In [10]: %timeit unique_int_tuple4(a) 100 loops, best of 3: 10.1 ms per loop In [11]: %timeit unique_ints(a) 100 loops, best of 3: 11.9 ms per loop In [12]: (unique_ints(a) == unique_int_tuple4(a)).all() Out[12]: True // helper.h #include &lt;unordered_set&gt; #include &lt;cstring&gt; struct Hasher { size_t size; size_t operator()(char* buf) const { // https://github.com/yt-project/yt/blob/c1569367c6e3d8d0a02e10d0f3d0bd701d2e2114/yt/utilities/lib/fnv_hash.pyx size_t hash_val = 2166136261; for (int i = 0; i &lt; size; ++i) { hash_val ^= buf[i]; hash_val *= 16777619; } return hash_val; } }; struct Comparer { size_t size; bool operator()(char* lhs, char* rhs) const { return (std::memcmp(lhs, rhs, size) == 0) ? true : false; } }; struct ArraySet { std::unordered_set&lt;char*, Hasher, Comparer&gt; set; ArraySet (size_t …
has comment: http://stackoverflow.com/comment/84787686
has comment: http://stackoverflow.com/comment/84787799
has comment: http://stackoverflow.com/comment/84786759
has comment: http://stackoverflow.com/comment/84790270
upvote count: 2
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84784997
accepted answer of: http://stackoverflow.com/q/48873995
type: Answer

http://stackoverflow.com/comment/84624961
type: QuestionComment
has text: Yes, If you read the help file for the `SET` command you would see the syntax plain as day. `SET [variable=[string]]`. No spaces.
score: 0
type: Comment
comment on: http://stackoverflow.com/q/48808460

http://stackoverflow.com/q/48858600
has body: a=np.arange(240).reshape(3,4,20) b=np.arange(12).reshape(3,4) c=np.zeros((3,4),dtype=int) x=np.arange(3) y=np.arange(4) I wanna get a 2d (3,4) shape array by the following step without loop. for i in x: c[i]=a[i,y,b[i]] c array([[ 0, 21, 42, 63], [ 84, 105, 126, 147], [168, 189, 210, 231]]) I tried, c=a[x,y,b] but it shows IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes (3,) (4,) (3,4) and then I also tried to establish newaxis by [:,None], it also doesn't work.
answer count: 2
tagged with: array-broadcasting
has answer: http://stackoverflow.com/a/48858686
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84720762
has title: IndexError: shape mismatch: indexing arrays could not be broadcast together with shapes
has comment: http://stackoverflow.com/comment/84721148
score: 1
upvote count: 1
type: Question
tagged with: numpy
tagged with: indexing
tagged with: arrays
has answer: http://stackoverflow.com/a/48858676

http://stackoverflow.com/comment/84795525
comment on: http://stackoverflow.com/q/48894311
type: Comment
type: QuestionComment
has text: I was missing a '\'. Its working now. I generated a merged PDF report with the each tables data separated into a page of its own. It is exactly what I required. Thank you for your help.
score: 0

http://stackoverflow.com/comment/84889043
comment on: http://stackoverflow.com/q/48936524
has text: pyrcc5 is part of PyQt5 https://pypi.python.org/pypi/pyqt5-tools
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84666530
score: 0
type: Comment
type: QuestionComment
has text: mmm, have you tried it on your pc?
comment on: http://stackoverflow.com/q/48830938

http://stackoverflow.com/comment/84674601
comment on: http://stackoverflow.com/q/48831728
score: 0
type: QuestionComment
has text: I know how to play a sound ( mp3, flac ... ) on my speaker ( the first audio device ) but i would like play sound on another device My English is corect ? :)
type: Comment

http://stackoverflow.com/q/48867924
answer count: 1
has answer: http://stackoverflow.com/a/48868512
favorite count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/85091844
tagged with: adaboost
tagged with: python
tagged with: sklearn-pandas
downvote count: 1
type: Question
has body: I have a set of football data in a database that I am trying to predict values for. import MySQLdb import pandas as pd from sklearn.feature_selection import RFE from sqlalchemy import create_engine import mysql.connector from matplotlib import pyplot mysql_cn= MySQLdb.connect(host='database.rds.amazonaws.com',port=3306,user='username', passwd='password', db='dev') games = pd.read_sql('SELECT game_id, game_date_id, home_team_id, away_team_id, referee_id, FTR, away_team_travel FROM dev.tmp_all_output_id WHERE game_id &lt; 6700;', con=mysql_cn) predict_games = pd.read_sql('SELECT game_id, game_date_id, home_team_id, away_team_id, referee_id, -10 AS FTR, away_team_travel FROM dev.tmp_all_output_id WHERE game_id &gt; 6700;', con=mysql_cn) feature_names = ['game_id', 'game_date_id', 'home_team_id', 'away_team_id', 'referee_id', 'away_team_travel'] X = games[feature_names] y = games['FTR'] # #Create Training and Test Sets and Apply Scaling from sklearn.model_selection import train_test_split validation_size = 0.20 seed = 7 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=validation_size, random_state=0) from sklearn.ensemble import AdaBoostClassifier ada = AdaBoostClassifier() ada.fit(X_train, y_train) predictions = ada.predict(X_test) print('Accuracy of AdaBoostClassifier on training set: {:.2f}'.format(ada.score(X_train, y_train))) print('Accuracy of AdaBoostClassifier on test set: {:.2f}'.format(ada.score(X_test, y_test))) #cnx = create_engine('mysql+mysqlconnector://username:password@database.rds.amazonaws.com:3306/dev', echo=False) #testResults.to_sql(name='tmp_all_output_prediction', con=cnx, if_exists = 'replace', index=False) mysql_cn.close() Once I have loaded my data set into a data frame and run a test_train_split and a fit on in, how do I predict values for an unseen data set and return the game_id's and the prediction values (FTR)? As you can see in the code, I have a table (tmp_all_output_id) where I select known result values into 'games' …
score: -1
has title: Python Sklearn Predicting values on an unseen data set
upvote count: 0

http://stackoverflow.com/a/48895887
has comment: http://stackoverflow.com/comment/84797664
has comment: http://stackoverflow.com/comment/84797692
score: 0
type: Answer
has body: This code evades the Session part of requests version with capital "S". Try to see if this works for you: import requests url = 'url' client = requests.session() # Retrieve the CSRF token first csrf = client.get(url).cookies['csrftoken'] login_data = dict(username=EMAIL, password=PASSWORD, csrfmiddlewaretoken=csrf, next='/') r = client.post(URL, data=login_data, headers=dict(Referer=url)) # Check if it worked? print r.status_code Perhaps its bugged at your install? EDIT1: try this: import requests from bs4 import BeautifulSoup client = requests.Session() headers = {'User-Agent': 'Mozilla/5.0'} url = 'url' soup = BeautifulSoup(client.get(url).text, "html.parser") csrf = soup.find(name="csrf")
answers question: http://stackoverflow.com/q/48893436
has comment: http://stackoverflow.com/comment/84797791
has comment: http://stackoverflow.com/comment/84797592

http://stackoverflow.com/a/48836652
score: 2
answers question: http://stackoverflow.com/q/48836596
has body: The reasons using the ? character in the pre-packaged Python IDLE shell fails, is because using the ? is specific to IPython: Typing ?word or word? prints detailed information about an object. If certain strings in the object are too long (e.g. function signatures) they get snipped in the center for brevity. This system gives access variable types and values, docstrings, function prototypes and other useful information.
downvote count: 0
upvote count: 2
type: Answer

http://stackoverflow.com/q/48837733
duplicate of: http://stackoverflow.com/q/26411994
tagged with: for-loop
linked to: http://stackoverflow.com/q/26411994
score: 0
has body: def loop(): for i in range (0,9): pass if i == 3: i = i +3 print(i) loop() Current output : 0 1 2 6 4 5 6 7 8 Expecting output: 0 1 2 6 7 8 9 Does this have to do something with the way stack frames are created in Python? Why doesn't the number of iterations reduce even though we increment i ?
has comment: http://stackoverflow.com/comment/84680177
answer count: 1
favorite count: 0
upvote count: 2
has title: Why aren't iterations skipped in a for loop when the loop variable is incremented?
accepted answer: http://stackoverflow.com/a/48837751
tagged with: python
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/920645
downvote count: 2
has answer: http://stackoverflow.com/a/48837751
tagged with: loops
type: Question

http://stackoverflow.com/comment/84785536
has text: So in Python, you are allowed to call a constructor of an object from its instance? I was expecting to see there Job(...) instead of self.job(...)
comment on: http://stackoverflow.com/a/48890073
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84859464
comment on: http://stackoverflow.com/q/48925289
score: 0
has text: what does the code in the question have to do with Excel?
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84917712
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48954337
has text: Then your virtualenv is probably borked - after the activation of `py1`, what do you get when running `python -V`, `pip -V` and `pip list --format=freeze | grep -i "django=\|mysqlclient="`?
score: 0

http://stackoverflow.com/a/48999836
score: 3
accepted answer of: http://stackoverflow.com/q/48892935
type: AcceptedAnswer
downvote count: 0
has body: The error seems to have been fixed in a unmerged branch of PyInstaller. More information can be found on the GitHub pull request conversation, but reinstalling PyInstaller using pip install https://github.com/bjones1/pyinstaller/archive/pyqt5_fix.zip fixed the style issue for me.
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/48892935

http://stackoverflow.com/a/48845348
type: Answer
has body: You could implement a dict-like class that does exactly that. class MultiDict: def __init__(self): self.dict = {} def __setitem__(self, key, value): try: self.dict[key].append(value) except KeyError: self.dict[key] = [value] def __getitem__(self, key): return self.dict[key] Here is how you can use it d = MultiDict() d['flow'] = 'flow' d['flow'] = 'wolf' d['flow'] # ['flow', 'wolf']
score: 2
upvote count: 2
answers question: http://stackoverflow.com/q/48845260
has comment: http://stackoverflow.com/comment/84694953
has comment: http://stackoverflow.com/comment/84694976
downvote count: 0

http://stackoverflow.com/q/48813968
tagged with: pipeline
has title: How to standardize only numerical columns in pipeline for machine learning?
tagged with: pandas
answer count: 1
downvote count: 0
tagged with: scikit-learn
favorite count: 0
has comment: http://stackoverflow.com/comment/84633301
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84634241
score: 2
linked to: http://stackoverflow.com/q/20109391
upvote count: 2
linked to: http://stackoverflow.com/q/48673402
tagged with: machine-learning
type: Question
has comment: http://stackoverflow.com/comment/84649592
has answer: http://stackoverflow.com/a/49231829
has comment: http://stackoverflow.com/comment/84649659
has comment: http://stackoverflow.com/comment/84634828
has body: I have data with numeric and categorical features; I would like to standardize the numerical features only. The columns of numerical values are captured in X_num_cols, however I am not sure how I can implement that into the Pipeline code, for example, make_pipeline(preprocessing.StandardScaler(columns=X_num_cols) doesn't work. I have found this on stackoverflow, but the answers don't fit my code layout/purpose. from sklearn import preprocessing from sklearn.pipeline import make_pipeline from sklearn.linear_model import LogisticRegression from sklearn.model_selection import train_test_split,GridSearchCV import pandas as pd import numpy as np # Separate target from training features y = df['MED'] X = df.drop('MED', axis=1) # Retain only the needed predictors X = X.filter(['age', 'gender', 'ccis']) # Find the numerical columns, exclude categorical columns X_num_cols = X.columns[X.dtypes.apply(lambda c: np.issubdtype(c, np.number))] # Split data into train and test sets X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=1234, stratify=y) # Pipeline pipeline = make_pipeline(preprocessing.StandardScaler(), LogisticRegression(penalty='l2')) # Declare hyperparameters hyperparameters = {'logisticregression__C' : [0.01, 0.1, 1.0, 10.0, 100.0], 'logisticregression__multi_class': ['ovr'], 'logisticregression__class_weight': ['balanced'] } # SKlearn cross-validation with pupeline clf = GridSearchCV(pipeline, hyperparameters, cv=10) Sample data is as follows: Age Gender CCIS 13 M 5 24 F 8

http://stackoverflow.com/comment/84833009
type: QuestionComment
type: Comment
has text: Maybe you can consider making a small interface.
score: 0
comment on: http://stackoverflow.com/q/48912898

http://stackoverflow.com/q/48946616
tagged with: smtp
has answer: http://stackoverflow.com/a/48948105
accepted answer: http://stackoverflow.com/a/48948105
score: 0
tagged with: email
tagged with: python
has title: Python: sending mail with SMTP (to Gmail) and can't encode headers properly
tagged with: gmail
type: AnsweredQuestion
has body: I have a following snipper of code, partly borrowed from the stackoverflow users: #!/usr/bin/env python # -*- coding: iso-8859-2 -*- def send_email(user, pwd, recipient, subject, body): import smtplib FROM = user TO = recipient if type(recipient) is list else [recipient] SUBJECT = subject TEXT = body # Prepare actual message message = """From: %s\nTo: %s\nSubject: =?iso-8859-2?Q?%s?=\n\n%s """ % (FROM, ", ".join(TO), SUBJECT, TEXT) print(message) try: server = smtplib.SMTP("smtp.gmail.com", 587) server.ehlo() server.starttls() server.login(user, pwd) server.sendmail(FROM, TO, message) server.close() print('successfully sent the mail') except: print("failed to send mail") sentence='Koń' send_email('login','pass','recipient@gmail.com',sentence.encode('iso-8859-2'),'test') And it sends an email from a gmail account to another gmail account, however when I log in to the gmail page, the subject displays as b'Ko\xf1' What am I doing wrong?
tagged with: character-encoding
has comment: http://stackoverflow.com/comment/84899565
type: Question
answer count: 1

http://stackoverflow.com/q/48916783
has comment: http://stackoverflow.com/comment/84846987
has comment: http://stackoverflow.com/comment/84918950
tagged with: python
tagged with: selenium-webdriver
tagged with: selenium-chromedriver
upvote count: 2
type: UnansweredQuestion
tagged with: selenium
downvote count: 1
type: Question
score: 1
has title: python/selenium/chromedriver TimeoutException
has body: I'm in the process of scraping pdfs from a website using selenium and chrome webdriver. I use the following, pulling the site from a list: driver.get(site) source = driver.page_source ... ... driver.quit() But I keep getting the following error, about 6,000 observations down my site list: Traceback (most recent call last): File "&lt;stdin&gt;", line 127, in &lt;module&gt; File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 323, in get self.execute(Command.GET, {'url': url}) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/webdriver.py", line 311, in execute self.error_handler.check_response(response) File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/remote/errorhandler.py", line 237, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.TimeoutException: Message: timeout (Session info: chrome=63.0.3239.84) (Driver info: chromedriver=2.33.506092 (733a02544d189eeb751fe0d7ddca79a0ee28cce4),platform=Linux 4.10.0-40-generic x86_64) I've tried refreshing the source page at shorter intervals (every 200 searches, but should I go shorter?). How do I extend selenium's 120sec timeout limit?
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84843054
has answer: http://stackoverflow.com/a/48920865

http://stackoverflow.com/comment/84689180
score: 0
comment on: http://stackoverflow.com/q/48842543
type: Comment
has text: Did you even read the error?
type: QuestionComment

import
type: Tag
tags question: http://stackoverflow.com/q/48840055
tags question: http://stackoverflow.com/q/48902763
tags question: http://stackoverflow.com/q/48820312
tag name: import
tags question: http://stackoverflow.com/q/48960049
tags question: http://stackoverflow.com/q/48894235
tags question: http://stackoverflow.com/q/48952692
tags question: http://stackoverflow.com/q/48849281
tags question: http://stackoverflow.com/q/48945739
tags question: http://stackoverflow.com/q/48884494
tags question: http://stackoverflow.com/q/48933845
tags question: http://stackoverflow.com/q/48906439
tags question: http://stackoverflow.com/q/48809516
tags question: http://stackoverflow.com/q/48857871
tags question: http://stackoverflow.com/q/48958633
tags question: http://stackoverflow.com/q/48889914
tags question: http://stackoverflow.com/q/48869198
tags question: http://stackoverflow.com/q/48923003
tags question: http://stackoverflow.com/q/48915230
tags question: http://stackoverflow.com/q/48889144
tags question: http://stackoverflow.com/q/48917140
tags question: http://stackoverflow.com/q/48887871

http://stackoverflow.com/comment/84871791
has text: @paul-panzer, what doest `(5)` stand for here?
type: AnswerComment
comment on: http://stackoverflow.com/a/48932462
score: 0
type: Comment

http://stackoverflow.com/a/48852141
type: Answer
score: 2
downvote count: 0
has body: Try to use prefetch_related to filter related data: from django.db.models import Prefetch class MyView(generics.ListAPIView): serializer_class = MySerializer def get_queryset(self): queryset = MyModel.objects.all() names = self.request.query_params.get('Simon', None) if names: queryset = queryset.filter(data__name__in=names.split(',')).prefetch_related(Prefetch('data', queryset=MyData.objects.filter(name__in=names.split(','))) return queryset Also you can use SerializerMethodField: class MyModelSerializer(serializers.ModelSerializer): data = SerializerMethodField() class Meta: model = MyModel fields = ('country', 'data',) def get_data(self, obj): names = self.context['request'].query_params.get('Simon', None) data = MyData.objects.filter(name__in=names.split(',')) data_serializer = MyDataSerializer(data, many=True) return data_serializer.data
answers question: http://stackoverflow.com/q/48852092
upvote count: 2

http://stackoverflow.com/comment/84643181
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48819435
has text: Sorry but I don't really understand by what an index or key exactly is? Like would I add an index=True under the column attributes? thanks!
score: 0

http://stackoverflow.com/q/48879633
tagged with: file
type: Question
has comment: http://stackoverflow.com/comment/84763607
has answer: http://stackoverflow.com/a/48879772
upvote count: 5
has comment: http://stackoverflow.com/comment/84772676
has body: I am trying to use: text = "★" file.write(text) In python 3. But I get this error message: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0: ordinal not in range(128) How can I print the symbol ★ in a file in python? This is the same symbol that is being used as star ratings.
has title: python: writing ★ in a file
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/6048085
favorite count: 0
accepted answer: http://stackoverflow.com/a/48879772
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84763543
tagged with: non-ascii-characters
score: 5
tagged with: python
has comment: http://stackoverflow.com/comment/84763237
type: AnsweredQuestion

http://stackoverflow.com/comment/84986693
type: Comment
has text: Means DF1 is having 250 rows and DF2 is having 230 rows.
type: AnswerComment
comment on: http://stackoverflow.com/a/48926933
score: 0

multi-index
tags question: http://stackoverflow.com/q/48861697
type: Tag
tags question: http://stackoverflow.com/q/48830485
tags question: http://stackoverflow.com/q/48868097
tags question: http://stackoverflow.com/q/48945380
tag name: multi-index
tags question: http://stackoverflow.com/q/48956286
tags question: http://stackoverflow.com/q/48843357
tags question: http://stackoverflow.com/q/48925474
tags question: http://stackoverflow.com/q/48953845
tags question: http://stackoverflow.com/q/48857303
tags question: http://stackoverflow.com/q/48817964
tags question: http://stackoverflow.com/q/48916912

wsgi
type: Tag
tags question: http://stackoverflow.com/q/48893546
tags question: http://stackoverflow.com/q/48894364
tags question: http://stackoverflow.com/q/48917810
tags question: http://stackoverflow.com/q/48844768
tags question: http://stackoverflow.com/q/48925318
tag name: wsgi

http://stackoverflow.com/comment/84894142
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48942663
has text: That sounds great but how would I do that?? I currently get the list from a database using: `list = News.objects.order_by('title')`. Is there a way to get that split up in groups of three?

http://stackoverflow.com/q/48825234
score: -1
possible better answer: http://stackoverflow.com/a/48825317
has comment: http://stackoverflow.com/comment/84654203
answer count: 2
has comment: http://stackoverflow.com/comment/84654232
downvote count: 1
linked to: http://stackoverflow.com/q/3270680
linked to: http://stackoverflow.com/q/20449427
favorite count: 0
has answer: http://stackoverflow.com/a/48825317
has answer: http://stackoverflow.com/a/48825337
accepted answer: http://stackoverflow.com/a/48825337
tagged with: python
type: AnsweredQuestion
upvote count: 0
has comment: http://stackoverflow.com/comment/84654161
has body: I tried to create a simple calculator using python. My code is this: def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x, y): return x * y def divide(x, y): return x / y invalid_input = True print("Available operations") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") choice = input("Choose one of the available operations:") if choice &gt;= '1' and choice &lt;= '4': num1 = int(input("First Number:")) num2 = int(input("Second Number:")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print ("invalid number") It works perfectly fine except of one thing. I assume the problem is here: if choice &gt;= '1' and choice &lt;= '4': When i enter 5, I get the invalid number output but when I enter a number like 12 or any number with 1,2,3 or 4 it goes inside the if and asks First number.I know how to fix it but I want to understand why this happens.Thanks in advance
type: Question
has title: Comparison operators error in Python
tagged with: if-statement

http://stackoverflow.com/comment/84820568
has text: There is no better way, though I question why you would want to leave one variable out. If your aim is to determine what variables would be important, you should take a look at sklearn's [feature selection](http://scikit-learn.org/stable/modules/feature_selection.html)
type: QuestionComment
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48906534

http://stackoverflow.com/comment/84759019
has text: @SamCraig This code example is _not_ reasonable. The amount of irrelevant comments and the function definition as such distract me from concentrating on the actual problem.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48877457
score: 0

http://stackoverflow.com/comment/84837029
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48804907
score: 0
has text: Precisely what expression are you using? As illustrated in the Jupyter notebook I referenced in my answer, there are consequences to each of the choices you might make in how you calculate this.

http://stackoverflow.com/comment/105491959
type: AnswerComment
type: Comment
score: 1
has text: Say I want to create *two* layers, where the weights in one layer are the transpose of the weights in the other layer. How could I do that?
comment on: http://stackoverflow.com/a/48953872

http://stackoverflow.com/comment/84632684
score: 0
type: AnswerComment
has text: @heemayl aahh thank you. I'm still very neeewbie at this.
comment on: http://stackoverflow.com/a/48814373
type: Comment

http://stackoverflow.com/q/48954337
has comment: http://stackoverflow.com/comment/84923373
has body: I am trying to get Django going with mySQL. I have started the app I can see all manage.py and other files. and in setting i changed: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'app', 'USERNAME': 'root', 'PASSWORD': 'root', 'HOST': 'localhost', } } I have installed mySQL separately, I have XAMPP I started it but when I run: python manage.py migrate I get the following errors: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 15, in &lt;module&gt; import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in &lt;module&gt; execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "&lt;frozen importlib._bootstrap&gt;", line 994, in _gcd_import File "&lt;frozen importlib._bootstrap&gt;", line 971, i…
has comment: http://stackoverflow.com/comment/85260642
has comment: http://stackoverflow.com/comment/84918146
has comment: http://stackoverflow.com/comment/84917394
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84936794
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84917712
has comment: http://stackoverflow.com/comment/84918234
answer count: 0
tagged with: mysql
tagged with: pip
has comment: http://stackoverflow.com/comment/84923479
has title: Getting traceback error on Django installation?
type: Question
has comment: http://stackoverflow.com/comment/84918464
has comment: http://stackoverflow.com/comment/84917499
score: 0

cryptography
tag name: cryptography
type: Tag
tags question: http://stackoverflow.com/q/48848668

http://stackoverflow.com/q/48933069
type: AnsweredQuestion
score: 1
has title: Django NoReverseMatch problems with get_absolute_url
has answer: http://stackoverflow.com/a/48933137
type: Question
has body: I know this probably the single most common Django problem there is, but I can't for the life of me figure this one out. I'll make it quick. # urls.py urlpatterns += [ path('certs/', views.certs, name='certs'), path('certs/&lt;int:id&gt;/', views.view_cert, name='view_cert'), ] - # views.py @login_required def certs(request): certs = Certification.objects.filter(user=request.user) return render(request, 'certs.html', {'certs': certs}) def view_cert(request, id): cert = Certification.objects.get(id=id) return render(request, 'view_cert.html', {'cert': cert}) - # certs.html {% if certs %} &lt;ul class="list-group"&gt; {% for cert in certs %} &lt;li class="list-group-item"&gt;{{ cert.name }}&lt;/li&gt; &lt;!--&lt;a href="{% url cert.get_absolute_url %}" class="list-group-item list-group-item-action"&gt;{{ cert.name }}&lt;/a&gt;--&gt; {% endfor %} &lt;/ul&gt; {% endif %} - # models.py class Certification(models.Model): ... def get_absolute_url(self): return reverse('crypto:view_cert', kwargs={'id': self.id}) The code works absolutely fine when i load /certs/1 for example. However when I try to load /certs (which should list a users certs), I get a NoReverseMatch. Reverse for '/certs/1/' not found. '/certs/1/' is not a valid view function or pattern name. What's even more confusing is that I can load it absolutely fine from shell: &gt;&gt;&gt; from django.urls import reverse &gt;&gt;&gt; reverse('crypto:view_cert', kwargs={'id': 1}) '/certs/1/' &gt;&gt;&gt; Anyone have any ideas?
upvote count: 1
answer count: 1
downvote count: 0
favorite count: 0
tagged with: python-3.x
tagged with: django
tagged with: python
accepted answer: http://stackoverflow.com/a/48933137

http://stackoverflow.com/comment/84717849
type: Comment
has text: @MdJohirulIslam I think the caffe-users is a public group? If so, you should be able to skip cookies and run just `./src/gggd.py -v caffe-users`
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48853513

http://stackoverflow.com/q/48865416
has body: I need to use sqlite version 3.8 or higher with python in Amazon Linux. I updated my sqlite installation to the latest version: $ sqlite3 -version 3.22.0 2018-01-22 18:45:57 0c55d179733b46d8d0ba4d88e01a25e10677046ee3da1d5b1581e86726f2171d I also updated my pysqlite version pip install --upgrade pysqlite However, my pysqlite still only seems to support sqlite version 3.7: $ python &gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; sqlite3.version '2.6.0' &gt;&gt;&gt; sqlite3.sqlite_version '3.7.17' &gt;&gt;&gt; &gt;&gt;&gt; from pysqlite2 import dbapi2 as sqlite &gt;&gt;&gt; sqlite.version '2.8.3' &gt;&gt;&gt; sqlite.sqlite_version '3.7.17' How can I update the sqlite python API to support a newer version of sqlite?
tagged with: pysqlite
type: Question
has answer: http://stackoverflow.com/a/65213377
has answer: http://stackoverflow.com/a/67672775
has answer: http://stackoverflow.com/a/51385365
has title: How to use the latest sqlite3 version in python
score: 15
has comment: http://stackoverflow.com/comment/100256100
has answer: http://stackoverflow.com/a/75462151
upvote count: 15
has comment: http://stackoverflow.com/comment/105141443
tagged with: sqlite
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 4
linked to: http://stackoverflow.com/q/29282380

exception
tags question: http://stackoverflow.com/q/48837130
tags question: http://stackoverflow.com/q/48821178
tags question: http://stackoverflow.com/q/48875563
tags question: http://stackoverflow.com/q/48850339
tags question: http://stackoverflow.com/q/48907073
tags question: http://stackoverflow.com/q/48838562
tags question: http://stackoverflow.com/q/48818571
tags question: http://stackoverflow.com/q/48884531
type: Tag
tags question: http://stackoverflow.com/q/48887232
tags question: http://stackoverflow.com/q/48902791
tag name: exception
tags question: http://stackoverflow.com/q/48811095
tags question: http://stackoverflow.com/q/48822642
tags question: http://stackoverflow.com/q/48874148

http://stackoverflow.com/comment/84612427
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48804756
has text: while you saying "another way" , what is that difference in both code ? adding `|` instead of grouping doesn't point to another way.

http://stackoverflow.com/a/48815450
upvote count: 3
has comment: http://stackoverflow.com/comment/84634877
accepted answer of: http://stackoverflow.com/q/48815365
has comment: http://stackoverflow.com/comment/84637193
score: 3
has body: from functools import reduce def path_lookup(my_dict, path): return reduce(lambda d, ks: d[ks], path, my_dict) print(path_lookup(myDict, ["main", "bar", "abc"])) # prints sit If you really want dictionaries to respond to tuple indexing as you indicate in your edit, you can make it happen by overriding __getitem__, but you probably don't want to do that.
has comment: http://stackoverflow.com/comment/84636894
type: AcceptedAnswer
downvote count: 0
answers question: http://stackoverflow.com/q/48815365
has comment: http://stackoverflow.com/comment/84634848
type: Answer

http://stackoverflow.com/comment/84906572
has text: I accepted Wiktor Stribiżew answer because it does not need to escape the string before use, but your solution is good too. +1
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48949852
type: AnswerComment

http://stackoverflow.com/q/48839504
score: 1
has comment: http://stackoverflow.com/comment/84683251
type: Question
has comment: http://stackoverflow.com/comment/84683292
linked to: http://stackoverflow.com/q/34803040
downvote count: 0
answer count: 1
has body: I was trying to install a package from pip but I have gotten that message: RuntimeError: aiohttp requires Python 3.4.2+ I have installed python 3.64 but it still gives me that error Thanks!
favorite count: 0
has comment: http://stackoverflow.com/comment/84685331
has title: How can I make pip to install to python 3.64 directory, instead of 2.7
has answer: http://stackoverflow.com/a/48839540
tagged with: python
tagged with: installation
type: UnansweredQuestion
tagged with: pip
upvote count: 1
has comment: http://stackoverflow.com/comment/84683173

http://stackoverflow.com/q/48906886
has comment: http://stackoverflow.com/comment/84819466
downvote count: 0
has comment: http://stackoverflow.com/comment/84819753
has body: I have written the following code and it's working: #!/usr/bin/python from os import system import ipaddress hostname = ipaddress.ip_address(str(input("Please Enter An IP Address : "))) response = system("ping -c 1 " + str(hostname)) if response ==0: print ("System is UP") else : print ("System is DOWN") While running the following command, I'm getting following results which are good but I don't need any gibberish output of ping. Please Enter An IP Address : 8.8.8.8 PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=64 time=0.039 ms --- 8.8.8.8 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.039/0.039/0.039/0.000 ms System is UP how can a I redirect following output in some other file or in dev/null: PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=64 time=0.039 ms --- 8.8.8.8 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 0.039/0.039/0.039/0.000 ms and only receive System is UP result as output by running the script. Please help.
tagged with: linux
answer count: 1
tagged with: python
favorite count: 0
has comment: http://stackoverflow.com/comment/84819769
has comment: http://stackoverflow.com/comment/84820062
tagged with: python-3.x
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84820044
upvote count: 1
has answer: http://stackoverflow.com/a/50408345
has title: Redirecting unwanted output in python3
score: 1
type: Question

http://stackoverflow.com/q/48819387
answer count: 1
accepted answer: http://stackoverflow.com/a/48822657
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has answer: http://stackoverflow.com/a/48822657
type: Question
has title: When posting to a Django form, are all fields posted?
tagged with: python
has body: I'm trying to write a test for a form to simulate the situation in which I'd like to update just one field. Here is the test: from django.test import TestCase from django.forms.models import model_to_dict class FamilyDemographicsUpdateTest(TestCase): def test_update_phone_types_with_fields_from_family_factory(self): # Create a family for which the employee uses an iPhone family = FamilyFactory(employee_phone_type=Family.IPHONE) url = reverse('dashboard:family', kwargs={'pk': family.id, 'tab': 'family-demographics'}) data = model_to_dict(instance=family, fields=FamilyDemographicsForm.base_fields) form = FamilyDemographicsForm(data=data) after which I drop into the debugger with import ipdb; ipdb.set_trace(). It is here that I notice that the form has errors: ipdb&gt; form.errors {'employee_email': ['This email is already taken.']} This can be traced back to the Family model on which the form is based. The form is a ModelForm: class FamilyDemographicsForm(forms.ModelForm): class Meta: model = Family The view is based on Django's generic UpdateView: class FamilyUpdate(SuccessMessageMixin, DashboardAccessMixin, UpdateView): template_name = 'families/edit.html' model = Family success_message = "Family was updated successfully." def get_form_class(self, **kwargs): tab = self.kwargs['tab'] if tab == 'family-demographics': return FamilyDemographicsForm and the corresponding Family object has a clean() method which is triggering this error (in class Family(models.Model)): def clean(self): if self.employee_email: db_user = User.objects.filter(username=self.employee_email).first() if db_user and db_user.family and db_user.family != self: raise ValidationError({'employee_email': 'This email is already taken.'}) if self.partner_email: db_user = User.objects.filter(username=self.partner_email).first() if db_user and db_user.family and db_user.family != self: raise ValidationError({'partner_email': 'This email is already taken.'}) However, if I actually use the form in the browser…
tagged with: django
upvote count: 1
has comment: http://stackoverflow.com/comment/84642963

http://stackoverflow.com/comment/84686634
comment on: http://stackoverflow.com/a/48841268
score: 0
type: AnswerComment
type: Comment
has text: but can it be done within for loop? The variable should take input even the user press enter or in the same line like in c,c++

http://stackoverflow.com/comment/84780904
type: Comment
has text: `sess.run([your normal gradient step])` will do `w = w - gradient` and `sess.run([your weight update ops])` will do `w = w - 1.0`. So eventually you are doing `w = w - gradient - 1`. Is that what you are trying to do about "aside from the weight update on each iteration, I would like to subtract some fixed value from my weight parameter."?
comment on: http://stackoverflow.com/a/48874511
type: AnswerComment
score: 0

http://stackoverflow.com/a/48907701
score: 2
has body: I think there is a clever way to do this in one pass, but a brute force solution is to just loop over the rows in the dataframe. For example: import pandas as pd # Sample input df = pd.DataFrame({ "id": [1, 2, 3, 4], "type": ["AP", "AP", "ES", "ES"], "start": [0, 3, 5, 12], "stop": [10, 7, 15, 18] }) df['count'] = 0 for row in df.itertuples(): mask = (row.start &lt;= df.stop) &amp; (row.stop &gt;= df.start) df.loc[row.Index, 'count'] = sum(mask) - 1 And we get id start stop type count 0 1 0 10 AP 2 1 2 3 7 AP 2 2 3 5 15 ES 3 3 4 12 18 ES 1
has comment: http://stackoverflow.com/comment/84823346
accepted answer of: http://stackoverflow.com/q/48907127
has comment: http://stackoverflow.com/comment/84823722
type: AcceptedAnswer
downvote count: 0
upvote count: 2
type: Answer
has comment: http://stackoverflow.com/comment/84822587
answers question: http://stackoverflow.com/q/48907127

http://stackoverflow.com/comment/84913604
has text: You still have to visit each character. How else can `split` find the right place to split? It visits each character until it finds the value you supplied.
comment on: http://stackoverflow.com/a/48951650
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/q/48817017
has title: NLP - Speed of Named Entity Recognition (StanfordNER)
score: 0
answer count: 1
tagged with: nlp
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48820290
upvote count: 1
tagged with: python
type: AnsweredQuestion
tagged with: named-entity-recognition
downvote count: 1
has comment: http://stackoverflow.com/comment/84640151
type: Question
has body: I'm doing Natural Language Processing (NLP) in Python 3 and more specifically Named Entity Recognition (NER) on the Harry Potter set of books. I'm using StanfordNER, which works pretty well but takes incredible amounts of time... I have done some research online on why it would be this slow but I can't seem to find anything that truly suits my code, and I honestly think the problem lays more in the (bad) way I have written the code. So here's what I wrote for now : import string from nltk.tokenize import sent_tokenize, word_tokenize import nltk.tag.stanford as st tagger = st.StanfordNERTagger('_path_/stanford-ner-2017-06-09/classifiers/english.all.3class.distsim.crf.ser.gz', '_path_/stanford-ner-2017-06-09/stanford-ner.jar') #this is just to read the file hp = open("books/hp1.txt", 'r', encoding='utf8') lhp = hp.readlines() #a small function I wrote to divide the book in sentences def get_sentences(lbook): sentences = [] for k in lbook: j = sent_tokenize(k) for i in j: if bool(i): sentences.append(i) return sentences #a function to divide a sentence into words def get_words(sentence): words = word_tokenize(sentence) return words sentences = get_sentences(lhp) #and now the code I wrote to get all the words labeled as PERSON by the StanfordNER tagger characters = [] for i in sentence: characters = [tag[0] for tag in tagger.tag(get_words(sentences[i])) if tag[1]=="PERSON"] print(characters) Now the problem, as I explained, is that the code takes huge amounts of time... So I'm wondering, is it normal or can I save time by rewriting the code in a better way ? If so, could you help me out ?
tagged with: stanford-nlp
has answer: http://stackoverflow.com/a/48820290

http://stackoverflow.com/comment/84836805
score: 1
type: AnswerComment
type: Comment
has text: That's exactly what it shows. Call `crawl` multiple times and `start` only once.
comment on: http://stackoverflow.com/a/48914428

http://stackoverflow.com/q/48858474
type: Question
has body: I am trying update a value in this selector (in a loop): df.loc[df['wsid']==w,col_name].iloc[int(lag)] Rebuild an example (inside the loop), will be: df.loc[df['wsid']==329,'stp_1'].iloc[0] I can print the value, but I don't know how to update it: df.loc[df['wsid']==329,'stp_1'].iloc[0] = 0 ??
possible better answer: http://stackoverflow.com/a/48858528
has comment: http://stackoverflow.com/comment/84756045
answer count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48858506
favorite count: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84790735
type: AnsweredQuestion
has title: How to update a value in a dataframe by a specific condition, a specific colum and a specific row?
score: 1
has answer: http://stackoverflow.com/a/48858528
upvote count: 1
accepted answer: http://stackoverflow.com/a/48858506

spacy
tags question: http://stackoverflow.com/q/48925328
tags question: http://stackoverflow.com/q/48875794
tag name: spacy
type: Tag
tags question: http://stackoverflow.com/q/48845016
tags question: http://stackoverflow.com/q/48827414
tags question: http://stackoverflow.com/q/48815411

http://stackoverflow.com/comment/84788965
score: 0
type: Comment
type: QuestionComment
has text: One thing you can do with locality sensitive hashing is basically hash all of your string (O(n)) and check if all the hashes are unique(O(n)). I would say bit sampling is probably a good choice here since you can tweak with the number of bits you sample. The only issue is it is based on hamming distance which is not exactly what you want.
comment on: http://stackoverflow.com/q/48819439

http://stackoverflow.com/comment/84896311
type: QuestionComment
has text: Thank ur reminding, I have updated the code. And the setting part is like ITEM_PIPELINES = { 'hello.pipelines.HelloPipeline': 1000, }
comment on: http://stackoverflow.com/q/48941220
type: Comment
score: 0

calendar
tags question: http://stackoverflow.com/q/48904779
tag name: calendar
type: Tag

http://stackoverflow.com/a/48835306
score: 1
answers question: http://stackoverflow.com/q/48835129
upvote count: 1
has comment: http://stackoverflow.com/comment/84676071
type: AcceptedAnswer
downvote count: 0
type: Answer
has body: There is the way s.unstack().stack(dropna=False).fillna(0) Out[774]: transaction_mm_yy ST_Email_Domain 2017-10 AOL.COM 0.0 GMAIL.COM 31.0 HOTMAIL.COM 2.0 MAIL.COM 3.0 OUTLOOK.COM 214.0 TSF.COM 9.0 YAHOO.COM 20.0 2017-11 AOL.COM 3.0 GMAIL.COM 14.0 HOTMAIL.COM 9.0 MAIL.COM 9.0 OUTLOOK.COM 14.0 TSF.COM 5.0 YAHOO.COM 62.0 dtype: float64 Another way is to using category data at the beginning tracking_df.ST_Email_Domain=tracking_df.ST_Email_Domain.astype('category') tracking_df.pivot_table(index=['transaction_mm_yy', 'ST_Email_Domain'], `columns='isFraud', values='order_number', aggfunc='count')
accepted answer of: http://stackoverflow.com/q/48835129
has comment: http://stackoverflow.com/comment/84676115

http://stackoverflow.com/a/48804975
has comment: http://stackoverflow.com/comment/84612928
answers question: http://stackoverflow.com/q/48804621
has comment: http://stackoverflow.com/comment/84613297
has body: For some reason, when you put them on the same window it doesn't work but separately try using this line (it worked for me): self.s.configure("colour.Horizontal.TProgressbar", foreground="green", background="green", theme = "clam") rather than: self.s.theme_use("clam") self.s.configure("colour.Horizontal.TProgressbar", foreground="green", background="green")
has comment: http://stackoverflow.com/comment/84612894
score: 0
has comment: http://stackoverflow.com/comment/84613259
has comment: http://stackoverflow.com/comment/84613508
has comment: http://stackoverflow.com/comment/84613538
type: Answer

http://stackoverflow.com/a/48818492
upvote count: 1
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48817792
has body: The solution is to make back a normal method. The parent can call methods of the child in the normal way. class Parent(object): def back(self): print("in parent.back()") self.change() class Child(Parent): def change(self): print("in child.change()") # create instance of child child = Child() # call the back function: child.back() The above code yields the following output: in parent.back() in child.change() If you prefer, you can make Parent.change() throw an error, to force the child to implement it: class Parent(object): ... def change(self): raise Exception("Child must implement 'change'") class MisfitChild(Parent): pass With the above, the following will throw an error: child = MisfitChild() child.back()
score: 1

http://stackoverflow.com/a/48893335
has comment: http://stackoverflow.com/comment/84829950
has body: I wrote a very brief prototype of a simple locality sensitive hashing algorithm in python. However there are a few caveats and you may want to optimize some pieces as well. I'll mention them when we see them. Assume all your strings are stored in strings. import random from collections import Counter MAX_LENGTH = 500 SAMPLING_LENGTH = 10 def bit_sampling(string, indices): return ''.join([string[i] if i&lt;len(string) else ' ' for i in indices]) indices = random.sample(range(MAX_LENGTH),SAMPLING_LENGTH) hashes = [bit_sampling(string, indices) for string in strings] counter = Counter(hashes) most_common, count = counter.most_common()[0] while count &gt; 1: dup_indices = [i for i, x in enumerate(hashes) if x == most_common] # You can use dup_indices to check the edit distance for original groups here. counter.pop(most_common) most_common, count = counter.most_common()[0] First of all, this is a slight variant of bit sampling that works best for the general hamming distance. Ideally if all your string are of the same length, this can give a theoretical probability bound for the hamming distance. When the hamming distance between two string is small, it is very unlikely that they will have different hash. This can be specified by the parameter SAMPLING_LENGTH. A larger SAMPLING_LENGTH will make it more likely to hash similar string to different hash but also reduce the probability of hashing not very similar string to the same hash. For hamming distance, you can calculate this trade-off easily. Run this snippet multiple times can increase your confident on no similar strings since each time you will sample different places. To accommodate your purpose to compare different length strings, one possible approach is to left padding space on shorter strings and make copies of them. Though all of the operation in this snippet are linear (O(n)), it may still consume significant memory and running time and it might be possible to reduce a constant factor. You might also want to …
has comment: http://stackoverflow.com/comment/84793126
upvote count: 4
has comment: http://stackoverflow.com/comment/84830399
has comment: http://stackoverflow.com/comment/84793553
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84795366
score: 4
has comment: http://stackoverflow.com/comment/84845084
has comment: http://stackoverflow.com/comment/84845373
has comment: http://stackoverflow.com/comment/84795432
has comment: http://stackoverflow.com/comment/84793517
has comment: http://stackoverflow.com/comment/84795174
has comment: http://stackoverflow.com/comment/84795479
has comment: http://stackoverflow.com/comment/84845301
type: Answer
accepted answer of: http://stackoverflow.com/q/48819439
has comment: http://stackoverflow.com/comment/84795409
has comment: http://stackoverflow.com/comment/84829672
answers question: http://stackoverflow.com/q/48819439

http://stackoverflow.com/comment/84817822
has text: what error are you getting?
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48904779
type: Comment

http://stackoverflow.com/comment/84674069
type: AnswerComment
type: Comment
has text: It's hard to tell for sure, but maybe it would be as simple as converting the `code` column to string: `... + df['code'].astype(str)`? Can you edit your question to add the `dtypes` of your columns?
comment on: http://stackoverflow.com/a/48833774
score: 0

http://stackoverflow.com/comment/84717854
type: QuestionComment
comment on: http://stackoverflow.com/q/48856989
type: Comment
has text: I did a little experiment and `__eq__` is definitely used by `in` for lists. The problem might be with your implementations of `__eq__` and `__ne__`.
score: 1

http://stackoverflow.com/comment/84840162
has text: @cᴏʟᴅsᴘᴇᴇᴅ "MSeifert's answer is based on the same principle: write a loop and then cythonize it, meaning you compile it to SIMD."... compile it to SIMD? What do you mean? Does Cython actually implicitly make use of SIMD intrinsics?
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48805093

http://stackoverflow.com/comment/84769088
type: Comment
comment on: http://stackoverflow.com/a/48873795
has text: Many thanks Rodriguez. The code is great. It is working!!
type: AnswerComment
score: 0

http://stackoverflow.com/q/48811171
has answer: http://stackoverflow.com/a/48812908
has comment: http://stackoverflow.com/comment/84626379
score: 0
has comment: http://stackoverflow.com/comment/84625782
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84658603
has comment: http://stackoverflow.com/comment/84649330
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84629375
has comment: http://stackoverflow.com/comment/84625809
linked to: http://stackoverflow.com/q/28218466
tagged with: python-3.x
has title: Use two separate versions of python in the same script
has comment: http://stackoverflow.com/comment/84625842
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84626357
tagged with: python
has comment: http://stackoverflow.com/comment/84625765
has answer: http://stackoverflow.com/a/48812750
has body: I have two blocks of code that I would like to combine into one python script. One block of code is written in Python 2.7, the other in Python 3.6 My question is, is there some way to call an old version of python mid script to run that specific block of code? For instance, if I ran the following code, the script would error out because the second print statement is missing the parenthesis: #Running python 2 and 3!! #Py 2 print "Python 2" #Py 3 print "Python 3" Note: Converting the block of code written in 2.7 is possible, but will take a very long time; Time that I do not have at the moment.
has comment: http://stackoverflow.com/comment/84625848

http://stackoverflow.com/q/48826287
has body: In my Django project I want to use Django Message ( from django.contrib import messages) to display error when user or email exist. Unfortunately my views not working. HTML: {% for message in messages %} &lt;p&gt;{{ message }}&lt;/p&gt; {% endfor %} views.py: def account_signup(request): if request.method == 'POST': nick = request.POST['nick'] email = request.POST['email'] password = request.POST['password'] user_model = get_user_model() if user_model.objects.filter(username__iexact=nick).exists(): messages.warning(request, 'Please correct the error below.') return render(request, "account/account_signup.html", context={'is_taken_email': email, 'messages': messages}) if user_model.objects.filter(email__iexact=email).exists(): messages.warning(request, 'Please correct the error below.') return render(request, "account/account_signup.html", context={'is_taken_email': email, 'messages': messages}) user = User.objects.create_user(username=nick, email=email, password=password) user.save() return HttpResponse(status=202) else: """Return template with sign up page.""" return render(request, "account/account_signup.html") I cant find a reason. Thanks in advance!
favorite count: 0
has comment: http://stackoverflow.com/comment/84656690
tagged with: python
has answer: http://stackoverflow.com/a/48826319
score: 2
has answer: http://stackoverflow.com/a/48826517
accepted answer: http://stackoverflow.com/a/48826517
downvote count: 0
tagged with: django
possible better answer: http://stackoverflow.com/a/48826319
type: Question
has comment: http://stackoverflow.com/comment/84656376
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84656334
upvote count: 2
answer count: 2
has title: Django Messages working only after manual page refresh when I try display error about existing user

http://stackoverflow.com/comment/117595230
score: 1
type: Comment
type: QuestionComment
has text: And how was all solved? I catch the same shit
comment on: http://stackoverflow.com/q/48868480

introspection
tags question: http://stackoverflow.com/q/48908406
tags question: http://stackoverflow.com/q/48865837
type: Tag
tag name: introspection

http://stackoverflow.com/comment/84725563
has text: the result im getting using sep="\t" is that they instead get rid of all the spaces inside the data, and the output becomes continuous and is loaded to a single column. So instead of 'asset 10904' it gives me 'asset10904'. My intended output is asset in (A,A) and 10904 in (A,B)
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48861071
type: Comment

http://stackoverflow.com/comment/84766692
type: QuestionComment
type: Comment
has text: @MatiasValdenegro I agree. But reducing the dimension any further means losing fine grain data, inturn taking a hit on accuracy. Any suggestions?
score: 0
comment on: http://stackoverflow.com/q/48880922

http://stackoverflow.com/q/48918008
type: Question
tagged with: opencv
has answer: http://stackoverflow.com/a/48920451
has body: I am trying to send a server request with the image keypoints and descriptor as a json object... here is my code.. import cv2 import requests import json imgDetail = {'keypoints': '', 'descriptor': ''} sift = cv2.xfeatures2d.SIFT_create() img = cv2.imread('images/query.jpg', 0) kp, des = sift.detectAndCompute(img, None) des = des.tolist() imgDetail['keypoints'] = kp imgDetail['descriptor'] = des jsonDump = json.dumps(imgDetail) resp = requests.post("http://localhost:5000", json=jsonDump, headers={'content-type': 'application/json'}) but its giving me the following error........... Traceback (most recent call last): File "E:/python projects/mawa/image.py", line 23, in &lt;module&gt; jsonDump = json.dumps(imgDetail) File "E:\Programs\Python\Python36\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "E:\Programs\Python\Python36\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "E:\Programs\Python\Python36\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "E:\Programs\Python\Python36\lib\json\encoder.py", line 180, in default o.__class__.__name__) TypeError: Object of type 'KeyPoint' is not JSON serializable Can anyone give a solution for this?
score: 1
has title: Object of type 'KeyPoint' is not JSON serializable opencv
tagged with: http://stackoverflow.com/tag/json
tagged with: keypoint
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48920451
tagged with: python
type: AnsweredQuestion
tagged with: sift
upvote count: 1

http://stackoverflow.com/q/48889709
type: UnansweredQuestion
upvote count: 1
tagged with: timeserieschart
score: 1
type: Question
downvote count: 0
has title: Calculate in Python 2.7 correct MACD and RSI indexes as they appear in binance web interface
answer count: 1
favorite count: 0
tagged with: moving-average
tagged with: finance
has answer: http://stackoverflow.com/a/48893527
tagged with: python
tagged with: trading
has body: I've been trying to compute and plot the prices, MACD and RSI indexes from cryptocoins on Binance (data obtained with this package), but I'm afraid either my indexes are not accurate or Binance is using different algorithms. I've been using the MACD and RSI functions from Matplotlib tutorial, which yield the same results as other algorithms I found elsewhere, so the algorithm should be accurate but I get the wrong results (as you can see from comparing the plots). In particular, the RSI seems to be correct, but the MACD (and the MACD and signal lines) are different from those displayed by the binance website trading view (see the pics) what am I doing wrong? #!/usr/bin/python # -*- coding: utf8 -*- import numpy as np import matplotlib.pyplot as plt ###### data prices = np.array([ 0.00061422, 0.00061422, 0.00061593, 0.00061672, 0.0006161 , 0.00061233, 0.000615 , 0.00061305, 0.00061346, 0.00061417, 0.00061428, 0.00061418, 0.0006115 , 0.00061203, 0.0006125 , 0.00061295, 0.00061296, 0.00061295, 0.00061242, 0.00061144, 0.00060874, 0.00060661, 0.00060512, 0.00060931, 0.000611 , 0.0006129 , 0.00061296, 0.000613 , 0.00061138, 0.0006115 , 0.0006123 , 0.0006123 , 0.00061288, 0.00061494, 0.000615 , 0.0006146 , 0.00061488, 0.00061399, 0.00061285, 0.0006129 , 0.0006129 , 0.00061291, 0.0006134 , 0.00061338, 0.00061355, 0.0006139 , 0.00061475, 0.0006167 , 0.0006158 , 0.000617 , 0.00061638, 0.00061452, 0.0006164 , 0.00061641, 0.00061646, 0.00061898, 0.0006198 , 0.00061818, 0.00061922, 0.00061979, 0.00061977, 0.00061924, 0.00061626, 0.00061488, 0.000616 , 0.000616 , 0.00061693, 0.0006165 , 0.0006165 , 0.00061699, 0.00061685, 0.00061687, 0.00061691, 0.000617 , 0.00061784, 0.00061899, 0.0006177 , 0.000617 , 0.00061732, 0.0006176 , 0.0006174 , 0.00061739, 0.00061739, 0.00061794, 0.0006185 , 0.0006185 , 0.00061785, 0.00061735, 0.00061743, 0.00061742, 0.00061429, 0.0006152 , 0.00061451, 0.00061514, 0.0006143 , 0.000614 , 0.0006154 , 0.0006148 , 0.00061444, 0.00061572]) ###### functions d…

http://stackoverflow.com/comment/84671238
has text: my mean is a 2D array @EspoirMurhabazi like this : `[ [1,1,1] , [2,2,2] , [3,3,3] ]`
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48833374
score: 0

http://stackoverflow.com/comment/84634492
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48814579
score: 3
has text: `<(...)` is not part of the POSIX standard; you need to run the script with `bash`, not `sh`. Use the `subprocess` module, not `os.system`.

http://stackoverflow.com/q/48811564
answer count: 1
tagged with: wxpython
has comment: http://stackoverflow.com/comment/84639189
has comment: http://stackoverflow.com/comment/84639180
score: 0
tagged with: python
has comment: http://stackoverflow.com/comment/84628941
tagged with: installation
has comment: http://stackoverflow.com/comment/84631328
has answer: http://stackoverflow.com/a/48816266
accepted answer: http://stackoverflow.com/a/48816266
type: AnsweredQuestion
has title: How to install wxpython in Xubuntu 17.10
type: Question
has body: I have been trying for two days to get wxpython installed and working for python3, to no avail. I have tried a range of installation methods, including building from source. It appears to be installed ok for python2, but in python3 I cannot import wx. Here's my most recent attempt. I wonder what I am missing... 15 Feb 15:20 /~ ⋄ lsb_release -r Release: 17.10 15 Feb 15:20 /~ ⋄ uname -a Linux j-asus 4.13.0-32-generic #35-Ubuntu SMP Thu Jan 25 09:13:46 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux 15 Feb 15:21 /~ ⋄ sudo apt install python-wxgtk3.0 [sudo] password for john: Reading package lists... Done Building dependency tree Reading state information... Done The following packages were automatically installed and are no longer required: linux-headers-4.10.0-19 linux-headers-4.10.0-19-generic linux-image-4.10.0-19-generic linux-image-extra-4.10.0-19-generic linux-signed-image-4.10.0-19-generic Use 'sudo apt autoremove' to remove them. The following additional packages will be installed: libwxbase3.0-0v5 libwxgtk3.0-0v5 python-wxversion Suggested packages: wx3.0-doc The following NEW packages will be installed libwxbase3.0-0v5 libwxgtk3.0-0v5 python-wxgtk3.0 python-wxversion 0 to upgrade, 4 to newly install, 0 to remove and 0 not to upgrade. Need to get 10.2 MB of archives. After this operation, 49.1 MB of additional disk space will be used. Do you want to continue? [Y/n] y Get:1 http://gb.archive.ubuntu.com/ubuntu artful/universe amd64 libwxbase3.0-0v5 amd64 3.0.3.1+dfsg2-1 [954 kB] Get:2 http://gb.archive.ubuntu.com/ubuntu artful/universe amd64 libwxgtk3.0-0v5 amd64 3.0.3.1+dfsg2-1 [4,180 kB] Get:3 http://gb.archive.ubuntu.com/ubuntu artful/universe amd64 python-wxversion all 3.0.2.0+dfsg-5 [12.4 kB] Get:4 http://gb.archive.ubuntu.com/ubuntu artful/universe amd64 python-wxgtk3.0 amd64 3.0.2.0+dfsg-5 [5,068 kB] Fetched 10.2 MB in 15s (672 kB/s) Selecting previously unselected package libwxbase3.0-0v5:amd64. (Reading database ... 229424 files and directories currently instal…

http://stackoverflow.com/a/48950607
answers question: http://stackoverflow.com/q/48830551
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48830551
type: Answer
has body: Ok guys I solved it! I found the solution here: https://www.raspberrypi.org/forums/viewtopic.php?t=63419 Connections as follows: Pi 5V to device 5V Pi ground to device ground Pi ground to device mode Pi TX to device RX Then configure the Pi serial link to 9600. stty -F /dev/ttyAMA0 9600 Then use echo to send commands to the device. The first byte is the device address (0 - 15). The second byte is a command. To change the device from address 0 to address 5 use echo -ne "\x00\xA0\x00\xAA\x00\xA5\x00\x05" >/dev/ttyAMA0 To change the device from address 5 back to address 0 use echo -ne "\x05\xA0\x05\xAA\x05\xA5\x05\x00" >/dev/ttyAMA0 All the details are in the docs you linked.

http://stackoverflow.com/q/48957960
has title: how to read multiple elements in xml in sequence with python
tagged with: python
tagged with: http://stackoverflow.com/tag/xml
type: UnansweredQuestion
has body: I have a xml files in this format: aaaaa bbbbb ccccc cccc ddddd how could I extract the text from those elements in order to be : aaaaa bbbbb ccccc ddddd
type: Question
score: 0
has answer: http://stackoverflow.com/a/48958068
answer count: 1

http://stackoverflow.com/comment/84638116
type: Comment
type: QuestionComment
has text: Juanpa, you are right, that is the reason. Thanks for the quick response!
comment on: http://stackoverflow.com/q/48816914
score: 0

http://stackoverflow.com/a/48899993
answers question: http://stackoverflow.com/q/48899783
has body: If you simply want the td in the document, without regard of the table, you can simply do: list_of_cells = [] for cell in page_soup.find_all('td'): text = cell.text.strip() if text.endswith('%'): list_of_cells.append(text) As for the error message regarding table, the ResultSet is like a list - you have to use individual items within it, such as through a for-loop. list_of_cells = [] for tab in table: for cell in tab.find_all('td'): text = cell.text.strip() if text.endswith('%'): list_of_cells.append(text) Note that this may skip the top level tags.
has comment: http://stackoverflow.com/comment/84805952
has comment: http://stackoverflow.com/comment/84805874
score: 0
type: Answer

http://stackoverflow.com/a/48929722
downvote count: 0
answers question: http://stackoverflow.com/q/48929281
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84867628
has comment: http://stackoverflow.com/comment/84866987
has body: Do it analytically: def cumm_sum(start, finish, steps, k): step = (finish - start) / steps pop = (finish - k) / step return (pop + 1) * 0.5 * (k + finish) and the call would be like: pick = ten_million[random.randint(0, 10000000)] result = cumm_sum(0.0, 1.0, 10000000, pick)
score: 1

http://stackoverflow.com/q/48900858
answer count: 1
has comment: http://stackoverflow.com/comment/84807110
has title: Issue when extending a matrix-like numpy array by adding extra list
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48901176
type: Question
tagged with: numpy
has body: I wrote the following code that does: (1) Generate root matrix of shape (3, 16), and (2) Generate 1000 binary vectors C such that each vector is added at the end of the root matrix iteratively one at a time. The code is the following (python 2.7): # STEP1: Generate root matrix root = [random.randint(0, 2 ** 16 - 1) for _ in range(16 - 1)] root = [('{0:0' + str(16) + 'b}').format(x) for x in root] root = np.asarray([list(map(int, list(x))) for x in root], dtype=np.uint8) # STEP2: Generate 1000 binary vectors C = [random.randint(0, 2 ** 16 - 1) for _ in range(1000)] C = list(set(C)) C = [('{0:0' + str(16) + 'b}').format(x) for x in C] C = np.asarray([list(map(int, list(x))) for x in C], dtype=np.uint8) # Step3: For each vector of C, append it at the end of root matrix for i in range(1000): batch = root[i:(i + (len(root)))] batch = np.append(batch, C[i]) print(batch) # Continue to process batch after being extended by adding a new vector The matrix C looks like this: [[0 1 1 ..., 0 1 1] [1 0 1 ..., 1 0 1] [0 1 0 ..., 1 1 0] ..., [1 1 0 ..., 1 0 0] [0 0 1 ..., 1 1 0] [1 1 1 ..., 1 1 1]] The problem is that np.append(batch, C[i])merges all vectors into a single one but this is not what I want. My goal is to extend the root matrix from (3, 16) to be (4,16) by just adding a vector C[i] iteratively. How can I achieve that? Thank you
accepted answer: http://stackoverflow.com/a/48901176
tagged with: python-2.7
score: 0

http://stackoverflow.com/q/48826653
type: Question
has answer: http://stackoverflow.com/a/48826730
upvote count: 0
has comment: http://stackoverflow.com/comment/84656897
has body: I have written this code to write the date in a csv file (excel sheet) the code has no error but the date is not shown in the excel I need a read function but I don't know how and where in the code to use it. date=["16.02.2018", "blah"] CSVreport = open('indata.csv', 'wb') wr = csv.writer(CSVreport) with open('indata.csv', 'w+') as CSVreport: wr = csv.writer(CSVreport) wr.writerow(date) CSVreport.close() Can anyone help me?
has comment: http://stackoverflow.com/comment/84656952
answer count: 1
favorite count: 0
tagged with: python-3.x
type: UnansweredQuestion
has title: date writing in csv file
score: -3
tagged with: python
downvote count: 3

http://stackoverflow.com/q/48852867
favorite count: 0
type: UnansweredQuestion
tagged with: legend
tagged with: python
has body: I have a graph in which the width of the edge is decided based on the size of the node. The nodes represent mails from an IMAP server. I am unable to get the corresponding line symbol in the legend item. The following code runs and shows the legend item description but not the legend. import pyqtgraph as pg w = pg.GraphicsWindow() v = w.addViewBox() v.setAspectLocked() lines = np.array((244, 66, 131, 255, 1),dtype=[('red',np.ubyte), ('green',np.ubyte), ('blue',np.ubyte), ('alpha',np.ubyte), ('width',float)]) curve1 = pg.mkPen(pen=lines) legend = pg.LegendItem(size=(10,10)) legend.addItem(curve1, name='0-10 kB') legend.setParentItem(v) legend.anchor((0,0), (0,0)) It says: "AttributeError:'QPen' object has no attribute 'opts'". Can anyone point out what I am doing wrong here?
has title: Unable to get the symbol of legend item in PyQtGraph
has comment: http://stackoverflow.com/comment/84712335
has comment: http://stackoverflow.com/comment/84717670
answer count: 0
score: 1
upvote count: 1
tagged with: pyqtgraph
type: Question
downvote count: 0

http://stackoverflow.com/a/48847576
has body: VSCode shows you an error because of "pylint". This is just a linter telling you that there is an error. I have got same problem when using OpenCV. There are some other posts that suggests we need to include it to whitelist. https://github.com/PyCQA/pylint/issues/1465
answers question: http://stackoverflow.com/q/48847515
type: Answer
upvote count: 1
score: 1
downvote count: 0

http://stackoverflow.com/q/48837841
type: Question
tagged with: python
score: -1
downvote count: 2
upvote count: 1
answer count: 1
has answer: http://stackoverflow.com/a/48837854
has title: No handlers could be found for logger 'matplotlib.lengend'
tagged with: matplotlib
type: UnansweredQuestion
has body: import numpy as np import matplotlib.pyplot as plt X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) plt.plot(X, S, color = 'green', linewidth = 1.0, linestyle = '-') plt.plot(X, C, color = 'blue', linewidth = 1.0, linestyle = '-') plt.xlim(-4.0, 4.0) plt.xticks(np.linspace(-4, 4, 9, endpoint=True)) plt.ylim(-1.0, 1.0) plt.yticks(np.linspace(-1, 1, 5, endpoint=True)) plt.legend(loc = 'upper left', frameon = False) plt.show() When I run this python code I see the plots but not the legend and get the output as: No handlers could be found for logger "matplotlib.legend"
favorite count: 0

http://stackoverflow.com/comment/84848260
type: Comment
type: QuestionComment
has text: how does df1 enter into this picture?
comment on: http://stackoverflow.com/q/48921011
score: 0

http://stackoverflow.com/a/48931292
has body: This is one way. df.loc[(df["D"] == "Monday") &amp; (df["B"] - df["C"]).dt.days.isin({-7, -8})] # A B C D # 1 aeg 2012-12-28 2013-01-04 Monday # 4 feh 2012-07-26 2012-08-03 Monday # 5 dd 2012-06-22 2012-06-30 Monday
type: AcceptedAnswer
downvote count: 0
type: Answer
accepted answer of: http://stackoverflow.com/q/48930681
answers question: http://stackoverflow.com/q/48930681
score: 1
upvote count: 1

http://stackoverflow.com/comment/84758268
type: Comment
has text: There is a Unix utility, `strings`, which scans a file, which can be a binary file, and outputs the strings it finds. You could use that, and even use your system's `grep`, to speed up your operation a bit and consume less memory: `strings input.txt` or with grep, `strings input.txt | grep "^attr \d"`. (I don't know the best regular expression on the command line without researching it more.) You'd need to use Shellwords.escape for quoted strings passed to the command line, doing `require shellwords` first.
score: 0
comment on: http://stackoverflow.com/a/48870448
type: AnswerComment

http://stackoverflow.com/q/48928347
tagged with: coreml
answer count: 1
type: UnansweredQuestion
tagged with: machine-learning
tagged with: python
has title: Custom MLModel File
tagged with: coremltools
type: Question
tagged with: ios
has body: I am new with machine learning and want to do following implementation Want to create a custom .mlmodel with input of "xls or csv or nsdata of this files" and output should be double or array. Pythone file should be able to read input data because i am going to use train_data from this input. Pythone will do some calculation on this input data and provide prediction on this (i will do this calculation using sklearn,LinearRegression) Can any one please help me how i can do this ?
has answer: http://stackoverflow.com/a/49052402
score: 0

http://stackoverflow.com/q/48863091
upvote count: 1
has answer: http://stackoverflow.com/a/62487485
answer count: 1
has comment: http://stackoverflow.com/comment/84729596
tagged with: chaining
has comment: http://stackoverflow.com/comment/84729839
favorite count: 0
has comment: http://stackoverflow.com/comment/84729313
has title: PEP8 Chained Methods
has comment: http://stackoverflow.com/comment/84730081
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/4768941
tagged with: python
has body: Goal: make the following function PEP8 compliant. The second line is too long (>79 chars) and needs to be split up. def a_function(): gdf_out = gdf_out.set_index(['level_0', 'level_1']).set_geometry('geometry') This is a chained method. Following another answer results in: def a_function(): gdf_out = ( gdf_out.set_index(['level_0', 'level_1']) .set_geometry('geometry') ) However this seems a bit odd to me, especially the indentation. Is there a better practice for chained commands in python PEP8? What about this? def a_function(): gdf_out = (gdf_out.set_index(['level_0', 'level_1']) .set_geometry('geometry'))
downvote count: 0
has comment: http://stackoverflow.com/comment/84730969
has comment: http://stackoverflow.com/comment/84729998
score: 1
has comment: http://stackoverflow.com/comment/84730216
has comment: http://stackoverflow.com/comment/84729449
type: Question
has comment: http://stackoverflow.com/comment/84729727
tagged with: pep8
has comment: http://stackoverflow.com/comment/84730346
linked to: http://stackoverflow.com/q/8683178

http://stackoverflow.com/comment/84808773
type: QuestionComment
comment on: http://stackoverflow.com/q/48901566
score: 0
has text: There is a contradiction here: *"which writes 8 bits for every 1 or 0"*, versus *"the same number of bits as the number of 1's and 0's"*. Is it 8 bits per 0/1, or is it 1 bit per 0/1? If the latter, how do you plan to deal with the left over when you cannot fill a whole byte with bits?
type: Comment

http://stackoverflow.com/a/48955976
has body: xls is not a text format, it's binary. There are apparently a number of bytes in the file that are equivalent to the ASCII newline character, but that will have no relation to how many rows there are in the spreadsheet.
score: 3
type: AcceptedAnswer
upvote count: 3
answers question: http://stackoverflow.com/q/48955851
type: Answer
has comment: http://stackoverflow.com/comment/84918865
accepted answer of: http://stackoverflow.com/q/48955851
downvote count: 0

axes
tag name: axes
type: Tag
tags question: http://stackoverflow.com/q/48858854

http://stackoverflow.com/q/48860117
downvote count: 0
answer count: 1
has answer: http://stackoverflow.com/a/48895109
favorite count: 0
has comment: http://stackoverflow.com/comment/84723644
score: 6
has body: Does anyone know why this gives a PerformanceWarning? d=pd.DataFrame( [ [1,2,3], [1,2,4], [1,None,5], [2,3,5], ], columns=['i','j','k'] ) print d.dtypes d = d.set_index(['i','j'])['k'] d = d.sort_index() print d.loc[(2,3)] # PerformanceWarning: indexing past lexsort depth may impact performance. My understanding from the docs is that the PerformanceWarning follows from not sorting the index (the index was sorted).
has title: Why PerformanceWarning when indexed lookup on sorted index?
tagged with: python
upvote count: 6
has comment: http://stackoverflow.com/comment/84723513
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84746073
accepted answer: http://stackoverflow.com/a/48895109
has comment: http://stackoverflow.com/comment/84723730
type: Question
has comment: http://stackoverflow.com/comment/84723536
tagged with: pandas

http://stackoverflow.com/comment/84859784
type: Comment
type: QuestionComment
has text: @AntiMatterDynamite There is discussion: [How do I ask and answer homework questions?](https://meta.stackoverflow.com/q/334822/5358968)
score: 1
comment on: http://stackoverflow.com/q/48926642

http://stackoverflow.com/q/48959884
has answer: http://stackoverflow.com/a/48959967
type: Question
has body: I have a DataFrameGroupBy object called 'grouped' that looks like this: for key, item in grouped: print('key: {0}, value: {1}'.format(key, grouped.get_group(key))) key: 9909, value: date quantity 0 2018-01-28 00:00:00+00:00 2.3 1 2018-01-29 00:00:00+00:00 3.0 key: 1151, value: date_period quantity 2 2018-01-28 00:00:00+00:00 5.0 3 2018-01-29 00:00:00+00:00 9.0 I am trying to turn this into a dataframe that looks like this: id, day1, day2 9909 2.3 3.0 1151 5.5 9.0 When I run the following: item_df = grouped.to_frame() I get the following error: 'DataFrameGroupBy' object has no attribute 'to_frame' When I run the following df = grouped.reset_index(inplace=True) I get the following: Cannot access callable attribute 'reset_index' of 'DataFrameGroupBy' objects, try using the 'apply' method. The DataFrameGroupBy object that I am trying to reformat was created from a dataframe like this: data = {'created_date': ['2018-01-22 12:40:03', '2018-01-22 13:40:03', '2018-01-23 15:00:05', '2018-01-26 14:30:04'], 'quantity': [11, 21, 23, 12], 'id': ['543', '543', '842', '543']} df = pd.DataFrame(data, columns = ['created_date', 'quantity' , 'id']) df.index = df['created_date'] df.index = pd.to_datetime(df.index) g = df.groupby('id').resample('D')['quantity'].sum() df = g.to_frame() dates = pd.date_range(df.index.levels[1].min(), g.index.levels[1].max()) idx = pd.MultiIndex.from_product([df.index.levels[0], dates]) df= df.reindex(idx, fill_value=0) df = df.fillna(0) df.reset_index(inplace=True) df.rename(columns={'level_0': 'id', 'level_1': 'date'}, inplace=True) grouped = df.groupby('id') #now to pivot this groupby object...
tagged with: pandas-groupby
tagged with: pandas
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48959967
tagged with: python
upvote count: 3
has title: Pivot a DataFrameGroupBy panadas object
type: AnsweredQuestion
score: 3

http://stackoverflow.com/q/48844322
has answer: http://stackoverflow.com/a/48844500
favorite count: 0
has answer: http://stackoverflow.com/a/48844552
accepted answer: http://stackoverflow.com/a/48844552
tagged with: pandas
has title: Shifting certain rows to the left in pandas dataframe
has body: I have a pandas database of some sports data. The columns are name, age, birth city, birth country, rookie, weight, and problem. The original data had birthcity as "City,State" for American players, so when I used a comma delimiter the result was two variables. So now all the American players are shifted over, and I needed to make a "Problem" variable to account for the excess. How can I shift just the Americans over to the left across thousands of observations? Thanks! What I have (please excuse the table formatting): Name Age BirthCity BirthCountry Rookie Weight Problem Frank 32 Seattle WA USA N 200 Jake 24 Geneva Switzerland Y 210 Desired: Name Age BirthCity BirthCountry Rookie Weight Frank 32 Seattle USA N 200 Jake 24 Geneva Switzerland Y 210
tagged with: shift
tagged with: python
possible better answer: http://stackoverflow.com/a/48844500
type: AnsweredQuestion
tagged with: database
type: Question
tagged with: numpy
answer count: 2
downvote count: 2
has comment: http://stackoverflow.com/comment/84694690
upvote count: 6
score: 4

http://stackoverflow.com/q/48847264
tagged with: input
tagged with: python
type: AnsweredQuestion
upvote count: 3
has title: Filtering csv file based on user input with python
has body: I have a large data base that looks like this: id, Start Time, End Time 0, 2017-01-01 00:00:21, 2017-01-01 00:11:41 1, 2017-01-01 00:00:45, 2017-01-01 00:11:46 2, 2017-02-01 00:00:57, 2017-02-01 00:22:08 3, 2017-03-01 00:01:10, 2017-03-01 00:11:42 4, 2017-01-01 00:01:51, 2017-01-01 00:12:57 Using pandas would probably be easier to do this, but I don't have much experience with it. I have researched modules such as arrow and datetime and would like to filter the data based on the user's input. Using that input, the user is returned filtered data. For example: def get_month('data.csv'): month = input('\nWhich month? January, February, March, April, May, or June?\n') date = '1 ' + month + ', 2017' with open(city_data, 'r') as fin, open('userdata.csv', 'w') as fout: writer = csv.writer(fout, delimiter=' ') for row in csv.reader(fin, delimiter=' '): if row[0] == arrow.get(date,'D MMMM, YYYY').format('YYYY-MM-DD'): return writer.writerow(row) Am I approaching this correctly? I think I may be going in the wrong direction in the date = '1 ' + month + ', 2017' part. Is there a way I could filter the data with just an input like January?
accepted answer: http://stackoverflow.com/a/48847399
type: Question
tagged with: pandas
score: 3
answer count: 1
downvote count: 0
linked to: http://stackoverflow.com/q/9847213
favorite count: 0
has answer: http://stackoverflow.com/a/48847399
tagged with: http://stackoverflow.com/tag/csv
tagged with: datetime

http://stackoverflow.com/comment/84823984
type: AnswerComment
type: Comment
has text: This is a "sunny weather raincoat": `with contextlib.contextmanager(lambda: (yield))(): raise Exception` fails with `RuntimeError: generator didn't yield`.
comment on: http://stackoverflow.com/a/48908462
score: 0

http://stackoverflow.com/a/48806579
type: AcceptedAnswer
upvote count: 3
type: Answer
answers question: http://stackoverflow.com/q/48806085
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48806085
score: 3
has body: Cassandra and CQL know a blob type which is probably what you want. See: https://docs.datastax.com/en/archived/cassandra/1.2/cassandra/tools/use_about_data_types_c.html You are transcoding the binary data with bin_data=bin_data.decode('latin-1').encode("utf-8") which should not be necessary at all. On top print (data.encode("utf-8").encode('latin-1')) shows two encode calls. Edit: found a test from the DataStax driver using blob here https://github.com/datastax/python-driver/blob/master/tests/integration/standard/test_types.py s.execute("CREATE TABLE blobbytes2 (a ascii PRIMARY KEY, b blob)") params = ['key1', bytearray(b'blob1')] s.execute("INSERT INTO blobbytes2 (a, b) VALUES (%s, %s)", params)

http://stackoverflow.com/comment/84642601
score: 1
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48818861
has text: @GeneBurinsky. Short answer- I was too lazy to check for in-place operations :) - but i'll update.

http://stackoverflow.com/a/48833464
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48833374
has body: numpy.where() is pretty cool. You could do the following: V[:,:] = np.where(V+50 &lt; 255, V+50, 255)
downvote count: 0
type: Answer

http://stackoverflow.com/a/48993102
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84991420
type: Answer
has body: Thanks to jezrael for your useful input. Builiding up on it, I've written a solution to the problem: apply a complex function that takes two or more arrays as input and return a single value and apply it to a dataframe with hierarchical column names together with resample based on datetime indexing. First, here is the table that I will use for the example mat = np.random.randint(0, 101, size = (10, 6)) index = pd.date_range(start = '25 Jan 2018', periods = 10) first_column_name = ['Group1']*3 + ['Group2']*3 second_column_name = ['Col1', 'Col2', 'Col3']*2 df = pd.DataFrame(mat, index = index, columns = [first_column_name,\ second_column_name]) Group1 Group2 Col1 Col2 Col3 Col1 Col2 Col3 2018-01-25 11 36 80 88 31 33 2018-01-26 30 32 61 53 55 43 2018-01-27 64 26 21 63 33 93 2018-01-28 52 59 23 54 91 60 2018-01-29 93 88 27 16 88 7 2018-01-30 28 76 48 5 38 1 2018-01-31 7 29 45 86 53 96 2018-02-01 18 89 69 3 34 34 2018-02-02 0 7 94 99 5 68 2018-02-03 29 13 98 25 51 44 Now I want to apply the function: def my_fun(arr1, arr2): arr1 = np.array(arr1) arr2 = np.array(arr2) tmp = np.abs(arr1 - arr2) return(np.sum(tmp)) Note that this is a simple case: in the real case the function is extremely more complex and work-around can't be taken! The desired output is the following, when I apply the function to 'Col1' 'Col 3': Group1 Group2 2018-01-31 296 124 2018-02-28 214 81 To do that I've applied a little bit of object oriented programming to combine resample with groupby. So I created this class class ApplyFunction(): def __init__(self, column_names, fun, resample = None): self.cn = column_names self.fun = fun self.resample = resample # Initialize the stored values self.stored_values = dict() for name in self.cn: self.stored_values[name] = [] def __store(self, x): self.stored_values[self.to_store].append(x.values.copy()) def wrapper_with_resample(self, x): if self.resample is None: print('Can not use this function with resample = None') return np.nan # Get the names of the group gr…
accepted answer of: http://stackoverflow.com/q/48946272
answers question: http://stackoverflow.com/q/48946272
score: 0

http://stackoverflow.com/a/48915585
score: 2
downvote count: 0
upvote count: 2
has body: After diving deeper in the BigTable mechanics, it seems that the python client executes a gRPC ReadRows call when you call table.read_rows(). That gRPC call returns a streaming response of rows in key order over HTTP/2 (see the docs). If the API returns data per row it seems to me that the only useful way to consume that response is row based. There seems to be little use in trying to load that data in a columnar format to avoid having to loop over the rows.
type: Answer
answers question: http://stackoverflow.com/q/48828545

http://stackoverflow.com/q/48876018
has answer: http://stackoverflow.com/a/48880358
downvote count: 1
answer count: 1
type: UnansweredQuestion
tagged with: split
upvote count: 0
tagged with: arrays
has comment: http://stackoverflow.com/comment/84758961
tagged with: string
favorite count: 0
has comment: http://stackoverflow.com/comment/84756003
has title: program won't parse splitlines string
type: Question
tagged with: range
tagged with: python
score: -1
has body: I'm trying to parse a show schedule so I can identify the times certain shows will be on. I created a relatively effective program when I was parsing a whole string, but when I split it up into lines it started generating a string index out of range error. I fixed that by reducing the range by 1 and making sure I wasn't checking an index coordinate that didn't exist but now the program is only printing two times. Here's my code. scheduleLines = schedule.splitlines() timeCoordinate = -10 for Line in scheduleLines: for counter in range(len(Line) - 1): if counter &lt;= timeCoordinate: continue if Line[counter].isdigit() == True: if Line[counter + 1] == ":": print(Line[counter:counter + 4]) timeCoordinate = counter + 4 if counter + 2 &lt; len(Line): if Line[counter + 2] == ":": print(Line[counter:counter + 5]) timeCoordinate = counter + 5 it only prints 9:00 and 8:00 and this is the schedule. The previous version of the program could extract and print all of the times. I can't get the schedule to format correctly when I post it to StackoverFlow, but each time plus the name of the show is a different line. Monday Feb 12th 9:00 am - CanDo’s ep9 9:30 - Storytime ep7 10:00am Afro Tusk ep3 11:00a - The Thunderbolt ep1 12:00 - Seattle here and Now ep27 1:00p - Startime ep53 3:00p - heartBeat Radio ep6 3:30 Single Father ep13p 4:00p - Traffic Jam 6:00 - Livin it Up ep 7 6:30 Sports &amp; Stuff ep15 7:00 - Lidline Sports 8:00 - Seattle Sports Weekly ep22 9:00p - The Reggae ep6 10:00 - MoJam Monday ep7 11:00 Just My Opinion ep21 Midnight - Diverse Programming

http://stackoverflow.com/a/48829979
answers question: http://stackoverflow.com/q/48825940
score: 0
type: Answer
has body: As an alternative you could try using an or | with a positive lookbehind (?&lt;= and a positive lookahead (?= for the single and double quotes (?&lt;=").*?(?=")|(?&lt;=').*?(?=')|[a-z]+ regex = r"(?&lt;=\").*?(?=\")|(?&lt;=').*?(?=')|[a-z]+" line = "a.\"b.t\".qq.d.d.'d'.'d.g.r'.d.d" print(re.findall(regex, line)) ['a', 'b.t', 'qq', 'd', 'd', 'd', '.', 'd.g.r', 'd', 'd'] Test output python

http://stackoverflow.com/q/48869904
has comment: http://stackoverflow.com/comment/84744124
tagged with: deep-copy
has comment: http://stackoverflow.com/comment/84743939
tagged with: pandas
answer count: 1
downvote count: 0
has comment: http://stackoverflow.com/comment/84743892
favorite count: 0
has comment: http://stackoverflow.com/comment/84743851
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84744089
tagged with: python
has body: I am still super confused on how pandas dataframes handle functions applied to a slice of the overall dataframe. Here is what I want to do.. I have a dataframe (normally would be much larger and with more columns!) &gt;&gt; df one two three 0 NaN 0.0 1000 1 NaN 0.0 2000 2 1.262950e+36 NaN 3000 3 NaN NaN 4000 I want to clip the value 1.262950e+36 to some other value, say 1000, so that no value in the dataframe (except for column 3) will have values larger than 1000. My try 1 I tried the following: df.loc[:, df.columns.tolist()[:-1]].clip(upper=1000, inplace=True) but it doesn't seem to work as we get &gt;&gt; df one two three 7317 NaN 0.0 1 7318 NaN 0.0 2 7319 1.262950e+36 NaN 3 7320 NaN NaN 4 My try 2 So I tried with copy df.loc[:, df.columns.tolist()[:-1]] copy.deepcopy(df.loc[:, df.columns.tolist()[:-1]].clip(upper=1000)) which works but it is obviously too long and unreadable! Is there a better, faster, more concise and more pythonic way? Edit: Dtypes The dtypes of the columns are &gt;&gt; df.dtypes() one float64 two float64 three int64 dtype: object
has comment: http://stackoverflow.com/comment/84744079
score: 1
upvote count: 1
has comment: http://stackoverflow.com/comment/84744008
type: Question
has comment: http://stackoverflow.com/comment/84744128
has comment: http://stackoverflow.com/comment/84743690
tagged with: dataframe
has answer: http://stackoverflow.com/a/71194976
has title: pandas dataframe use clip on a subset of columns

http://stackoverflow.com/a/48811901
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48804621
has body: I realized I forgot to put root.update() in my main code so it wasn't updating. The progress bar changed colour after I did this.

http://stackoverflow.com/comment/84868272
type: Comment
score: 1
has text: This trick is awesome. Thanks. Took me 15 minutes to figure it out though!
type: AnswerComment
comment on: http://stackoverflow.com/a/48929666

http://stackoverflow.com/comment/84793553
has text: True. Your explanation was very clean and concise and I appreciate the arxiv source as well. Thanks.
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48893335
type: AnswerComment

http://stackoverflow.com/a/48885706
downvote count: 0
score: 1
accepted answer of: http://stackoverflow.com/q/48885509
upvote count: 1
type: AcceptedAnswer
type: Answer
has body: Just to be sure, check that your code isn't actually something like this: for i in range(2): arr=np.empty((1,), dtype=np.int32) arr=np.union1d(arr, data[df.iloc[i,7]]) If not, I'd debug in the following way for i in range(2): new_arr = data[df.iloc[i,7]] print(type(new_arr)) # check that it's an array print(new_arr.shape) # check that first dim &gt; 1, second dim = 1 Once you get this working I'd also suggest initializing arr = [] because np.empty initializes the array by placing a very very small value as a placeholder so it will be present in your final concatenated array!
has comment: http://stackoverflow.com/comment/84776393
answers question: http://stackoverflow.com/q/48885509

nexus
type: Tag
tags question: http://stackoverflow.com/q/48812740
tag name: nexus

http://stackoverflow.com/comment/84760439
comment on: http://stackoverflow.com/q/48878219
has text: What exactly is your original data? Show us its Python form, not the printout.
type: Comment
type: QuestionComment
score: 0

http://stackoverflow.com/q/48954694
has answer: http://stackoverflow.com/a/48955311
tagged with: tensorflow
type: Question
tagged with: keras
upvote count: 3
has comment: http://stackoverflow.com/comment/84916371
has comment: http://stackoverflow.com/comment/84917531
answer count: 1
has body: I searched a lot for an answer but wasn't able to find a satisfying one. If I understood correctly, during model.fit(), Keras prints the loss for the last batch to terminal. If I call model.evaluate() on the training set I get the loss value for the whole set. So, intuitively if I call model.evaluate() on a single instance of the training set I should get a value that is a fraction of the value I would get calling model.evaluate() on the whole training set. But instead I get a value that is close or even bigger by ~10 times. Any idea why?
favorite count: 0
tagged with: machine-learning
tagged with: python
accepted answer: http://stackoverflow.com/a/48955311
type: AnsweredQuestion
score: 3
downvote count: 0
has title: How to interpret the loss returned by model.evaluate()?

http://stackoverflow.com/a/48943843
has body: list1=[] list2=[] f = open("inputfile.txt","r") lines = f.readlines() f.close() list1 = [int(x) for x in lines[0].split(",")] list2 = [int(x) for x in lines[1].split(",")] print(list1) print(list2) output: [1, 5, 7, 18, 9, 8, 12] [2, 41, 12, 11, 1, 10]
downvote count: 0
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48943667

http://stackoverflow.com/q/48860520
tagged with: python
has comment: http://stackoverflow.com/comment/84724223
has answer: http://stackoverflow.com/a/48861084
has title: Display link, not tag
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48860814
has answer: http://stackoverflow.com/a/48860814
has comment: http://stackoverflow.com/comment/84724608
accepted answer: http://stackoverflow.com/a/48861084
has comment: http://stackoverflow.com/comment/84724552
has comment: http://stackoverflow.com/comment/84724514
type: Question
score: 0
answer count: 2
has comment: http://stackoverflow.com/comment/84724219
tagged with: javascript
tagged with: jquery
has body: I have a list of html tags, called papersFound, e.g. papersFound = ['Symmetric spectra', 'Topological transformation groups'] I want to loop through this list, and display hyperlinks to the papers, not the tags themselves (obviously). What I have now is displaying the tags: {% for paper in papersFound %} {{ paper }} {% endfor %} Any help is greatly appreciated. Thank you. EDIT: At http://jinja.pocoo.org, I see the example {% for user in users %} {{ user.username }} {% endfor %} I want to implement this. But what kind of object is users (which has properties url and username)? EDIT 2: Currently, my page is displaying the html tags, as you can see
tagged with: http://stackoverflow.com/tag/html

http://stackoverflow.com/a/48901755
score: 0
type: Answer
has comment: http://stackoverflow.com/comment/84844968
answers question: http://stackoverflow.com/q/48901678
has comment: http://stackoverflow.com/comment/84846382
has body: I think you need merge without parameter on, so all columns are joined: df = pd.merge(df1, df2) print (df) A B 0 emp_table emp_id 1 pay_table da_amount

http://stackoverflow.com/comment/84714408
score: 0
comment on: http://stackoverflow.com/a/48851083
type: Comment
has text: Odd indeed. I'm using the community version (2017.3) myself on my office laptop.
type: AnswerComment

http://stackoverflow.com/comment/84667710
comment on: http://stackoverflow.com/q/48831730
score: 1
type: Comment
type: QuestionComment
has text: `"[[:<:]]{}[[:>:]]".format(i)`

http://stackoverflow.com/a/48836817
upvote count: 2
type: Answer
has body: Improving @Ajax1234's answer; this will only find tags with the itemprop attribute. See find_all() from bs4 import BeautifulSoup as soup l = """ One Text1 Text2 Text3 Two """ s = soup(l, 'lxml') final_text = [i.text for i in s.find_all("a", attrs={"itemprop": "affiliation"})]
has comment: http://stackoverflow.com/comment/84776991
score: 2
downvote count: 0
answers question: http://stackoverflow.com/q/48836215

http://stackoverflow.com/q/48860428
type: Question
has comment: http://stackoverflow.com/comment/84724091
has body: I am trying to do a plot of values over time using seaborn linear model plot but I get the error TypeError: invalid type promotion I have read that it is not possible to plot pandas date objects, but that seems really strange given seaborn requires you pass a pandas DataFrame to the plots. Below is a simple example. Does anyone know how I can get this to work? import pandas as pd import seaborn as sns; sns.set(color_codes=True) import matplotlib.pyplot as plt date = ['1975-12-03','2008-08-20', '2011-03-16'] value = [1,4,5] df = pd.DataFrame({'date':date, 'value': value}) df['date'] = pd.to_datetime(df['date']) g = sns.lmplot(x="date", y="value", data=df, size = 4, aspect = 1.5) I am trying to do a plot like this one I created in r using ggplot hence why I want to use sns.lmplot
accepted answer: http://stackoverflow.com/a/48860713
answer count: 2
tagged with: pandas
possible better answer: http://stackoverflow.com/a/56462698
downvote count: 0
has comment: http://stackoverflow.com/comment/84724036
has comment: http://stackoverflow.com/comment/84724055
has answer: http://stackoverflow.com/a/56462698
favorite count: 0
has comment: http://stackoverflow.com/comment/84724581
tagged with: seaborn
linked to: http://stackoverflow.com/q/44354614
tagged with: datetime
tagged with: python
has answer: http://stackoverflow.com/a/48860713
type: AnsweredQuestion
has title: Passing datetime-like object to seaborn.lmplot
score: 7
tagged with: matplotlib
upvote count: 7

http://stackoverflow.com/q/48915810
has comment: http://stackoverflow.com/comment/123308107
has comment: http://stackoverflow.com/comment/99883736
tagged with: contiguous
tagged with: pytorch
downvote count: 1
answer count: 8
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/52229694
linked to: http://stackoverflow.com/q/69840389
linked to: http://stackoverflow.com/q/49643225
has answer: http://stackoverflow.com/a/64019069
score: 245
has answer: http://stackoverflow.com/a/61194130
tagged with: memory
has body: What does x.contiguous() do for a tensor x?
type: Question
has answer: http://stackoverflow.com/a/67021086
possible better answer: http://stackoverflow.com/a/69599806
has title: What does .contiguous() do in PyTorch?
has answer: http://stackoverflow.com/a/69599806
has answer: http://stackoverflow.com/a/57723311
accepted answer: http://stackoverflow.com/a/52229694
has answer: http://stackoverflow.com/a/48922607
favorite count: 0
has answer: http://stackoverflow.com/a/52070381
has comment: http://stackoverflow.com/comment/108256176
upvote count: 246
tagged with: python

http://stackoverflow.com/comment/85042079
type: AnswerComment
has text: here is a link to the updated question: https://stackoverflow.com/questions/49018025/beautifulsoup4-identifying-info-by-strong-tag-value-only-works-for-some-values
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48944048

http://stackoverflow.com/q/48834945
has title: Django Correct Usage of Models.Cascade (on_delete)
has answer: http://stackoverflow.com/a/60682393
favorite count: 0
has comment: http://stackoverflow.com/comment/84674635
type: UnansweredQuestion
has body: I am trying to work what is the correct usage of the models.cascade statement. I have two models Cart and Entry. If I delete an Entry the deletion is not updated on the Cart Entry. I have checked this via the admin interface. My models.py is as below: class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) count = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=10, decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CartManager() def __str__(self): return "Cart:{} User:{} Items:{} Total:£{}".format(self.id, self.user, self.count, self.total) class Entry(models.Model): product = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE) quantity = models.PositiveIntegerField(default=0)
tagged with: django
tagged with: python
linked to: http://stackoverflow.com/q/38388423
score: 3
upvote count: 3
tagged with: django-models
has comment: http://stackoverflow.com/comment/84674819
type: Question
answer count: 2
linked to: http://stackoverflow.com/q/12655347
has answer: http://stackoverflow.com/a/48835526
downvote count: 0

http://stackoverflow.com/a/48937291
has body: use global in order to reassign text variable text = "a" def a(): global text text += " hi" print(text) def b(): global text text += " there" print(text) def main(): a() b() main() result with a hi a hi there
type: Answer
answers question: http://stackoverflow.com/q/48937219
has comment: http://stackoverflow.com/comment/84881575
score: 0

http://stackoverflow.com/a/48836035
upvote count: 2
has comment: http://stackoverflow.com/comment/84676968
type: Answer
has body: The corresponding series value is on index1, does that help? Docs: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.iterrows.html DataFrame.iterrows()[source] Iterate over DataFrame rows as (index,Series) pairs. print(row[1] == data_file.iloc[0]) Another solution: for ind, row in data_file.iterrows():
score: 2
has comment: http://stackoverflow.com/comment/84676950
has comment: http://stackoverflow.com/comment/84686156
has comment: http://stackoverflow.com/comment/84687564
accepted answer of: http://stackoverflow.com/q/48835864
downvote count: 0
has comment: http://stackoverflow.com/comment/84687445
has comment: http://stackoverflow.com/comment/84687534
answers question: http://stackoverflow.com/q/48835864
type: AcceptedAnswer

http://stackoverflow.com/comment/84790861
has text: I just read your question again, is there other text on the screen? This solution doesn't clear the screen but it does put the lines in an absolute position. If you need something more dynamic that can be achieved with the same library but will take a little more work.
type: AnswerComment
comment on: http://stackoverflow.com/a/48892453
score: 0
type: Comment

http://stackoverflow.com/q/48939847
has body: I'm having the hardest time trying to figure out the difference in usage between multiprocessing.Pool and multiprocessing.Queue. To help, this is bit of code is a barebones example of what I'm trying to do. def update(): def _hold(url): soup = BeautifulSoup(url) return soup def _queue(url): soup = BeautifulSoup(url) li = [l for l in soup.find('li')] return True if li else False url = 'www.ur_url_here.org' _hold(url) _queue(url) I'm trying to run _hold() and _queue() at the same time. I'm not trying to have them communicate with each other so there is no need for a Pipe. update() is called every 5 seconds. I can't really rap my head around the difference between creating a pool of workers, or creating a queue of functions. Can anyone assist me? The real _hold() and _queue() functions are much more elaborate than the example so concurrent execution actually is necessary, I just thought this example would suffice for asking the question.
type: AnsweredQuestion
upvote count: 14
has answer: http://stackoverflow.com/a/48945440
tagged with: multiprocessing
type: Question
score: 14
has title: Mutliprocessing Queue vs. Pool
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48945440
favorite count: 0
tagged with: python-3.x
tagged with: python

http://stackoverflow.com/q/48893524
tagged with: matplotlib
type: Question
has comment: http://stackoverflow.com/comment/84792729
answer count: 1
has answer: http://stackoverflow.com/a/48901107
has body: I have a dataframe named recast with the following structure: data = [[ 374000,np.nan,749500,np.nan], [np.nan,np.nan,298000,np.nan], [540065.326633,np.nan,904750,np.nan], [np.nan,np.nan,514000,np.nan], [411000,np.nan,np.nan,np.nan]] cols = pd.MultiIndex.from_tuples([('EUR, Oil (bbls)',c) for c in ['DE WITT','FAYETTE','GONZALES','LAVACA']], names=('','County')) index = ['1776 ENERGY','ALMS','BURLINGTON','BXP','CHESAPEAKE'] recast=pd.DataFrame(data,index=index,columns=cols) recast.index.name = 'ShortName' print(recast) EUR, Oil (bbls) County DE WITT FAYETTE GONZALES LAVACA ShortName 1776 ENERGY 374000.000000 NaN 749500.0 NaN ALMS NaN NaN 298000.0 NaN BURLINGTON 540065.326633 NaN 904750.0 NaN BXP NaN NaN 514000.0 NaN CHESAPEAKE 411000.000000 NaN NaN NaN What I would like to do is make a heatmap that has only the County names and not the column names that it is giving me. When I call .info() on the dataframe I get: &lt;class 'pandas.core.frame.DataFrame'&gt; Index: 29 entries, 1776 ENERGY to VERDUN OIL Data columns (total 4 columns): (EUR, Oil (bbls), DE WITT) 14 non-null float64 (EUR, Oil (bbls), FAYETTE) 3 non-null float64 (EUR, Oil (bbls), GONZALES) 23 non-null float64 (EUR, Oil (bbls), LAVACA) 5 non-null float64 dtypes: float64(4) So by default my x labels on the heatmap are, for example: EUR, Oil (bbls), DE WITT, when I only want: DE WITT. I have tried elminating the unwanted part by trying rename the columns in the dataframe and by trying to set x_label, but can't get it to work. For plotting I am using the following code: fig = plt.figure(71) fig = sns.heatmap(recast, cmap='coolwarm', linewidths=0.25, linecolor='black') fig = plt.xticks(rotation=0) plt.tight_layout plt.show() Also, I would like to remove the X and Y titles(?) that appear beneath/left of the labels.
has comment: http://stackoverflow.com/comment/84795890
tagged with: pandas
has title: Rename pandas dataframe columns when plotting heatmap with seaborn
tagged with: seaborn
score: 0
tagged with: python
accepted answer: http://stackoverflow.com/a/48901107
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84808475

http://stackoverflow.com/comment/84701750
score: 0
type: Comment
has text: Thanks! I wasn't able to get the example code running before leaving the office (key too large, and not hashable, either), but I'll read through the stuff you linked and let you know if it worked. Of course, this won't help the fact that it takes a few minutes for the pipeline to even start. Do you know anything that can be done about that?
comment on: http://stackoverflow.com/a/48848778
type: AnswerComment

http://stackoverflow.com/comment/84737378
type: QuestionComment
has text: Yes, that's right.
comment on: http://stackoverflow.com/q/48865055
score: 0
type: Comment

http://stackoverflow.com/a/48819033
type: Answer
upvote count: 6
has body: Currently: you have 4 NumPy arrays: y_test, y_train, y_test_pred, and y_train_pred. You want: 2 NumPy arrays, y_true and y_pred. You can combine train + test with np.concatenate. For example: y_test = np.array([0, 1, 0, 1]) y_train = np.array([0, 0, 1, 1]) y_test_pred = np.array([1, 1, 0, 1]) # from classifier_logistic.predict(x_test) y_train_pred = np.array([0, 1, 0, 1]) # from classifier_logistic.predict(x_train) y_true = np.concatenate((y_train, y_test)) # you already have this as `Y` y_pred = np.concatenate((y_train_pred, y_test_pred)) There's a very good example of plotting a confusion matrix in the sklearn docs. Here's an example with your case in mind: import itertools import matplotlib.pyplot as plt import numpy as np from sklearn.metrics import confusion_matrix # Source: http://scikit-learn.org/stable/auto_examples/model_selection/ # plot_confusion_matrix.html#confusion-matrix y_test = np.array([1, 1, 0, 1]) y_train = np.array([0, 0, 1, 1]) y_test_pred = np.array([1, 1, 0, 1]) # from classifier_logistic.predict(x_test) y_train_pred = np.array([0, 1, 0, 1]) # from classifier_logistic.predict(x_train) y_true = np.concatenate((y_train, y_test)) y_pred = np.concatenate((y_train_pred, y_test_pred)) def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("Normalized confusion matrix") else: print('Confusion matrix, without normalization') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) fmt = '.2f' if normalize else 'd' thresh = cm.max() / 2. for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])): plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="c…
answers question: http://stackoverflow.com/q/48817300
score: 6
has comment: http://stackoverflow.com/comment/103523347
accepted answer of: http://stackoverflow.com/q/48817300
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48845017
has comment: http://stackoverflow.com/comment/84694351
type: Question
has answer: http://stackoverflow.com/a/48846206
has title: translating compose functions from javascript to python, the functional way
linked to: http://stackoverflow.com/q/16739290
score: 0
has comment: http://stackoverflow.com/comment/84694740
answer count: 2
has comment: http://stackoverflow.com/comment/84694992
tagged with: functional-programming
has comment: http://stackoverflow.com/comment/84694679
tagged with: javascript
has comment: http://stackoverflow.com/comment/84695732
has comment: http://stackoverflow.com/comment/84694341
tagged with: python
has answer: http://stackoverflow.com/a/48845073
has body: I'm trying to translate my Javascript compose functions into Python but I'm having trouble with the last one. How can I generalize an unknown number of functions? After reading this, I would like to avoid the reduce() method. javascript: /* compose functions */ const comp1 = (fn2, fn1) =&gt; arr =&gt; fn2(fn1(arr)) // 2 functions, one array const comp2 = (fn2, fn1) =&gt; (...arrs) =&gt; fn2(fn1(...arrs)) // 2 functions, multiple arrays const comp3 = (...fns) =&gt; (...arrs) =&gt; fns.reduceRight((v,f) =&gt; f(v), arrs) // multiple functions, multiple arrays python: /* compose functions */ comp1 = lambda fn2,fn1: lambda arr: fn2(fn1(arr)) # 2 functions, 1 array comp2 = lambda fn2,fn1: lambda *arrs: fn2(fn1(*arrs)) # 2 functions, multiple arrays comp3 = lambda *fns: lambda *arrs: ???? all improvements are appreciated...
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84694579

http://stackoverflow.com/q/48911576
upvote count: 1
has answer: http://stackoverflow.com/a/48912321
accepted answer: http://stackoverflow.com/a/48912321
has answer: http://stackoverflow.com/a/48911836
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84829644
tagged with: python
has answer: http://stackoverflow.com/a/48911768
has title: Is it best practice to avoid 'self' instances?
downvote count: 0
score: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84829588
tagged with: oop
has body: If I were to implement a class, such as: class LinkedList: def __init__(self): self.head = None def size(self): self.count = 0 self.current = self.head while self.current != None: self.current = self.current.get_next() self.count += 1 return self.count The size method would work perfectly fine without using self. for the count and current variables, so I was wondering: Why is it the case that count and current work both with and without self., whereas self.head wouldn't work without it? Is it generally bad practice to use self. in cases where it isn't necessarily required?
possible better answer: http://stackoverflow.com/a/48911768
type: Question
answer count: 3

http://stackoverflow.com/q/48868904
downvote count: 0
score: 1
tagged with: oauth-2.0
tagged with: slack
type: Question
has answer: http://stackoverflow.com/a/48869818
accepted answer: http://stackoverflow.com/a/48869818
upvote count: 1
has body: First Question: So, I'm attempting to post an image to a specific slack channel using the files.upload API call in the Slack APIs. I have a client_id and a client_secret. I just want this to be used for my team using slack to communicate. Is this possible without getting an access token through OAuth 2? Secondary question: In my attempt to go through OAuth 2, I have placed my client_id into a python dictionary and then json.dumps() it. I stored the id in the field 'client_id' yet the message returned is "OAuth message: please specify a 'client_id'" Why is this an error? Should I name it something other than 'client_id'? EDIT: I found the answer to question 2. I don't receive what I expected, but simply sending the dictionary without turning into a JSON object solved the client_id issue.
answer count: 1
tagged with: slack-api
favorite count: 0
has title: OAuth 2 and the Slack APIs for posting images
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84934295
comment on: http://stackoverflow.com/q/48958410
score: 0
has text: From what I saw, the API was only for training - which I don't need. Plus, getting the detection working with their library was super easy. The problem is that when using their detection to `start_conversation()`, `process_event` no longer works. If you think that using their API instead of using local hotword detection would be advantageous, please give a brief explanation on why and I'll take a look.
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84683401
type: QuestionComment
has text: `__init__.py` is not a good place for functions that are imported elsewhere. It exists to run code that initializes the package on the first import. In most cased there is very few code inside, some convenience imports maybe.
comment on: http://stackoverflow.com/q/48839566
score: 0
type: Comment

http://stackoverflow.com/a/48820856
upvote count: 1
type: AcceptedAnswer
downvote count: 0
has body: The function com() returns nothing (that is, a None). On return, you attempt to apply the selection operator to None (['fee']), which would work only if com() returned a dictionary.
answers question: http://stackoverflow.com/q/48820463
accepted answer of: http://stackoverflow.com/q/48820463
type: Answer
score: 1

http://stackoverflow.com/comment/84759841
comment on: http://stackoverflow.com/a/48877329
type: Comment
has text: @coldspeed bad time for me ;(
score: 0
type: AnswerComment

http://stackoverflow.com/a/48959253
upvote count: 3
has body: One way is: import numpy as np np.array(lst)[:, (0, 1, 3)]
answers question: http://stackoverflow.com/q/48959183
type: Answer
downvote count: 0
score: 3
has comment: http://stackoverflow.com/comment/84925271

http://stackoverflow.com/comment/84728550
type: QuestionComment
has text: @Astro update working fine but when i try to delete record using `id` it's gives error `global name 'ObjectId' is not defined`
comment on: http://stackoverflow.com/q/48840597
score: 0
type: Comment

http://stackoverflow.com/comment/84750929
has text: It is recommended by the community at large that this is a bad idea. It requires mucking with `globals()`. But we've all seen this question time and again and it always comes down to, "Use a dictionary. But if you insist:..."
score: 3
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48873515

http://stackoverflow.com/comment/84699320
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48846953
score: 0
has text: I should mention that this is actually quite a *bad* use case for recursion :-)

http://stackoverflow.com/q/48918438
has comment: http://stackoverflow.com/comment/84843438
answer count: 2
possible better answer: http://stackoverflow.com/a/48919540
has body: I'm learning python and the lib beatifulsoup to do some crawlers and i want to extract a text from a html code but the text is not into a tag. look the code My bs4 code is this: for p in soup.find_all("div", class_="description__container-text"): v1 = p for x in v1: print(v1) and the output is this: TEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXTTEXT” HD *********I WANT TO EXTRACT THIS TEXT HEAR!!!!!!*************************************************** so, how can i get the text: *********I WANT TO EXTRACT THIS TEXT HEAR!!!!!!***************************************************
score: 0
has answer: http://stackoverflow.com/a/48919540
has answer: http://stackoverflow.com/a/48920099
tagged with: beautifulsoup
tagged with: python
has title: Getting text into div with python beautifulsoup
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48920099
linked to: http://stackoverflow.com/q/16835449
type: Question

http://stackoverflow.com/comment/84652122
type: Comment
comment on: http://stackoverflow.com/a/48824235
has text: datetime and time probably use the same underlying C library.
type: AnswerComment
score: 0

http://stackoverflow.com/a/48861812
downvote count: 2
has body: When using slice it excludes the endpoint, just like in range(a, b) = a..(b-1) Though when you do list[:1] it should return [list[0]], not an empty array. Thus I suspect that your array is empty from the beginning. Reference
upvote count: 1
answers question: http://stackoverflow.com/q/48861789
score: -1
has comment: http://stackoverflow.com/comment/84726615
has comment: http://stackoverflow.com/comment/84726590
type: Answer
has comment: http://stackoverflow.com/comment/84726607
has comment: http://stackoverflow.com/comment/84726742

cloudinary
tags question: http://stackoverflow.com/q/48914518
type: Tag
tag name: cloudinary

http://stackoverflow.com/comment/84625467
type: AnswerComment
has text: Oh, no, this is just nice and easy. Imagine reloading whole module that was imported using 'from' statement. That's a real mess. Oh, and, yes, using reload() will work, but it will reload only your module. Modules that your module is importing won't be reloaded as long as they are in cache. So don't be surprised if you reload your module after you changed something in its submodule and the change is not reflected.
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48809943

http://stackoverflow.com/a/48917558
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48917460
accepted answer of: http://stackoverflow.com/q/48917460
type: Answer
has body: One solution. But you should consider whether you really need to perform this kind of manipulation of numeric data. import numpy as np arr = np.array([[181, 2], [ 3, 45], [ 5, 6]]) print(''.join('('+' '.join(map(str, i))+') ' for i in arr)) # (181 2) (3 45) (5 6)

http://stackoverflow.com/a/48829283
score: 3
upvote count: 3
answers question: http://stackoverflow.com/q/48829197
has body: You are missing a return statement on line 3 of gcd2. The updated function is below. def gcd2(m, n): if m % n != 0: return gcd2(n, m % n) else: return n Hope this helps.
downvote count: 0
has comment: http://stackoverflow.com/comment/84662492
type: Answer

http://stackoverflow.com/comment/84904385
comment on: http://stackoverflow.com/a/48948077
has text: Okay, I've restarted my laptop and now "python" works just fine. But, for some reason my output is still in bulk after the script finishes.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84747513
score: 0
type: Comment
type: QuestionComment
has text: @wwii I can't figure out the implementation of that algo.
comment on: http://stackoverflow.com/q/48870253

http://stackoverflow.com/comment/84634905
type: QuestionComment
has text: You can't possibly get the same results with different coordinates. At the very least, the image should show up in a different location. Or are you saying that even with different coordinates it's still showing up in the same place?
score: 0
comment on: http://stackoverflow.com/q/48814864
type: Comment

http://stackoverflow.com/q/48854020
tagged with: pyqt5
has title: Making QComboBox widgets distinguishable in a for loop using PyQt5
type: Question
accepted answer: http://stackoverflow.com/a/48854241
tagged with: pyqt
answer count: 1
downvote count: 0
has body: I'm having trouble with an application that creates a grid of QComboBox widgets (see picture below). I use a for loop to create the elements of the grid. QComboBox grid layout I would like to be able to treat each QComboBox separately. Here is the code without attempts to do so: grid = QGridLayout() combos = [ '1', '1', '1', '', '1', '1', '1', '1', '', '1', '1', '1', '1', '', '1', '1', '1', '1', '', '1'] positions = [(i,j) for i in range(5) for j in range(5)] for position, dcombo in zip(positions, combos): if dcombo == '': continue combo = QComboBox() for x in range(0, 30): combo.addItem(QIcon("/icons/%d.PNG" % x),"") combo.setFixedSize(120,100) combo.setIconSize(QSize(100,100)) grid.addWidget(combo, *position) comboList['combo{0}'.format(position)] = position Here is my attempt, and the point at which I am currently stuck: grid = QGridLayout() combos = [ '1', '1', '1', '', '1', '1', '1', '1', '', '1', '1', '1', '1', '', '1', '1', '1', '1', '', '1'] comboList = {} positions = [(i,j) for i in range(5) for j in range(5)] for position, drawcombo in zip(positions, combos): if drawcombo == '': continue combo = QComboBox() for x in range(0, 30): # combo.addItem(QIcon("absolver deck reviewer/icons/%d.PNG" % x),"") combo.setFixedSize(120,100) combo.setIconSize(QSize(100,100)) grid.addWidget(combo, *position) comboList['combo{0}'.format(position)] = position combo.currentIndexChanged.connect(lambda: self.logChange(comboList['combo{0}'.format(position)])) def logChange(self, currentCombo): sender = self.sender() print(str(currentCombo) + ' was changed') The print() method only ever returns the last position in the list (in this case, the (3, 4) tuple.
favorite count: 0
has answer: http://stackoverflow.com/a/48854241
tagged with: python
score: 2
type: AnsweredQuestion
tagged with: qcombobox
upvote count: 2

http://stackoverflow.com/a/48903338
score: 1
upvote count: 1
has body: If you want to match zero for all missing values, you could use something like this: @@ -(\d*),?(\d*) \+(\d*),?(\d*) @@ This would return and empty string if there was no match. You'd have to replace that with zero later in your code. Output Your examples would then output : ['1289','4','1289','4'] ['1289','2','1289',''] ['1289','','1289','8']
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48903177

http://stackoverflow.com/comment/84942547
comment on: http://stackoverflow.com/a/48956221
type: Comment
has text: I still don't see why a while loop would be useful. What you are describing can be done using an if statement.
score: 0
type: AnswerComment

http://stackoverflow.com/a/48847486
score: 0
has comment: http://stackoverflow.com/comment/84699046
type: Answer
has comment: http://stackoverflow.com/comment/84699028
has body: you are actually not defining a switch statement up there: switcher = { "name": rule.name = value, "src": rule.src = value, } This is a dictionary, and the interpreter is complaining about the statements as value there. You could just reference your methods like this: def type(option, value): switcher = { "name": rule.setName, "src": rule.setSrc } method = switcher.get(option, lambda: "Invalid Option") method(rule, value) Another idea Here is another aproach. Maybe something like this is helpful: def type(rule, option, value): if hasattr(rule, option): setattr(rule, option, value) else: print("Invalid Option") # Some error handling Explicitly checking the option name @PaulPanzer pointed out, that it is maybe in your intention to explicitly check weather options are correct. So here is a more secure version of the typefunction: def type(rule, option, value): if option in ["name", "src"]: setattr(rule, option, value) else: print("Invalid Option") # Some error handling This implies that you have to change the code in two different places, whenever you extend your file format. But this is a question of how defensive you want to be, how often the rules get extended and how much flexibility you need.
has comment: http://stackoverflow.com/comment/84699118
answers question: http://stackoverflow.com/q/48847387
has comment: http://stackoverflow.com/comment/84699203
has comment: http://stackoverflow.com/comment/84699304
has comment: http://stackoverflow.com/comment/84699087
has comment: http://stackoverflow.com/comment/84699029

http://stackoverflow.com/a/48858280
has comment: http://stackoverflow.com/comment/84803125
has body: There are a couple of methods to do this. Assuming you want to encode the independent variables you can use pd.get_dummies with the drop_first=True included. Here is an example: import pandas as pd # Create a data of independent variables X for the example X = pd.DataFrame({'Country':['China', 'India', 'USA', 'Indonesia', 'Brasil'], 'Continent': ['Asia', 'Asia', 'North America', 'Asia', 'South America'], 'Population, M': [1403.5, 1324.2, 322.2, 261.1, 207.6]}) print(X) # Encode columnsToEncode=X.select_dtypes(include=[object]).columns X = pd.get_dummies(X, columns=columnsToEncode, drop_first=True) print(X) # X prior to encoding Continent Country Population, M 0 Asia China 1403.5 1 Asia India 1324.2 2 North America USA 322.2 3 Asia Indonesia 261.1 4 South America Brasil 207.6 # X after encoding Population, M Continent_North America Continent_South America \ 0 1403.5 0 0 1 1324.2 0 0 2 322.2 1 0 3 261.1 0 0 4 207.6 0 1 Country_China Country_India Country_Indonesia Country_USA 0 1 0 0 0 1 0 1 0 0 2 0 0 0 1 3 0 0 1 0 4 0 0 0 0
score: 5
type: Answer
has comment: http://stackoverflow.com/comment/84797564
has comment: http://stackoverflow.com/comment/84798855
upvote count: 5
downvote count: 0
answers question: http://stackoverflow.com/q/48856595

http://stackoverflow.com/comment/84841403
score: 0
type: QuestionComment
type: Comment
has text: @juanpa.arrivillaga I am trying to minimize the amount of variables I use and I thought that removing the use of lists would be plausible
comment on: http://stackoverflow.com/q/48917405

http://stackoverflow.com/a/75802156
type: Answer
has body: I solved it in this way it means you have an existing app name in ur directory if not visible on ur directory close and reopen the editer the you will get it.
answers question: http://stackoverflow.com/q/48834534
downvote count: 1
score: -1
upvote count: 0

http://stackoverflow.com/comment/84813661
has text: Maybe I need to generate this "cpf" column with quotation marks? LibreOffice has the command on the opening screen - "Fields in quotation marks as text"
type: Comment
comment on: http://stackoverflow.com/a/48903715
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84917091
type: Comment
has text: @ShadowRanger. That's what I get for being lazy and not testing my code before posting. Fixed it up now.
score: 1
type: AnswerComment
comment on: http://stackoverflow.com/a/48955090

http://stackoverflow.com/comment/84737877
comment on: http://stackoverflow.com/a/48867329
type: Comment
has text: FYI: code-only answers are often frowned upon, even if commented. Consider providing commentary text to explain what the code actually does.
score: 2
type: AnswerComment

http://stackoverflow.com/q/48917761
tagged with: algorithm
accepted answer: http://stackoverflow.com/a/48918060
possible better answer: http://stackoverflow.com/a/48918090
upvote count: 2
answer count: 2
has body: I have a smoothing algorithm that I implemented that basically applies a kernel: [0 1 0; 1 4 1; 0 1 0]/8 to a matrix (image) and then corrects the edges and corners, equivalent to setting the kernel as [0 1 0; 0 5 1; 0 1 0]/8 for a left edge, and [0 0 0; 0 6 1; 0 1 0]/8 for a top-left corner. My goal now is to apply a smoothing that only applies to a masked part of that image. For example (refer to images below), if I had a square image of a disk, where the disk would have values of 128+-10 (+-10 is a noise effect), and the background is black (value of 0), the normal smoothing algorithm applied infinite times should give a square image with a constant pixel intensity. For the masked smoothing algorithm I would like to mask the disk such that the algorithm applied infinite times should give a uniform disk at 128 and a black (0) background. In other words, only the disk was smoothed. The main thing that I'm trying to avoid is that the background "bleeds" into the disk, making the edges of the disk fuzzy. I'm also willing to change the smoothing algorithm to something different (eg. average of 3x3 pixels) that would allow for a more efficient approach. ( Noisy Original ) (After the normal smooth) ( After the masked smooth ) Here is my code for normal smooth: def SmoothImage(Matrix,N=1): '''Smooths a Matrix with kernel [0 1 0; 1 4 1; 0 1 0]/8''' A=Matrix.copy() for i in range(N): s=A.shape[0]-1 B=A*4.0 B[-s:,:]+=A[:s,:] B[0,:]+=A[0,:] B[:,-s:]+=A[:,:s] B[:,0]+=A[:,0] B[:s,:]+=A[-s:,:] B[-1,:]+=A[-1,:] B[:,:s]+=A[:,-s:] B[:,-1]+=A[:,-1] B*=1/8 A=B return A
downvote count: 0
has answer: http://stackoverflow.com/a/48918060
has answer: http://stackoverflow.com/a/48918090
favorite count: 0
tagged with: python
type: AnsweredQuestion
score: 2
has title: numpy masked smoothing algorithm
type: Question
tagged with: numpy

http://stackoverflow.com/comment/84647445
type: AnswerComment
has text: Yes, there's a div with id `currency-exchange-rates` that contains the exchange rates. Haven't poked around in the JS, but the page appears to be using that preloaded exchange-rate data to instantly recalculate when the user selects a different currency. There aren't any requests back to the server when you change currencies.
comment on: http://stackoverflow.com/a/48821571
score: 0
type: Comment

http://stackoverflow.com/q/48832836
upvote count: 1
has body: This is a general question but I attached a real data set to illustrate idea. When I trained a model on a very large data set, it took me hours to finished(logistic regression, macbook air, CPU:1.4 GHz Intel Core i5 8G RAM). Is there a way to divide/ shard the training data per se, so we can more efficiently compute the model performance in sklearn or python? The dataset: from sklearn.datasets import fetch_covtype import numpy as np import pandas as pd cov.data.shape #(581012 rows, 54 features) cov = fetch_covtype() cov_data = pd.DataFrame(cov.data) cov_target = pd.DataFrame(cov.target) Can anyone please help?
has answer: http://stackoverflow.com/a/49738183
has title: How to subset a big dataset with pandas or sklearn to shorten run time for model training?
downvote count: 0
tagged with: dataset
type: UnansweredQuestion
tagged with: scikit-learn
score: 1
favorite count: 0
tagged with: sklearn-pandas
type: Question
tagged with: python
answer count: 1

http://stackoverflow.com/q/48860734
answer count: 1
has body: I have a form where I'm trying to compare two objects (Cards) that are randomly selected from the database. In my form, I tried to dynamically populate a choicefield with the two cards, and in the view I'm trying to create an object (CardComparison(winning_card,losing_card)) with the choice of the user. I've overwritten the __init__ of the form to dynamically populate the card choices, and it's working fine. The problem is that when the user selects a card, it only passes the selected card, and I'm not able to figure out which card is NOT chosen in the view. I'm new to Django, and I've realized the more I struggle with this, a dynamic choice field may not be what I actually want to use, so a suggestion for a better method would also be greatly appreciated. forms.py: def get_new_comparison(): left_card = #get a random card (code hidden for cleanliness) right_card = #get a second random card left_card_choice = (left_card, left_card.name) right_card_choice = (right_card, right_card.name) return [left_card_choice, right_card_choice] class CompareCardsForm(forms.Form): def __init__(self, *args, **kwargs): post_flag = False if kwargs.get('post_flag'): post_flag = kwargs.pop('post_flag') super(CompareCardsForm, self).__init__(*args, **kwargs) if post_flag and len(args) &gt; 0: card_name = args[0].get('cards_to_compare') card_obj = Card.objects.get(name=card_name) card_choice = [(card_obj,card_name)] self.fields['cards_to_compare'] = forms.ChoiceField(choices=card_choice, widget=forms.RadioSelect()) #Because everytime the __init__ is called the choices are randomized, I need to set the choices to the POST data's choices otherwise the selected card may not be in the form when it's trying form.is_valid() else: self.fields['cards_to_compare'] = forms.ChoiceField(choices=get_new_comparison(), widget=forms.RadioSelect()) views.py: def CompareCards(request): if request.method == 'POST': form = CompareCardsForm(request.POST, post_flag=True) if form.is_valid(): print(form.cleaned_d…
score: 0
tagged with: python
has answer: http://stackoverflow.com/a/48878112
tagged with: django
type: AnsweredQuestion
has title: Dynamically populate a choice field and get the non-chosen fields in the post data
type: Question
accepted answer: http://stackoverflow.com/a/48878112

http://stackoverflow.com/comment/84680332
type: Comment
comment on: http://stackoverflow.com/q/48817972
score: 0
type: QuestionComment
has text: @Denis yes I added "path('payments/', include('pinax.stripe.urls')),"... but i it doesnt seem that any html files for the templates are in the pinax-stripe site-packages folder. I then found this stackoverflow answer... What do you think? https://stackoverflow.com/a/38021293/8854130

http://stackoverflow.com/a/51614727
has body: The attribute self.train_score_ is recreated in the following way: test_dev = [] for i, pred in enumerate(clf.staged_decision_function(X_test)): test_dev.append(clf.loss_(y_test, pred)) ax = plt.gca() ax.plot(np.arange(clf.n_estimators) + 1, test_dev, color='#d7191c', label='Test', linewidth=2, alpha=0.7) ax.plot(np.arange(clf.n_estimators) + 1, clf.train_score_, color='#2c7bb6', label='Train', linewidth=2, alpha=0.7, linestyle='--') ax.set_xlabel('n_estimators') plt.legend() plt.show() See the result below. Note that the curves are on top of each other as the training and test data are the same data.
has comment: http://stackoverflow.com/comment/90266080
score: 0
has comment: http://stackoverflow.com/comment/90276406
answers question: http://stackoverflow.com/q/48889441
type: Answer
has comment: http://stackoverflow.com/comment/90263696

http://stackoverflow.com/comment/84660841
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48828549
type: Comment
has text: The api needs all those friends to have used my app for that api method to work . So scraping is my only option

series
tag name: series
type: Tag
tags question: http://stackoverflow.com/q/48871018
tags question: http://stackoverflow.com/q/48805069
tags question: http://stackoverflow.com/q/48935958
tags question: http://stackoverflow.com/q/48947557
tags question: http://stackoverflow.com/q/48866452
tags question: http://stackoverflow.com/q/48913801

http://stackoverflow.com/q/48822567
tagged with: python
has answer: http://stackoverflow.com/a/48823211
has comment: http://stackoverflow.com/comment/84650444
has body: I am writing a data in a file using append method of file handling but it is not being shown in a file. Also while reading a file it shows a Null byte error. with open("filename.txt",'a') as f_ro_panel: f_ro_panel.write('\n'+str(vl)+'\t'+str(op_minute)+'\t'+str(bcc)+\ '\t'+str(temp)+'\t'+str(tds2)+'\t'+str(tds1)+'\t'+str(pfr)+\ '\t'+str(rfr)+'\t'+str(rwpc)+'\t'+str(hppc)+'\t'+str(twv)+\ '\t'+str(rwv)+'\t'+str(uvst)+'\t'+str(tsc)+'\t'+str(tlv)) f_ro_panel.close() This is the code of writing. while reading I am using this program with open("filename.txt", 'rU') as my_file: reader = csv.reader(my_file, delimiter='\t') my_list = list(reader) ListLen = len(my_list) my_file.close() Any help would be appreciated.
has comment: http://stackoverflow.com/comment/84650642
has comment: http://stackoverflow.com/comment/84649003
has comment: http://stackoverflow.com/comment/84648711
type: Question
answer count: 1
tagged with: linux
has title: while appending a file the data is not writing in a file and while reading it it shows null byte in python
has comment: http://stackoverflow.com/comment/84649054
has comment: http://stackoverflow.com/comment/84648665
has comment: http://stackoverflow.com/comment/84648698
score: 0
type: UnansweredQuestion
tagged with: file
tagged with: error-handling
has comment: http://stackoverflow.com/comment/84648647

http://stackoverflow.com/comment/84852162
has text: Please also read https://stackoverflow.com/help/someone-answers
score: 0
comment on: http://stackoverflow.com/q/48922334
type: QuestionComment
type: Comment

http://stackoverflow.com/q/48941548
answer count: 1
tagged with: scikit-learn
has body: I am in the process of converting a binary classification problem to multi-label classification program. The code is written in python. The below is the existing code: positive_labels = [[0, 1] for _ in positive_examples] negative_labels = [[1, 0] for _ in negative_examples] Now i would like to convert this into a multi-label like 3 classes - 0,1,2 positive_labels = [[1,0,0] for _ in positive_examples] neutral_labels = [[0,1,0] for _ in neutral_examples] negative_labels = [[0,0,1] for _ in negative_examples] Is this correct? If not could you please let me know how to do this? Please help.
has title: Mutli-class classification in python
tagged with: python
tagged with: classification
tagged with: text-classification
tagged with: multilabel-classification
type: Question
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84889976
score: 0
has answer: http://stackoverflow.com/a/48941744
accepted answer: http://stackoverflow.com/a/48941744

http://stackoverflow.com/a/71868872
has body: this works for me from tensorflow.keras.layers import LeakyReLU output = tf.layers.dense(input, n_units, activation=LeakyReLU(alpha=0.01))
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48957094
score: 2
upvote count: 2

http://stackoverflow.com/comment/84666121
has text: While this is interesting (and a bit terrifying) I don't really see how this related to the line continuation \.
score: 5
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48830918

http://stackoverflow.com/comment/84977995
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48883740
has text: Yeah, I just read most of my data and it does start with 30 1, so I can use those values to test against?
score: 0

http://stackoverflow.com/q/48875775
has answer: http://stackoverflow.com/a/48875802
type: Question
upvote count: 2
answer count: 2
favorite count: 0
tagged with: pandas-groupby
tagged with: pandas
downvote count: 0
has title: How can I get a cell value from grouped dataframe without the index
tagged with: python
has answer: http://stackoverflow.com/a/48875808
accepted answer: http://stackoverflow.com/a/48875808
score: 2
type: AnsweredQuestion
has body: I am using a pandas df.groupby() function to group my dataframe on a column and iterate over it as follows: df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'], 'B' : ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'], 'C' : np.random.randn(8), 'D' : np.random.randn(8)}) """ above df looks like this A B C D 0 foo one -0.575010 -0.271119 1 bar one -0.130209 -0.106217 2 foo two 0.093987 -1.351369 3 bar three -0.403304 0.983619 4 foo two 0.668989 0.249099 5 bar two 1.153876 1.407159 6 foo one 1.453793 -0.347721 7 foo three 0.493562 -0.051688 """ grouped = df.groupby('A') for name, group in grouped: print(group) print(group['B']) Here print(group) returns as follows: A B C D 1 bar one -0.130209 -0.106217 3 bar three -0.403304 0.983619 5 bar two 1.153876 1.407159 And group['B'] returns 1 one 3 three 5 two I want to get one and not the index 1 or 3 or 5 but just one, three and two which are column B values. Here iloc won't work as indexes aren't continuous and I won't know which index is coming while iterating over the grouped dataframe.
tagged with: dataframe
possible better answer: http://stackoverflow.com/a/48875802

http://stackoverflow.com/comment/84774466
type: Comment
type: AnswerComment
has text: Although, hashing a dict isn't possible either. I'm not sure if this will increase my computing time, for I'm working with dict and pd.dataframes
score: 0
comment on: http://stackoverflow.com/a/48884739

http://stackoverflow.com/comment/84648698
score: 1
comment on: http://stackoverflow.com/q/48822567
has text: Reading from the [brochure](https://docs.python.org/3/library/csv.html#csv.reader) brother: `If csvfile is a file object, it should be opened with newline=''.` You have an example of use there too.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84640212
comment on: http://stackoverflow.com/a/48817866
has text: Aha! This is exactly what I was looking for. Thanks.
type: AnswerComment
score: 0
type: Comment

http://stackoverflow.com/comment/84653296
type: Comment
comment on: http://stackoverflow.com/q/48820732
has text: @Usernamenotfound i have cross verify with one image and i found that key_str for particular image is available in leveldb file
score: 0
type: QuestionComment

http://stackoverflow.com/a/63080695
score: 2
has body: An alternative is to use it as markdown with githubusercontent (source) instead a codeline on Colab, add a text (markdown text) and then to use the next line. e.g.
upvote count: 2
answers question: http://stackoverflow.com/q/48856683
downvote count: 0
type: Answer

http://stackoverflow.com/a/49315643
has body: I had a similar issue and figure out a way. You need to re-compile the theme. Here are the steps. sudo -u edxapp bash source /edx/app/edxapp/edxapp_env cd /edx/app/edxapp/edx-platform paver update_assets cms --settings=aws paver update_assets lms --settings=aws exit This will update the files that are served from /edx/var/edxapp/staticfiles/images
type: Answer
answers question: http://stackoverflow.com/q/48947270
score: 2
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48947270
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/comment/84725684
type: QuestionComment
comment on: http://stackoverflow.com/q/48861328
score: 0
has text: Aside: to my knowledge, the format year-day-month (2018-09-02 as Feb 9) doesn't even exist. It makes me wonder how that came about in your dataset.
type: Comment

http://stackoverflow.com/a/48911909
type: Answer
has body: As per my understanding there is no documentation of Odoo rest api(you will have to create one if you need by checking the controllers and authentications or there are some paid modules in odoo apps). But If you are using Odoo8 and angularjs, have a look at this repo for Odoo angularjs connector
answers question: http://stackoverflow.com/q/48903018
score: 0

http://stackoverflow.com/comment/84682121
score: 0
comment on: http://stackoverflow.com/q/48838842
type: Comment
type: QuestionComment
has text: /home/marimo/Desktop/midi/midi.mid

http://stackoverflow.com/q/48860385
upvote count: 17
answer count: 4
has comment: http://stackoverflow.com/comment/84723919
has body: As far as I know, now we can declare variables using type annotation syntax in Python 3.6 as following code. def printInt(): a: int = 0 b: int = 1 c: int = 2 print(a, b, c) What I want to do is declaring variables a, b, c in one line. I tried a, b, c: int, but it returns error. Also a: int=0, b: int=1, c: int=2 returns error too. Is there any way to declare multiple variables using type annotation syntax in one line?
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84724189
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84724367
tagged with: python
has comment: http://stackoverflow.com/comment/84724244
has title: How to declare multiple variables with type annotation syntax in Python?
downvote count: 0
has comment: http://stackoverflow.com/comment/84724039
score: 17
type: Question
tagged with: mypy
has answer: http://stackoverflow.com/a/56447812
has answer: http://stackoverflow.com/a/48860726
has answer: http://stackoverflow.com/a/48860517
has answer: http://stackoverflow.com/a/74361998
favorite count: 0

http://stackoverflow.com/q/48939151
tagged with: reactjs
tagged with: plotly-dash
has title: Python Dash without using external URLs for js
has answer: http://stackoverflow.com/a/48939244
answer count: 2
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I am interested in using Dash to make some web applications for displaying data. I want to run this entirely locally without the references to unpkg.com/[...]. I realize that there is a relative package path (pointing to local files) and an external package path (pointing to external locations), but I don't understand how I can switch from external to relative. Where is this documented and/or does anyone have a solution for running Dash without the references to these packages? Thanks.
score: 1
upvote count: 1
has answer: http://stackoverflow.com/a/77202648
type: Question

http://stackoverflow.com/q/48942743
favorite count: 0
has answer: http://stackoverflow.com/a/48942779
tagged with: python
accepted answer: http://stackoverflow.com/a/48942779
has title: Python, Pandas to remove rows in Excel
upvote count: 3
tagged with: excel
type: AnsweredQuestion
score: 3
tagged with: dataframe
has body: A spreadsheet to remove certain rows. All the rows of its first column contains values started with “36” are to be removed, before saving to a new spreadsheet. I use these codes (and need to split the columns afterwards in Excel). The example looks like this: import xlwt from xlrd import open_workbook old_file = open_workbook('C:\\original.xlsx') old_sheet = old_file.sheet_by_index(0) new_file = xlwt.Workbook(encoding='utf-8', style_compression = 0) new_sheet = new_file.add_sheet('Sheet1', cell_overwrite_ok = True) contents = [] for row in range(old_sheet.nrows): a = str(old_sheet.cell(row,0).value) b = str(old_sheet.cell(row,1).value) if not a.startswith("36"): contents.append(a + "," + b) for c, content in enumerate(contents): new_sheet.write(c, 0, content) new_file.save('C:\\result.xls') It’s not really sufficient so I want to learn the Pandas way doing so. I tried something like df.drop(["3649"]) but it doesn’t work. What’s the proper Pandas way to remove the rows? Thank you.
type: Question
tagged with: pandas
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/84793623
score: 0
type: Comment
type: QuestionComment
has text: @Goyo the os.listdir(attachments_folder) works, and returns the list of pdf files.
comment on: http://stackoverflow.com/q/48893773

http://stackoverflow.com/comment/84769717
type: AnswerComment
comment on: http://stackoverflow.com/a/48882514
score: 0
type: Comment
has text: Will your data-input-file be a plain text file (e.g. 'txt") with data separated by e.g. comma, tab, ":" or "-"?

http://stackoverflow.com/a/48823983
score: 2
downvote count: 0
upvote count: 2
type: Answer
has body: You have a nested structure, a defaultdict containing defaultdict instances. You only converted the outermost object; you need to create a deep copy instead. You could generate a new dictionary with a dict comprehension to create a copy 2 levels deep: {k: dict(v) for k, v in d.items()} Alteratively, build your data structure without using defaultdict objects: d = {} for (a, b), c in farm_sub_count: inner = d.setdefault(a, {}) inner[b] = inner.get(b, 0) + c
answers question: http://stackoverflow.com/q/48823942

http://stackoverflow.com/a/48864648
score: 0
accepted answer of: http://stackoverflow.com/q/48864433
type: Answer
answers question: http://stackoverflow.com/q/48864433
has comment: http://stackoverflow.com/comment/84733747
type: AcceptedAnswer
has body: Try this: for index, name in enumerate(newList): if index in toChange: newName = name.replace(name, str(index)) os.rename(name, newName) print(newName) Index is a index each variable in newList. Then you check is this index is in your list toChange. If it is you change file name. Enumerate: for index, number in enumerate([10, 20, 30]): print('index -&gt; {}'.format(index)) print('number -&gt; {}'.format(number)) &gt;&gt;&gt; index -&gt; 0 number -&gt; 10 index -&gt; 1 number -&gt; 20 index -&gt; 2 number -&gt; 30 How work 'in': 2 in [1,2,3] &gt;&gt; True 2 in [1,3] &gt;&gt; False

http://stackoverflow.com/comment/84711236
type: Comment
comment on: http://stackoverflow.com/a/48853746
has text: Thanks! Is it possible to set the x-axis numbers (1,2,3,4) to be on the middle of each bar?
score: 1
type: AnswerComment

http://stackoverflow.com/comment/84892518
type: Comment
has text: @JimDennis I can see it is almost identical up to the sort vs. sorted thing ;-)
type: AnswerComment
score: 1
comment on: http://stackoverflow.com/a/48942926

http://stackoverflow.com/q/48877207
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48877235
downvote count: 3
has comment: http://stackoverflow.com/comment/84758495
upvote count: 0
answer count: 1
linked to: http://stackoverflow.com/q/29801975
has title: Python subprocess with arguments
has answer: http://stackoverflow.com/a/48877235
tagged with: python
favorite count: 0
has body: I run a python script test.py by using python subprocess. I want to send two strings 'John', 'Henry' as argument and read the argument values from the test.py. I want something like this subprocess.call(['python3', 'test.py']) #add two names 'John', 'Henry' as argument test.py print(name1) #print John print(name2) #print Henry How can I do this?
score: -3
type: Question

http://stackoverflow.com/comment/136029096
comment on: http://stackoverflow.com/a/57229642
has text: The accepted solution works OS-independently
score: 0
type: AnswerComment
type: Comment

http://stackoverflow.com/comment/101834217
type: AnswerComment
comment on: http://stackoverflow.com/a/48808652
type: Comment
score: 1
has text: This will work just for this specific example, but there is an interest to be able to define the sequence of entries shown in a general way, e.g. for histograms.

http://stackoverflow.com/q/48832112
type: Question
has comment: http://stackoverflow.com/comment/84668642
has comment: http://stackoverflow.com/comment/84670277
has title: Python 3.6.3: Multiple "Exception ignored in: <generator object..." in flask app
has comment: http://stackoverflow.com/comment/84672996
answer count: 1
downvote count: 0
tagged with: flask
has comment: http://stackoverflow.com/comment/85138952
has answer: http://stackoverflow.com/a/49143540
tagged with: system-error
score: 1
favorite count: 0
type: UnansweredQuestion
upvote count: 1
tagged with: python
tagged with: generator
has body: I'm running a flask app, upgraded everything from Python 2.7 to 3 about 5 months ago. Most things have gone smooth enough, other than this one that's consistently bugging me locally. I'm on a MacBook on OSX 10.12.6, and a brew install of Python 3.6.3 under a virtualenv. When a request comes in from a page that seemingly has multiple static requests (.css, .js, and image files mainly), I seem to be able to get this error just about anywhere that's using generators anywhere in my code. Some examples (request is a flask.request object): A place that checks to see if a path starts with '/static' of '/admin/static' (my code), any(request.path.startswith(k) for k in self._static_paths) . Exception ignored in: &lt;generator object CustomPrincipal._is_static_route.&lt;locals&gt;.&lt;genexpr&gt; at 0x11450f3b8&gt; Traceback (most recent call last): File "/Developer/repos/git/betapilibs/lbbsports/flask_monkeypatches.py", line 22, in &lt;genexpr&gt; any(_checker(request.path, k) for k in self._static_paths) SystemError: error return without exception set If a url path is restricted, check if the logged in user has the proper permissions / role, return role in (role.name for role in self.roles) . Exception ignored in: &lt;generator object UserMixin.has_role.&lt;locals&gt;.&lt;genexpr&gt; at 0x1155a7e08&gt; Traceback (most recent call last): File "/Developer/virtualenvs/lbb3/lib/python3.6/site-packages/flask_security/core.py", line 386, in &lt;genexpr&gt; SystemError: error return without exception set A custom bit of code to ensure their "sub" account id is valid, (not any(ident == account_id for ident in account_ids)) . Exception ignored in: &lt;generator object CustomSession.get_set_accounts.&lt;locals&gt;.&lt;genexpr&gt; at 0x115ff4fc0&gt; Traceback (most recent call last): File "/Developer/customflask/flasklogin.py", line 168, in &lt;genexpr&gt; SystemError: error return without exception set Now, nothing seems to break in the system, I just get these error messages, and no…
has comment: http://stackoverflow.com/comment/91163313
linked to: http://stackoverflow.com/q/50369959

http://stackoverflow.com/comment/84828659
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48910369
has text: Any joy with that? Or are you still having problems?

http://stackoverflow.com/q/48881067
type: Question
has comment: http://stackoverflow.com/comment/84803335
answer count: 1
has title: Subject Extraction of a paragraph/document using NLP
tagged with: n-gram
score: 0
has comment: http://stackoverflow.com/comment/84802354
tagged with: nlp
has answer: http://stackoverflow.com/a/48910818
type: UnansweredQuestion
has body: I am trying to build a subject extractor, simply put, read all the sentences of a paragraph and make a calculated guess to what the subject of the paragraph/article/document is. I might even upgrade it to a summerize depending on the progress I make. There is a great deal of information on the internet. It is difficult to understand all of it and select a correct path, as I am not well versed with NLP. I was hoping someone with some experience could point me in the right direction. I am NOT looking for a linguistic computation model, but rather an n-gram or neural network approach, something that has been done recently. I am also looking into coreference resolution using n-grams, if anyone has any leads on that, it is much appreciated. Slightly familiar with the Stanford Coreferential Solver, but don't want to use it as is. Any information, ideas and opinions are welcome.
tagged with: python

http://stackoverflow.com/a/48933899
has body: using the @akrun comment for( i in seq(5)){ cat(i,"") } 1 2 3 4 5
score: 0
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48933351
has comment: http://stackoverflow.com/comment/84874763
type: Answer
accepted answer of: http://stackoverflow.com/q/48933351

http://stackoverflow.com/a/48941439
has body: It is possible with Python, albeit not "out of the box" with the native re module. First alternative The newer regex module supports a variable-length lookbehind, so you could use (?&lt;=^[^:]+)\) # pos. lookbehind making sure there's no : in that line In Python: import regex as re data = """ Hello1 ( First : (), Second ) Hello2 ( First )""" pattern = re.compile(r'(?&lt;=^[^:]+)\)', re.MULTILINE) parts = pattern.split(data) print(parts) Which yields ['\nHello1 (\nFirst : (),\nSecond ', '\n\nHello2 (\nFirst \n', ''] Second alternative Alternatively, you could match the lines in question and let them fail with (*SKIP)(*FAIL) afterwards: ^[^:\n]*:.*(*SKIP)(*FAIL)|\) # match lines with at least one : in it # let them fail # or match ) Again in Python: pattern2 = re.compile(r'^[^:\n]*:.*(*SKIP)(*FAIL)|\)', re.MULTILINE) parts2 = pattern.split(data) print(parts2) See a demo for the latter on regex101.com. Third alternative Ok, now the answer is getting longer than previously thought. You can even do it with the native re module with the help of a function. Here, you need to substitute the ) in question first and split by the substitute: def replacer(match): if match.group(1) is not None: return "SUPERMAN" else: return match.group(0) pattern3 = re.compile(r'^[^:\n]*:.*|(\))', re.MULTILINE) data = pattern3.sub(replacer, data) parts3 = data.split("SUPERMAN") print(parts3)
accepted answer of: http://stackoverflow.com/q/48940160
has comment: http://stackoverflow.com/comment/84894936
score: 4
upvote count: 4
has comment: http://stackoverflow.com/comment/84915842
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84895512
type: Answer
answers question: http://stackoverflow.com/q/48940160

http://stackoverflow.com/comment/84803476
comment on: http://stackoverflow.com/q/48898959
has text: 2 is the number that you are looking for how many times it is been repeated in the list
score: 0
type: QuestionComment
type: Comment

http://stackoverflow.com/a/48814978
score: 0
type: Answer
has body: The algorithm you use with multiprocessing is O(n^2) (loop of 1, loop of 2, ... loop of 9999), while the "normal approach" is O(n). Without multiprocessing, the first way took about 3 times longer in my tests. Related: What is a plain English explanation of “Big O” notation?
accepted answer of: http://stackoverflow.com/q/48814788
type: AcceptedAnswer
answers question: http://stackoverflow.com/q/48814788

netlify
tag name: netlify
tags question: http://stackoverflow.com/q/48859444
type: Tag

http://stackoverflow.com/comment/84755799
has text: Thanks @Stranac! I guess I'll remove that version of python and blow everything away and try python3. Hopefully that will fix this! :)
type: Comment
comment on: http://stackoverflow.com/a/48875130
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84750382
type: AnswerComment
has text: You're right, I should've put a code example that *modified* table data - I updated my question. I can't use the ORM layer, but I see what you mean from your code examples, those methods exist in the core layer too. That means my implementation is safe against SQL injection and using the core layer is just fine. Thanks!
type: Comment
score: 1
comment on: http://stackoverflow.com/a/48870677

http://stackoverflow.com/comment/84901638
type: Comment
has text: Thanks Roberto, came back to this fresh and set my work VM .pypirc up again and it does indeed work with twine but not using python setup.py register. That's sufficient for my purposes.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48833470

http://stackoverflow.com/a/71975639
score: 0
has comment: http://stackoverflow.com/comment/127187409
type: Answer
answers question: http://stackoverflow.com/q/48884960
has body: In both solutions, I believe we need to change df1 to df1_list, and change df2 to df2_list in the second sentences.

http://stackoverflow.com/comment/84890048
has text: So this basically means that set_script_timeout does not do anything if there is no execute_async_script call?
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48941597
type: AnswerComment

http://stackoverflow.com/a/48925205
has comment: http://stackoverflow.com/comment/84858779
answers question: http://stackoverflow.com/q/48924970
has comment: http://stackoverflow.com/comment/84860510
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84865069
has body: You can build a simple "language model" for this purpose. It will estimate probability of a phrase, and mark phrases with low average per-word probability as unusual. For word probability estimation, it can use a smoothed word count. This is how the model could look like: import re import numpy as np from collections import Counter class LanguageModel: """ A simple model to measure 'unusualness' of sentences. delta is a smoothing parameter. The larger delta is, the higher is the penalty for unseen words. """ def __init__(self, delta=0.01): self.delta = delta def preprocess(self, sentence): words = sentence.lower().split() return [re.sub(r"[^A-Za-z]+", '', word) for word in words] def fit(self, corpus): """ Estimate counts from an array of texts """ self.counter_ = Counter(word for sentence in corpus for word in self.preprocess(sentence)) self.total_count_ = sum(self.counter_.values()) self.vocabulary_size_ = len(self.counter_.values()) def perplexity(self, sentence): """ Calculate negative mean log probability of a word in a sentence The higher this number, the more unusual the sentence is. """ words = self.preprocess(sentence) mean_log_proba = 0.0 for word in words: # use a smoothed version of "probability" to work with unseen words word_count = self.counter_.get(word, 0) + self.delta total_count = self.total_count_ + self.vocabulary_size_ * self.delta word_probability = word_count / total_count mean_log_proba += np.log(word_probability) / len(words) return -mean_log_proba def relative_perplexity(self, sentence): """ Perplexity, normalized between 0 (the most usual sentence) and 1 (the most unusual)""" return (self.perplexity(sentence) - self.min_perplexity) / (self.max_perplexity - self.min_perplexity) @property def max_perplexity(self): """ Perplexity of an unseen word """ return -np.log(self.delta / (self.total_count_ + self.vocabulary_size_ * self.delta)) @property def min_perplexity(self): """ Perplexity of the most likely word """ return self.perplexity(self.…
type: Answer
has comment: http://stackoverflow.com/comment/84858695
score: 3
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48924970

http://stackoverflow.com/a/48939268
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48938664
upvote count: 1
has body: I've recently written a library for this, oyaml. At the shell: $ pip install oyaml In your Python code, it is a one character change: from oyaml import load # instead of `from yaml import load` Then mappings will be loaded into collections.OrderedDict instances instead of regular dicts, preserving their original ordering from the config file.
type: Answer

http://stackoverflow.com/comment/84644576
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48820394
has text: @ClockSlave Thanks. Yeah, I definitely intend to use `'APP_DIRS' : True` and have app-specific templates in the apps themselves. I'm just not sure the most common approach for the homepage.
score: 0

http://stackoverflow.com/q/48814811
favorite count: 0
tagged with: dask
tagged with: correlation
upvote count: 5
answer count: 0
type: UnansweredQuestion
tagged with: python
tagged with: parallel-processing
downvote count: 0
has title: How to use xarray/dask/pandas/deepgraph for parallel pairwise correlation matrix in Python 3?
type: Question
score: 5
has body: I'm trying to follow the tutorial on xarray's documentation: http://xarray.pydata.org/en/stable/dask.html#automatic-parallelization My ultimate goal is to get a pairwise spearman correlation matrix from a dataset that has ~100,000 attributes which led me to the tutorial mentioned above. I'm testing implementations out on the iris dataset from sklearn but I'm having issues since this type of parallelization syntax is a lot different than that of joblib. I can't figure out how to get the code below to make a pairwise spearman correlation matrix with a resulting shape of (150,150). I showed an example of doing it in pandas but this is not parallel and will take forever on my actual dataset. Does anyone know how to adapt this xarray code to work with creating symmetric correlation measures? If not, can someone direct me to a better method for doing pairwise similarity measures. I'm aware of sklearns pairwise_distance but I'm wondering if that is the only implementation? import bottleneck import pandas as pd import xarray as xr from sklearn.datasets import load_iris X_iris = pd.DataFrame(load_iris().data, index = ["iris_%d" % i for i in range(load_iris().data.shape[0])], columns = [x.split(" (cm)")[0].replace(" ","_") for x in load_iris().feature_names]) da_iris = xr.DataArray(X_iris, dims=["samples", "attributes"]) def covariance_gufunc(x, y): return ((x - x.mean(axis=-1, keepdims=True)) * (y - y.mean(axis=-1, keepdims=True))).mean(axis=-1) def pearson_correlation_gufunc(x, y): return covariance_gufunc(x, y) / (x.std(axis=-1) * y.std(axis=-1)) def spearman_correlation_gufunc(x, y): x_ranks = bottleneck.rankdata(x, axis=-1) y_ranks = bottleneck.rankdata(y, axis=-1) return pearson_correlation_gufunc(x_ranks, y_ranks) def spearman_correlation(x, y, dim): return xr.apply_ufunc( spearman_correlation_gufunc, x, y, input_core_dims=[[dim], [dim]], dask='parallelized', output_dtypes=[float])
tagged with: pairwise

http://stackoverflow.com/q/48847556
upvote count: 1
tagged with: python
downvote count: 1
has answer: http://stackoverflow.com/a/48847592
has body: I made a Python script that generates multiplication problems my only issue is if the multiplication problem is wrong. I need to get the script to display the question again and run through the if statement wouldn't I need to make the if statement a function? If so how would I do that? I'm still pretty new to python any help would be appreciated! import random limit = 12 number_problems = int(input('How many problems do you want to solve? ')) for i in range(number_problems): x, y = random.randint(1,limit), random.randint(1,limit) true_ans = x*y print(x ,'x', y , '=' ) ans = int(input('your answer:')) if ans == true_ans: print("correct!") elif ans &lt; true_ans: print('Your answer is to low') print(x ,'x', y , '=' ) ans = int(input('your answer:')) elif ans &gt; true_ans: print('Your answer is to high') print(x ,'x', y , '=' ) ans = int(input('your answer:')) else: print("incorrect! The answer is ", true_ans)
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84699233
has comment: http://stackoverflow.com/comment/84699366
score: 0
linked to: http://stackoverflow.com/q/23294658
favorite count: 0
has title: Looping if statements Python
has answer: http://stackoverflow.com/a/48847598
type: UnansweredQuestion

http://stackoverflow.com/q/48860804
upvote count: 4
linked to: http://stackoverflow.com/q/26568722
linked to: http://stackoverflow.com/q/33404752
has comment: http://stackoverflow.com/comment/84730549
has comment: http://stackoverflow.com/comment/84725128
has title: Python : How to remove all emojis
favorite count: 0
tagged with: python-3.x
has body: import re emoji_pattern = re.compile("[" u"\U0001F600-\U0001F64F" # emoticons u"\U0001F300-\U0001F5FF" # symbols &amp; pictographs u"\U0001F680-\U0001F6FF" # transport &amp; map symbols u"\U0001F1E0-\U0001F1FF" # flags (iOS) "]+", flags=re.UNICODE) print(emoji_pattern.sub(r'', text)) but still some emoji such:{ , ⭐️, , } appear after filtering , I need to remove all emojis symbol
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/51217909
tagged with: python
answer count: 0
duplicate of: http://stackoverflow.com/q/33404752
downvote count: 1
type: Question
score: 3
has comment: http://stackoverflow.com/comment/84727927
has comment: http://stackoverflow.com/comment/84724748

http://stackoverflow.com/comment/84810543
type: AnswerComment
comment on: http://stackoverflow.com/a/48902593
has text: This doesn't work with `s = ' Feb 21 `. You can add a `?`to stop at the first `"`, like so: `pattern="title=\"(.*?)\""`.
type: Comment
score: 2

http://stackoverflow.com/a/48845387
has body: In order to search how many times S appears in P, you can simply do the following. P = "/home/shan/shan/shan/editshanfile/exe" S = "shan" parts = P.split(S) print (len(parts)-1)
answers question: http://stackoverflow.com/q/48845287
score: 0
type: Answer

http://stackoverflow.com/q/48820655
has title: Finding in siblings subtree with BeautifulSoup4
downvote count: 0
answer count: 1
favorite count: 0
tagged with: beautifulsoup
accepted answer: http://stackoverflow.com/a/48824021
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion
type: Question
has body: Is there a way to find a tag in siblings subtree with BeautifulSoup? The scenario here is that I have already found a tag that I wanted, and I need to grab another tag that is in its sibling's subtree. An equivalent xpath would be #mytag ~ div span #mytag ~ div span{ background: green; color: white; } nope foo bar I can find all siblings using .find_next_siblings but that doesn't search for subtrees. Is there a way that I can do it easily?
has answer: http://stackoverflow.com/a/48824021

python-telegram-bot
tags question: http://stackoverflow.com/q/48903681
tag name: python-telegram-bot
tags question: http://stackoverflow.com/q/48907951
tags question: http://stackoverflow.com/q/48951424
type: Tag
tags question: http://stackoverflow.com/q/48949472

http://stackoverflow.com/q/48876248
type: Question
has body: I received a merge sort function from someone else, here's the code: def mergesort(lst): l = len(lst) if l &lt;= 1: return lst return mergesorted(mergesort(lst[:l//2]), mergesort(lst[l//2:])) def mergesorted(a, b): i, j = 0, 0 la, lb = len(a), len(b) while i &lt; la or j &lt; lb: if i == la or (j != lb and a[i] &gt; b[j]): yield b[j] j += 1 else: yield a[i] i += 1 I'm still trying to understand how yield works, so when I was trying to print the result to test the function, I used m = mergesort([4, 2, 5, 1, 6, 3]) for i in m : print(i) It gave me this error: Traceback (most recent call last): for i in m : la, lb = len(a), len(b) TypeError: object of type 'generator' has no len() Am I using the print statement wrong?
has answer: http://stackoverflow.com/a/48876319
accepted answer: http://stackoverflow.com/a/48876319
has comment: http://stackoverflow.com/comment/84756460
has title: Error in Merge Sort function in yield
upvote count: 1
answer count: 1
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84757236
has comment: http://stackoverflow.com/comment/84756585
tagged with: python
linked to: http://stackoverflow.com/q/7460836
type: AnsweredQuestion
downvote count: 0
score: 1

http://stackoverflow.com/comment/84829484
type: QuestionComment
comment on: http://stackoverflow.com/q/48911487
score: 0
has text: Can you tell us what your code does and how that is different from what you wish it did?
type: Comment

http://stackoverflow.com/a/48884347
has comment: http://stackoverflow.com/comment/84773262
has body: First you'll need to find out whether it is the datageneration or the writing that is taking the time. Easiest would be to seperate the program in logical functions, and use timeit to time these. calculating the data There is a lot of repetition in calculating the model, so we can easily abstract that import csv from itertools import product from pathlib import Path weather_dir = Path('.') / 'data' / 'raw' / 'weather' measurements = { 'precipitation': { 'glob_pattern': "pr*45*d.nc", 'value' = '86400', 'input_filename' = 'precip45.nc', 'output_filename' = 'precip45mm.nc' }, 'tasmax': { 'glob_pattern': "tasmax*45*", 'value' = '273.15', 'input_filename' = 'tasmax45.nc', 'output_filename' = 'tasmax45C.nc' }, 'tasmin': { 'glob_pattern': "tasmin*45*", 'value' = '273.15', 'input_filename' = 'tasmin45.nc', 'output_filename' = 'tasmin45C.nc' }, 'evsps45': { 'glob_pattern': "evsps*45*", 'value' = '86400', 'input_filename' = 'evsps45.nc', 'output_filename' = 'evsps45mm.nc' }, } def get_measurement(cdo, weather_dir, settings): input = weather_dir.glob(settings['glob_pattern']) temp_file = str(weather_dir / settings['input_filename']) out_file = str(weather_dir / settings['input_filename']) cdo.mergetime(input=precip45l, output = temp_file) cdo.mulc( settings['value'], input=temp_file, output=out_file, ) return Dataset(out_file) That part is easily times like this: times = {} data = {} for key, value in measurements.items(): times[key] = timeit.timeit( 'data[key] = get_measurement(cdo, weather_dir, value)', number=1, globals=globals(), ) datetime_model = None times['datetime_model'] = timeit.timeit( '''data['datetime_model'] = netCDF4.num2date( precip45.variables["time"][:], "days since 1949-12-1 00:00:00", )''', number=1, globals=globals(), ) By this abstraction of the calculation, it is also possible to see whether the results have already been calculated. If they are, there is perhaps no reason to do the calculation again def get_measurement_with_cache(cdo, weather_dir, setti…
answers question: http://stackoverflow.com/q/48881883
has comment: http://stackoverflow.com/comment/84773783
score: 0
type: Answer

http://stackoverflow.com/comment/84864584
score: 0
type: Comment
has text: Now I am receiving this error, ValueError: array is too big; `arr.size * arr.dtype.itemsize` is larger than the maximum possible size.
type: AnswerComment
comment on: http://stackoverflow.com/a/48916866

http://stackoverflow.com/q/48902625
type: UnansweredQuestion
tagged with: cufft
type: Question
has answer: http://stackoverflow.com/a/54357444
tagged with: numpy
answer count: 1
tagged with: fft
tagged with: pycuda
score: 0
tagged with: python
has body: I am writing code which can compare between numpy.fft.fft2 and pycuda but the results are not matching. Additionally pycuda results are ambiguous every time. data file : https://nofile.io/f/bjGRQGRVSCG/gauss.npy from pyfft.cuda import Plan import numpy as np from pycuda.tools import make_default_context import pycuda.gpuarray as gpuarray import pycuda.driver as cuda import time import matplotlib.pyplot as plt cuda.init() context = make_default_context() data = np.load('gauss.npy') data_complex = data.astype(np.complex64) start_time = time.time() plan = Plan((32,32)) gpu_data = gpuarray.to_gpu(data_complex) plan.execute(gpu_data) result = gpu_data.get() print("--- %s seconds (FFT calculation pycuda)---" % (time.time() - start_time)) start_time_3 = time.time() result_np = np.fft.fft2(data) #print(result_np) print("--- %s seconds (FFT calculation numpy.fft.fft)---" % (time.time() - start_time)) context.pop() #plt.plot(result) #plt.plot(result_np) I'm starting to wonder whether we can even perform 2D FFT with pycuda?
has title: Getting different results everytime in pycuda FFT

http://stackoverflow.com/q/48840282
has answer: http://stackoverflow.com/a/48840524
tagged with: python-3.6
has title: numpy got installed in Python3.5 but not in Python3.6
score: 0
has answer: http://stackoverflow.com/a/48840918
answer count: 3
tagged with: python-3.5
has body: I have both Python 3.5 and Python 3.6 on my laptop. I am using Ubuntu 16.04. I used pip3 to install numpy. It is working with Python3.5 but not with Python3.6. Please help.
has answer: http://stackoverflow.com/a/48840430
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84684942
type: Question

http://stackoverflow.com/comment/84844438
type: Comment
type: QuestionComment
has text: Don't forget to add a newline
comment on: http://stackoverflow.com/q/48918844
score: 0

pycharm
tags question: http://stackoverflow.com/q/48940743
tags question: http://stackoverflow.com/q/48836945
tags question: http://stackoverflow.com/q/48932596
tags question: http://stackoverflow.com/q/48904701
tags question: http://stackoverflow.com/q/48830033
tags question: http://stackoverflow.com/q/48924787
tags question: http://stackoverflow.com/q/48887603
tag name: pycharm
tags question: http://stackoverflow.com/q/48849920
tags question: http://stackoverflow.com/q/48862762
tags question: http://stackoverflow.com/q/48856881
tags question: http://stackoverflow.com/q/48834216
tags question: http://stackoverflow.com/q/48877570
tags question: http://stackoverflow.com/q/48859607
tags question: http://stackoverflow.com/q/48825031
tags question: http://stackoverflow.com/q/48910356
tags question: http://stackoverflow.com/q/48954908
tags question: http://stackoverflow.com/q/48809409
tags question: http://stackoverflow.com/q/48953202
tags question: http://stackoverflow.com/q/48825487
tags question: http://stackoverflow.com/q/48933470
tags question: http://stackoverflow.com/q/48821969
tags question: http://stackoverflow.com/q/48853947
tags question: http://stackoverflow.com/q/48935441
tags question: http://stackoverflow.com/q/48895867
tags question: http://stackoverflow.com/q/48923721
type: Tag
tags question: http://stackoverflow.com/q/48860709
tags question: http://stackoverflow.com/q/48859452
tags question: http://stackoverflow.com/q/48878497
tags question: http://stackoverflow.com/q/48854809
tags question: http://stackoverflow.com/q/48895923
tags question: http://stackoverflow.com/q/48915008
tags question: http://stackoverflow.com/q/48917775
tags question: http://stackoverflow.com/q/48924292
tags question: http://stackoverflow.com/q/48947494
tags question: http://stackoverflow.com/q/48912638
tags question: http://stackoverflow.com/q/48824351

http://stackoverflow.com/q/48873768
upvote count: 2
type: UnansweredQuestion
tagged with: python
tagged with: pygame
score: 2
type: Question
has comment: http://stackoverflow.com/comment/84751807
downvote count: 0
has title: Check Capslock In Pygame.Key
has comment: http://stackoverflow.com/comment/84751989
answer count: 1
has comment: http://stackoverflow.com/comment/84751432
tagged with: capslock
tagged with: key
has comment: http://stackoverflow.com/comment/84751836
favorite count: 0
tagged with: python-3.x
has body: I wrote a notetaking app, which provides with easier usage, but I cannot check whether the caps lock button is on or off. I can get the value when it is turned on, but there is not any response when it is turned off. In other words, I can get the output of the key when the led is turned on, but not when it is turned off. import pygame import random import time import subprocess from pygame.locals import * time_a = time.time() slides = [] POS = (0,0) capslock = False altcizgi = False italic = False bold = False yazi = "" character = "" time_d = 0 sayim = 0 time_b = 0 buyukluk = 30 liste = [] r = "" rty = "" time_c = 0 durum = 0 sol_bas = -100 WHITE= (255,255,255) BLACK = (0,0,0) GREY = (200,200,200) ORANGE = (200, 100, 50) CYAN = (0, 255, 255) MAGENTA = (255, 0, 255) TRANS = (1, 1, 1) firca_ucu = 3 # initializations pygame.init() infoObject = pygame.display.Info() screen = pygame.display.set_mode((infoObject.current_w, infoObject.current_h)) pygame.display.set_caption('Noting') pygame.display.set_mode((infoObject.current_w, infoObject.current_h), pygame.FULLSCREEN) background = pygame.Surface(screen.get_size()) background = background.convert() color = (0, 0, 0) startPos = (0, 0) clock = pygame.time.Clock() background.fill((255, 255, 255)) image = pygame.image.save(background,'image.png') font = pygame.font.SysFont('arial', 150) colorName = "Black" welcomeFont = pygame.font.SysFont('arial', 50) colorConfigFont = pygame.font.SysFont('arial', 35) welcomeScreen = True # mainloop while 1: # welcomescreen while welcomeScreen: for i in pygame.event.get(): mainScreenPressed = pygame.key.get_pressed() screen.fill((0,0,0)) screen.blit(welcomeFont.render("Paint Program Keys", True, (0, 255, 0)), (100, 50)) screen.blit(colorConfigFont.render("Left: Decrease Punto", True, (0, 255, 0)), (900, 150)) screen.blit(colorConfigFont.render("Right: Increase Punto", True, (0, 255, 0)), (900, 200)) screen.blit(colorConfigFont.render("Up: Increase Brush Size", True, (0, 255, 0)), (900, 250)…
has answer: http://stackoverflow.com/a/48874068

http://stackoverflow.com/comment/84957463
comment on: http://stackoverflow.com/a/48973127
type: AnswerComment
score: 0
type: Comment
has text: Well, in this case you need to pick the other approach mentioned in the first sentence. Or give this slightly modifier version using `onchanges` a try.

http://stackoverflow.com/comment/84754419
type: Comment
has text: Ah, sorry, you need to pass the response as an argument to the item loader for it to be accessible through `context`. Will update my answer to mention this.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48874804

http://stackoverflow.com/a/48847453
score: 0
type: Answer
answers question: http://stackoverflow.com/q/48847387
has body: Python has no switch statement. The common replacement - as you already seem to know - is using a dictionary to dispatch different behaviors. With that being the case however, the syntax you're trying to use simply isn't allowed for dictionaries. Dictionary key values should be expressions. You can work around this by using anonymous functions and setattr. Here's a self-contained example: &gt;&gt;&gt; class Dummy: pass &gt;&gt;&gt; dummy = Dummy() &gt;&gt;&gt; dic = { 'a': lambda: setattr(dummy, 'a', 0), 'b': lambda: setattr(dummy, 'b', 0) } &gt;&gt;&gt; dic.get('a', lambda: print("Invalid Option"))() &gt;&gt;&gt; dummy.a 0 &gt;&gt;&gt; dic.get('b', lambda: print("Invalid Option"))() &gt;&gt;&gt; dummy.b 0 &gt;&gt;&gt; dic.get('x', lambda: print("Invalid Option"))() Invalid Option &gt;&gt;&gt;

http://stackoverflow.com/comment/84783898
score: 0
comment on: http://stackoverflow.com/q/48888713
type: Comment
type: QuestionComment
has text: And then the detailed view of the specific game would look like `/competitions/<int:competition_id>/games/<int:game_id>/`

http://stackoverflow.com/comment/84901544
type: Comment
comment on: http://stackoverflow.com/q/48947682
type: QuestionComment
has text: Don't you mean `datas.append(mail)` ? You also miss a `:` after your for. Please provide more information about the error you get.
score: 0

dictionary
tags question: http://stackoverflow.com/q/48814917
tags question: http://stackoverflow.com/q/48928536
tags question: http://stackoverflow.com/q/48929787
tags question: http://stackoverflow.com/q/48816332
tags question: http://stackoverflow.com/q/48932732
tags question: http://stackoverflow.com/q/48892119
tags question: http://stackoverflow.com/q/48938908
tags question: http://stackoverflow.com/q/48940547
tags question: http://stackoverflow.com/q/48835765
tags question: http://stackoverflow.com/q/48874110
tags question: http://stackoverflow.com/q/48924123
tags question: http://stackoverflow.com/q/48853499
tags question: http://stackoverflow.com/q/48827884
tags question: http://stackoverflow.com/q/48953557
tags question: http://stackoverflow.com/q/48894060
tags question: http://stackoverflow.com/q/48941157
tags question: http://stackoverflow.com/q/48956985
tags question: http://stackoverflow.com/q/48954697
tags question: http://stackoverflow.com/q/48823942
tags question: http://stackoverflow.com/q/48889368
tags question: http://stackoverflow.com/q/48923009
tags question: http://stackoverflow.com/q/48822166
tags question: http://stackoverflow.com/q/48895906
tags question: http://stackoverflow.com/q/48848815
tags question: http://stackoverflow.com/q/48926974
tags question: http://stackoverflow.com/q/48864578
tags question: http://stackoverflow.com/q/48827614
tags question: http://stackoverflow.com/q/48887674
tags question: http://stackoverflow.com/q/48952443
tags question: http://stackoverflow.com/q/48924491
tags question: http://stackoverflow.com/q/48954446
tags question: http://stackoverflow.com/q/48883750
tags question: http://stackoverflow.com/q/48824514
tags question: http://stackoverflow.com/q/48844007
tags question: http://stackoverflow.com/q/48910302
tags question: http://stackoverflow.com/q/48930927
tags question: http://stackoverflow.com/q/48833434
tags question: http://stackoverflow.com/q/48956785
tags question: http://stackoverflow.com/q/48824056
tags question: http://stackoverflow.com/q/48844705
tags question: http://stackoverflow.com/q/48838029
tags question: http://stackoverflow.com/q/48927191
tags question: http://stackoverflow.com/q/48855674
tags question: http://stackoverflow.com/q/48915207
tags question: http://stackoverflow.com/q/48832823
tags question: http://stackoverflow.com/q/48842893
tags question: http://stackoverflow.com/q/48811332
tags question: http://stackoverflow.com/q/48900343
tags question: http://stackoverflow.com/q/48857528
tag name: dictionary
tags question: http://stackoverflow.com/q/48902411
tags question: http://stackoverflow.com/q/48897868
tags question: http://stackoverflow.com/q/48864096
tags question: http://stackoverflow.com/q/48882293
tags question: http://stackoverflow.com/q/48907158
tags question: http://stackoverflow.com/q/48840867
tags question: http://stackoverflow.com/q/48945254
tags question: http://stackoverflow.com/q/48936869
tags question: http://stackoverflow.com/q/48846997
tags question: http://stackoverflow.com/q/48887198
tags question: http://stackoverflow.com/q/48960752
tags question: http://stackoverflow.com/q/48883493
tags question: http://stackoverflow.com/q/48842543
tags question: http://stackoverflow.com/q/48825753
tags question: http://stackoverflow.com/q/48828586
tags question: http://stackoverflow.com/q/48939473
tags question: http://stackoverflow.com/q/48857168
tags question: http://stackoverflow.com/q/48858170
tags question: http://stackoverflow.com/q/48848618
tags question: http://stackoverflow.com/q/48828243
tags question: http://stackoverflow.com/q/48884965
tags question: http://stackoverflow.com/q/48810701
tags question: http://stackoverflow.com/q/48891298
tags question: http://stackoverflow.com/q/48917135
tags question: http://stackoverflow.com/q/48902085
tags question: http://stackoverflow.com/q/48935409
tags question: http://stackoverflow.com/q/48877620
tags question: http://stackoverflow.com/q/48910709
tags question: http://stackoverflow.com/q/48821518
tags question: http://stackoverflow.com/q/48931576

http://stackoverflow.com/q/48960034
has title: Python Class Syntax Error
upvote count: 2
downvote count: 3
type: Question
score: -1
tagged with: class
answer count: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84928673
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48960244
tagged with: python
tagged with: pygame
has body: I have been following a guide to make my game. However, when I try to run the program I get a syntax Error with the Class Circle and not sure why? I can't figure out the reason and I'm sure there are more issue afterward the Class Circle but can't fix it. import pygame from pygame.locals import * from uagame import Window import time import random def main(): window = Window('Pong', 500, 400) window.set_auto_update(False) game = Game(window) game.play() window.close() class Rect: def __init__(self, center, radius, color, window): self.center = center self.radius = radius self.color = color self.window = window def draw(self): pygame.draw.rect(self.window.get_surface(), self.color, Rect((100, 200), (20, 30)) class Circle: # Syntax Error: class Circle:: &lt;string&gt;, line 28, pos 5 def __init__(self, center, radius, color, window): self.center = center self.radius = radius self.color = color self.window = window def draw(self): pygame.draw.circle(self.window.get_surface(), self.color, self.center,self.radius) def get_color(self): return self.color def move(self): window_size = (self.window.get_width() , self.window.get_height()) for index in range(0,2): self.center[index] = (self.center[index] + 1) % window_size[index] def enlarge(self,increment): self.radius = self.radius + increment class Game: def __init__(self, window): self.window = window self.bg_color = pygame.Color('black') self.fg_color = 'green' self.rect_color = 'green' self.pause_time = 0.02 self.close_clicked = False self.continue_game = True self.circle = Ball([200,200], 20, pygame.Color(self.fg_color),window) self.rect = Rect([100,200], 50 , pygame.Color(self.fg_color),window) self.radius_increment = 5 def play(self): while not self.close_clicked: self.handle_event() self.draw() if self.continue_game: self.update() self.decide_continue() time.sleep(self.pause_time) def handle_event(self): event = pygame.event.poll() if event.type == QUIT: self.close_clicked = True elif event.type == MOUSEBUTTONUP and …

http://stackoverflow.com/q/48902469
favorite count: 0
tagged with: beautifulsoup
has answer: http://stackoverflow.com/a/48902688
type: UnansweredQuestion
tagged with: python
answer count: 4
linked to: http://stackoverflow.com/q/2612548
has answer: http://stackoverflow.com/a/48902685
has comment: http://stackoverflow.com/comment/84810145
has answer: http://stackoverflow.com/a/48902593
upvote count: 0
tagged with: web-scraping
type: Question
has title: How to Extract Text from Inside " Python
has body: Doing some web scraping and I need to extract the date from inside a HTML tag that looks something like this: Feb 21 I need to pull out the text at title, as this is the full date. I have tried: s = ' Feb 21 ' l = s.split('"')[1::2] print l[1] However I get the error "TypeError: 'NoneType' object is not callable"
score: -1
tagged with: substring
downvote count: 1
has answer: http://stackoverflow.com/a/48902594
tagged with: string
has comment: http://stackoverflow.com/comment/84810187

http://stackoverflow.com/comment/84833066
type: AnswerComment
has text: Apperently the bytes I am sending have to be in hex representation - how would I do that?
type: Comment
comment on: http://stackoverflow.com/a/48911970
score: 0

http://stackoverflow.com/comment/84852800
type: QuestionComment
has text: In `__str__():` you have `self.read = (self.read + 1) % self.size`. So `self.read` gets updated. But updating the instance attributes in `__str__` seems like a rather bad idea....
score: 1
comment on: http://stackoverflow.com/q/48923065
type: Comment

http://stackoverflow.com/comment/84977284
score: 0
type: Comment
type: AnswerComment
has text: If you want SSL you need to configure it with the Web Server not Django. When you say talking to multiple server, does that mean that you are calling it from the client or does the server make the request
comment on: http://stackoverflow.com/a/48942911

http://stackoverflow.com/a/72627508
answers question: http://stackoverflow.com/q/48940344
score: 0
type: Answer
has body: patool can handle password protected archives. You only need to add verbosity argument to 1 as shown: import patoolib patoolib.extract_archive(r'your file path', outdir=r"folder path", verbosity=1) now, cmd opened in new window like this and asked you to enter the password: if you have other files in it, it asked you again. you can press 'A' to apply this to all files in it like this: If you want to use unrar libray (I don't recommend it because patool is simpler and more comprehensive library), you should download UnRAR.dll from Extras tab in Rarlab.Then install it and add it to environment variables like this: and then click on environment variables: and then click on new: and then complete it as: Variable name: UNRAR_LIB_PATH Variable value: C:\Program Files(x86)\UnrarDLL\x64\UnRAR64.dll if your windows is 32-bit complete it as: Variable name: UNRAR_LIB_PATH Variable value: C:\Program Files (x86)\UnrarDLL\UnRAR.lib I hope this help you.

http://stackoverflow.com/comment/84759534
type: Comment
has text: @coldspeed i dont understand can you help how to import and save. Can you give me entire code plz help me
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48877329

http://stackoverflow.com/comment/84882287
type: QuestionComment
comment on: http://stackoverflow.com/q/48937336
score: 0
type: Comment
has text: @Haleemur Ali How do I wrap executemany in a transaction?

http://stackoverflow.com/a/48928772
type: AcceptedAnswer
has body: The key here is adding the path to the folder containing the environment(s) to the user's conda configuration file .condarc. Like this: envs_dirs: - C:\full\path\to\environments\folder This makes all the environments (subfolders within) available to the user. It does not appear to be possible to make a specific, named environment available. As has been pointed out, you can create an environment in a specific location using the -p flag, and then add the parent directory to the configuration file, but this is not a requirement. This may be useful, however, to avoid permissions errors if sharing environments that exists in protected user areas. On Windows 10, my user configuration file was in C:\Users\&lt;my-user-name&gt;\, and I just added the above text to the end of it.
type: Answer
has comment: http://stackoverflow.com/comment/92259309
upvote count: 19
downvote count: 1
answers question: http://stackoverflow.com/q/48871289
has comment: http://stackoverflow.com/comment/99523226
accepted answer of: http://stackoverflow.com/q/48871289
score: 18

http://stackoverflow.com/comment/84887743
type: Comment
comment on: http://stackoverflow.com/a/48907135
score: 0
type: AnswerComment
has text: I tried it in the Python3.6 32 bit thingy but it said there is a syntax error. Can you clarify which command promp to use? P.S. I use a Windows 7

oop
tags question: http://stackoverflow.com/q/48827829
tags question: http://stackoverflow.com/q/48847212
tags question: http://stackoverflow.com/q/48846133
tags question: http://stackoverflow.com/q/48962208
tags question: http://stackoverflow.com/q/48910863
tag name: oop
tags question: http://stackoverflow.com/q/48935836
tags question: http://stackoverflow.com/q/48897299
tags question: http://stackoverflow.com/q/48809682
tags question: http://stackoverflow.com/q/48906207
tags question: http://stackoverflow.com/q/48868228
tags question: http://stackoverflow.com/q/48920795
tags question: http://stackoverflow.com/q/48807942
tags question: http://stackoverflow.com/q/48814211
tags question: http://stackoverflow.com/q/48845989
tags question: http://stackoverflow.com/q/48911576
tags question: http://stackoverflow.com/q/48849438
type: Tag
tags question: http://stackoverflow.com/q/48934975
tags question: http://stackoverflow.com/q/48875290

http://stackoverflow.com/a/48854817
upvote count: 1
has body: Try: filtered = data[(data.column3 != "-") &amp; (data.column4 != "-") &amp; (data.column5 != "-") &amp; (data.column6 != "-") &amp; (data.column7 != "-")]
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48854768

http://stackoverflow.com/comment/84772276
score: 0
comment on: http://stackoverflow.com/q/48883694
type: Comment
type: QuestionComment
has text: It is difficult to offer solutions when the problem statement is simply, ["it doesn't work"](http://idownvotedbecau.se/itsnotworking/). Please [edit] your question to give a more complete description of what you expected to happen and how that differs from the actual results. See [ask] for hints on what makes a good explanation.

http://stackoverflow.com/q/48840025
has body: I have developed a rest API using Flask to expose a Python Keras Deep Learning model (CNN for text classification). I have a very simple script that loads the model into memory and outputs class probabilities for a given text input. The API works perfectly locally. However, when I git push heroku master, I get Compiled slug size: 588.2M is too large (max is 500M). The model is 83MB in size, which is quite small for a Deep Learning model. Notable dependencies include Keras and its tensorflow backend. I know that you can use GBs of RAM and disk space on Heroku. But the bottleneck seems to be the slug size. Is there a way to circumvent this? Or is Heroku just not the right tool for deploying Deep Learning models?
tagged with: deep-learning
answer count: 7
has answer: http://stackoverflow.com/a/49025547
tagged with: keras
favorite count: 0
has comment: http://stackoverflow.com/comment/84692506
possible better answer: http://stackoverflow.com/a/67769512
tagged with: python
has answer: http://stackoverflow.com/a/67769512
has answer: http://stackoverflow.com/a/49088981
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/61806979
has title: Heroku: deploying Deep Learning model
has comment: http://stackoverflow.com/comment/85115623
score: 11
has answer: http://stackoverflow.com/a/49099164
has answer: http://stackoverflow.com/a/66046664
downvote count: 1
tagged with: tensorflow
type: Question
tagged with: heroku
has answer: http://stackoverflow.com/a/49025400
upvote count: 12
accepted answer: http://stackoverflow.com/a/49099164

http://stackoverflow.com/comment/84768607
type: Comment
has text: Maybe use a virtual machine to use it.
comment on: http://stackoverflow.com/a/48882154
score: 0
type: AnswerComment

http://stackoverflow.com/a/48805334
has body: This is one method, if you wish to avoid categoricals: orderdic = dict(zip(myorder, range(len(myorder)))) df = df.assign(order=df.index.to_series().map(orderdic))\ .sort_values('order').drop('order', 1) # Value # Monday 6 # Monday 6 # Tuesday 9 # Tuesday 1 # Wednesday 1 # Wednesday 3 # Thursday 0 # Thursday 7
type: Answer
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48804909
downvote count: 0

http://stackoverflow.com/comment/84879980
type: QuestionComment
score: 1
has text: @Animamorta And because you are aesthetically displeased, you rather call a function twice? Ooookeh.
comment on: http://stackoverflow.com/q/48936533
type: Comment

http://stackoverflow.com/comment/84743706
score: 0
type: Comment
has text: 502 is Bad Gateway, so your urls, you are trying to download from are not going anywhere
type: AnswerComment
comment on: http://stackoverflow.com/a/48869462

http://stackoverflow.com/q/48880068
answer count: 0
downvote count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84765850
type: Question
has body: When I try to import PyvtTbl and DataFrame, this error coming. ImportError Traceback (most recent call last) &lt;ipython-input-35-452740a411c0&gt; in &lt;module&gt;() ----&gt; 1 from pyvttbl import DataFrame 2 from base import PyvtTbl, DataFrame ~\AppData\Local\Continuum\lib\site-packages\pyvttbl\__init__.py in &lt;module&gt;() 8 # This software is funded in part by NIH Grant P20 RR016454. 9 ---&gt; 10 from base import PyvtTbl, DataFrame 11 12 from misc import * ImportError: cannot import name 'PyvtTbl' I already installed these packages using pip install.
favorite count: 0
tagged with: python-3.x
upvote count: 2
tagged with: python
has title: ImportError: cannot import name 'PyvtTbl'
has comment: http://stackoverflow.com/comment/88704583
score: 2

http://stackoverflow.com/a/48901176
has body: If you can swap this: batch = root[i:(i + (len(root)))] batch = np.append(batch, C[i]) For this: batch = np.append(batch, [C[i]], axis=0) axis allows you to append two matrices on a particular dimension. So we make C[i] into a matrix and append it in dimension 0. I am not sure what the intention of this batch = root[i:(i + (len(root)))] is but it shortens batch to a matrix the size of root every time so it will not increase in size. It actually shrinks as you near the end of root. Also C is not always 1000 vectors. Making them unique removes some.
accepted answer of: http://stackoverflow.com/q/48900858
type: Answer
answers question: http://stackoverflow.com/q/48900858
downvote count: 0
has comment: http://stackoverflow.com/comment/84829633
score: 1
upvote count: 1
type: AcceptedAnswer

http://stackoverflow.com/comment/84858844
has text: Sorry, autocomplete fail, that should have been "all addresses".
type: AnswerComment
comment on: http://stackoverflow.com/a/48926353
score: 0
type: Comment

http://stackoverflow.com/comment/84668868
score: 0
type: Comment
type: QuestionComment
has text: Sorry, actually I cannot extract the code, and when I rewrite a small example, it works as expected... The problem lies somewhere else obviously.
comment on: http://stackoverflow.com/q/48832024

http://stackoverflow.com/comment/84809487
score: 1
comment on: http://stackoverflow.com/q/48902085
type: Comment
type: QuestionComment
has text: I suggest reading up on [zip](https://docs.python.org/3/library/functions.html#zip) function

http://stackoverflow.com/a/50281532
downvote count: 0
has body: Assuming you have a dummy project that looks like: src/ file.py file2.py tests/ test1.py test2.py 3rdparty/ skip.py setup.py And you want to analyze everything except the 3rdparty folder, you can execute the following commands: cov-configure --python cov-build --dir foo \ --no-command \ --fs-capture-search ./ \ --fs-capture-search-exclude-regex ./3rdparty cov-analyze --dir foo \ --all \ --aggressiveness-level high cov-format-errors --dir foo \ --html-output results cov-commit-defects --dir foo \ --host coverity.mycompany.com \ --stream MYSTREAM \ --auth-key-file mycoverity.key Explanation: cov-configure --python Inform Coverity that you will be scanning Python code cov-build Inform Coverity to build your code. Since Python is not compiled but interpreted, does not need to be built (--no-command) but Coverity still needs to know where to get the sources from (--fs-capture-search). You can add more than one --fs-capture-search or --fs-capture-search-exclude-regex arguments to suit your needs. The "built" sources will be placed into the foo directory (--dir foo). cov-analyze Perform the actual code analysis on the "built" sources placed at foo. There's a ton of switches you can pass here but I think that for Python those would be enough. cov-format-errors Generate a useful HTML report inside a new results folder. Other output formats are supported, not just HTML. cov-commit-defects Commit the scan results into your Coverity Connect central server at the specified stream. For the commit to work you have to identify yourself using a Coverity key file (you download this key from the Coverity server Web UI), and this file needs to be readonly for the user (i.e. chmod 400 mycoverity.key) NOTE: All the above works fine against my company's internal Coverity server (i.e. paid product). For the free for open source version of Coverity, things might be different (have not tested it). For the later case I'd look at some of the open source projects: https://github.com/search?q=--…
answers question: http://stackoverflow.com/q/48820620
type: Answer
score: 2
upvote count: 2

http://stackoverflow.com/a/48845576
answers question: http://stackoverflow.com/q/48845560
has comment: http://stackoverflow.com/comment/84695651
score: 5
has comment: http://stackoverflow.com/comment/84695386
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48845560
has comment: http://stackoverflow.com/comment/84695358
has body: Sort by . separated first int value as sorting key: sorted(lst, key=lambda x: int(x.split('.')[0])) Example: In [20]: lst = ["1. Banana", "2. Pear", "11. Apple", "5. Grapes", "4. Orange"] In [21]: sorted(lst, key=lambda x: int(x.split('.')[0])) Out[21]: ['1. Banana', '2. Pear', '4. Orange', '5. Grapes', '11. Apple']
type: Answer
upvote count: 6
has comment: http://stackoverflow.com/comment/84695333
has comment: http://stackoverflow.com/comment/84695687
downvote count: 1

http://stackoverflow.com/q/48815921
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48816396
tagged with: python
has answer: http://stackoverflow.com/a/48816115
has comment: http://stackoverflow.com/comment/84636132
type: Question
has body: I have below code. It is part of bigger code and i am just providing a snippet to show the problem. When i run below code i get the error AttributeError: 'str' object has no attribute 'values'. df['URL'].values[0] runs fine. I want copy text values from URL field into new field called pdf_text and i want to do this one value at a time. Therefore I am using a function. In my real code, i take values from URL column and open those files and do further processing. sales = [{'account': 'credit cards', 'Jan': '150 jones', 'Feb': '200 .jones', 'URL': 'ea2018-001.pdf'}, {'account': '1', 'Jan': 'Jones', 'Feb': '210', 'URL': ''}, {'account': '1', 'Jan': '50', 'Feb': '90', 'URL': 'ea2017-104.pdf' }] df = pd.DataFrame(sales) def pdf2text(url): url=url.values[0] return url # abc= (df.assign(pdf_text = df['URL'].apply(pdf2text)))
has title: Python error when getting absolute value from a cell while using function
score: 0
answer count: 2
tagged with: pandas
tagged with: string

http://stackoverflow.com/comment/84995020
type: Comment
type: QuestionComment
has text: Is it possible that the API call is failing, and that's why there's no "source_enum_s" to reference?
comment on: http://stackoverflow.com/q/48953184
score: 0

http://stackoverflow.com/comment/84669855
has text: up, down, left, right ?? the models are not graphics, if you are going to handle a lot of data and have efficiency problems do not use QStandardItemModel, create your own model. the information display part is handled by QTableView, it is optimized to show that kind of information. what do you want to do?
score: 0
comment on: http://stackoverflow.com/q/48832526
type: QuestionComment
type: Comment

http://stackoverflow.com/comment/84700939
type: Comment
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48848537
has text: Hey Thanks heaps for your response, I now get UnicodeDecodeError: 'utf-8' codec cant decode byte 0xc4 in position 10: invalid continuation byte

http://stackoverflow.com/a/48951713
answers question: http://stackoverflow.com/q/48951629
type: AcceptedAnswer
upvote count: 7
type: Answer
has body: One solution could be building a dict with values you want to pass to the function, modified depending on special value. Then use python unpacking to expand it as a list of named arguments to the function you want to call: def do_a_thing(stuff, special=False): kwargs = dict( first=os.environ['first'], second=stuff['second'], third=stuff['third'] fourth='Some Value', fifth=False, seventh='example', eighth=True ) if special: kwargs['sixth'] = 'IMPORTANT_VALUE' return some.library.func(**kwargs)
downvote count: 0
score: 7
accepted answer of: http://stackoverflow.com/q/48951629

http://stackoverflow.com/comment/84772668
score: 0
has text: giving OP benefit of the doubt, he may looking for an extendible / generic function. this is not an unreasonable thing to desire.
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48883792

http://stackoverflow.com/q/48912943
tagged with: py2app
type: Question
has comment: http://stackoverflow.com/comment/85004806
has answer: http://stackoverflow.com/a/49000157
has title: py2App working in alias mode and not working in the final distribution file
downvote count: 0
answer count: 1
has body: So I finally have an app working while in py2app alias mode. I can open the file and it works well. After I remove the build &amp; dist files and run python setup.py py2app, the package receives an error. Why would it be doing this? magnolia.py: from splinter import Browser import webbrowser with Browser() as browser: # Visit URL url = "http://magnolia.msstate.edu/k12/login.asp" browser.visit(url) browser.fill('username', 'magn0897') # Find and click the 'search' button button = browser.find_by_name('btnG') # Interact with elements browser.find_by_xpath('//html/body/div[3]/div[1]/div/section/form/input').click() #Open browser in new tab to keep browser open webbrowser.open_new_tab('http://magnolia.msstate.edu/k12/elementary.asp') #source: https://splinter.readthedocs.io/en/latest/mouse-interaction.html #Instructions: # Activate: go into bin.... $source activate # To Update Requirements File: $pip freeze &gt; requirements.txt #http://www.marinamele.com/from-a-python-script-to-a-portable-mac-application-with-py2app setup.py: from setuptools import setup APP = ['magnolia.py'] DATA_FILES = [] OPTIONS = {'argv_emulation': True,'iconfile': 'robot.icns'} setup( app=APP, data_files=DATA_FILES, options={'py2app': OPTIONS}, setup_requires=['py2app'], ) After $open magnolia.app in terminal:
favorite count: 0
type: UnansweredQuestion
tagged with: python
score: 2
upvote count: 2

http://stackoverflow.com/comment/84918930
type: QuestionComment
has text: Please read why a [screenshot of HTML or code or error is a bad idea](https://meta.stackoverflow.com/questions/303812/discourage-screenshots-of-code-and-or-errors). Consider updating the Question with formatted text based relevant HTML, code trials and error stack trace.
score: 0
comment on: http://stackoverflow.com/q/48953127
type: Comment

http://stackoverflow.com/comment/84614116
type: Comment
has text: For your usage, it seems that [selenium](http://www.seleniumhq.org/) might be more adapted.
score: 0
type: QuestionComment
comment on: http://stackoverflow.com/q/48805574

http://stackoverflow.com/comment/84714905
comment on: http://stackoverflow.com/a/48855548
score: 1
type: AnswerComment
type: Comment
has text: I think you misunderstood my idea. The list is not sorted based on the numbers themselves but based on the index they are in each pair of list. For example I have a pair (70,62). When I put them together, 70 should stay before 62 in a new list.

http://stackoverflow.com/comment/84649054
score: 0
type: QuestionComment
type: Comment
comment on: http://stackoverflow.com/q/48822567
has text: Exactly FlyingTeller sir I don't see the new text in a file

http://stackoverflow.com/comment/88288108
score: 1
has text: As far as I understand the solution they propose, they have regular time intervals, which is not the case in my situation.
comment on: http://stackoverflow.com/a/50598876
type: AnswerComment
type: Comment

http://stackoverflow.com/q/48902856
has title: Not able to import pandas in python 2.7.14 in Ubuntu 16.04
has comment: http://stackoverflow.com/comment/84811145
upvote count: 2
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48903311
tagged with: python
has body: Not able to work on pandas in python 2.7.14 ubuntu 16.02. When I try to install pandas module using pip install pandas It shows requirement already satisfied. If we try to import in python program, it gives no module named numpy. I tried uninstalling pandas package, it but didn't work for me. It is working fine with python 2.7.12. But I want it to be working in latest version of python 2.7 I used below commands to upgrade default python 2.7.12 in ubuntu to python 2.7.14 Download using the following command: version=2.7.14 cd ~/Downloads/ wget https://www.python.org/ftp/python/$version/Python-$version.tgz Extract and go to the directory: tar -xvf Python-$version.tgz cd Python-$version Now, install using the command you just tried, using checkinstall instead to make it easier to uninstall if needed: ./configure sudo make install Is there anything wrong in upgrading python version?
score: 2
tagged with: ubuntu-16.04
type: Question
answer count: 2
downvote count: 0
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84811199
tagged with: pandas
has comment: http://stackoverflow.com/comment/95553478
has comment: http://stackoverflow.com/comment/84811504
has answer: http://stackoverflow.com/a/48902957
favorite count: 0

http://stackoverflow.com/q/48892614
score: 2
answer count: 1
downvote count: 0
has answer: http://stackoverflow.com/a/48892690
favorite count: 0
has comment: http://stackoverflow.com/comment/84790831
upvote count: 2
has body: I have a string of the following format: x = '2018-02-15-11' I need to convert this to a date format. I have tried: from datetime import date from datetime import time from datetime import datetime dhs = '2018-02-15-11' x = datetime.strptime(dhs, '%Y-%M-%d-%H') print x However, the output is 2018-01-15 11:02:00 I need the output in the format (as date object): 2018-01-15-11 Am I missing something here?
has comment: http://stackoverflow.com/comment/84790819
tagged with: datetime
accepted answer: http://stackoverflow.com/a/48892690
tagged with: python
has title: String to date formatting
type: AnsweredQuestion
type: Question
has comment: http://stackoverflow.com/comment/84790835

http://stackoverflow.com/q/48895003
type: Question
has answer: http://stackoverflow.com/a/48895047
has title: Type Error argument 1 needs to be a iterator
has body: I'm currently trying to copy data over from my filteredData.csv to my average2016.csv which I have done, but when I'm going through and trying to split the date I'm getting File "U:/CISP253/Final/test", line 9, in &lt;module&gt; readCSV = csv.reader(csvfile, delimiter=',') TypeError: argument 1 must be an iterator &gt;&gt;&gt; as my error. import shutil import csv import collections with open("filteredData.csv", "wb") as csvfile: csvfile.close() with open("average2016.csv", "w") as csvfile2: shutil.copyfile('filteredData.csv', 'average2016.csv') readCSV = csv.reader(csvfile2, delimiter=',') result = collections.defaultdict(list) for row in readCSV: year = row[1].split("-")[0] result[year].append(row) csvfile2.close() I made the change to readCSV = csv.reader(csvfile2, delimiter=',') that was necessary and that was to turn csvfile to csvfile2 as was mentioned. Also is this the best way to go about splitting the date? Thank you
has comment: http://stackoverflow.com/comment/91280048
answer count: 1
downvote count: 0
favorite count: 0
accepted answer: http://stackoverflow.com/a/48895047
has comment: http://stackoverflow.com/comment/84796124
has comment: http://stackoverflow.com/comment/84796624
tagged with: python
has comment: http://stackoverflow.com/comment/84796762
type: AnsweredQuestion
score: 1
upvote count: 1

http://stackoverflow.com/comment/84736909
type: QuestionComment
has text: no,seek sets the pointer - both for reading and writing.
type: Comment
score: 0
comment on: http://stackoverflow.com/q/48866806

http://stackoverflow.com/comment/84807574
score: 1
comment on: http://stackoverflow.com/q/48891003
type: QuestionComment
has text: @wjmccann: Thanks. For those inputs, it looks as though your code is giving the right answer. The sum of the distances from the origin will be 3. The sum of the distances to the point `(-1/sqrt(3), 0)` that your code found is `1 + sqrt(3)`, which is smaller.
type: Comment

http://stackoverflow.com/q/48842902
favorite count: 0
accepted answer: http://stackoverflow.com/a/48843009
has title: How to get rid of duplicates when you append a class instance to another class's list variable?
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48843009
tagged with: class
has body: So I am trying to add a unit to the The_Term Class but the unit_type (core and foundation) cannot be repeated in the unitlist. After adding two units of the same type on to the unitlist it is still appending both units into the list instead of rejecting the second addition. class The_Unit(): def __init__(self,code,name, unit_type, prereq, maxStuNum, students): self.code = code self.name = name self.unit_type = unit_type self.prereq = list(prereq) self.maxStuNum = maxStuNum self.students = list(students) class The_Term(): def __init__(self,termcode, startdate, enddate, unitlist): self.termcode = termcode self.startdate = startdate self.enddate = enddate self.unitlist = list(unitlist) def __str__(self): return 'Term Code: ' + self.termcode + \ '\nStart Date: ' + self.startdate + \ '\nEnd Date: ' + self.enddate + \ '\nUnitlist: ' + ','.join((str(x) for x in self.unitlist)) def addunit(self,unit): for x in self.unitlist: if x == 'foundation' or 'core': print("error") else: self.unitlist.append(unit.unit_type) self.unitlist.append(unit.code) unit1 = The_Unit('FIT9133','programming foundations in python','foundation', ['none'],'3', ['saki','michelle']) unit2 = The_Unit('FIT5145','Inroduction to Data Science','core', ['FIT9133','MAT9004','FIT9132'],'6', ['saki','michelle','Ruchi']) unit3 = The_Unit('FIT9132','Introduction to Data Base','foundation', ['none'],'3', ['saki','michelle']) term2 = The_Term('TP2','03/03','19/04', '' ) term2.addunit(unit1) term2.addunit(unit3) term2.addunit(unit2) print(term2) error error error error error error Term Code: TP2 Start Date: 03/03 End Date: 19/04 Unitlist: foundation,FIT9133,foundation,FIT9132,core,FIT5145
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48916076
favorite count: 0
tagged with: python-3.x
tagged with: word-count
tagged with: python
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48916260
downvote count: 1
type: Question
has title: Sorting the keys and values in counter
score: -1
tagged with: sorting
has body: This is the code am working on and I want the output as the count in descending and if the count is same then order by name. from collections import Counter import re from nltk.corpus import stopwords import operator text = "The quick brown fox jumped over the lazy dogs bowl. The dog was angry with the fox considering him lazy." def tokenize(text): tokens = re.findall(r"\w+|\S", text.lower()) #print(tokens) tokens1 = [] for i in tokens: x = re.findall(r"\w+|\S", i, re.ASCII) for j in x: tokens1.append(j) return tokens tok = tokenize(text) punctuations = ['(',')',';',':','[',']',',', '...', '.', '&amp;'] keywords = [word for word in tok if not word in punctuations] cnt = Counter() d= {} for word in keywords: cnt[word] += 1 print(cnt) freq = operator.itemgetter(1) for k, v in sorted(cnt.items(), reverse=True, key=freq): print("%3d %s" % (v, k)) Current output: 4 the 2 fox 2 lazy 1 quick 1 brown 1 jumped 1 over 1 dogs 1 bowl 1 dog 1 was 1 angry 1 with 1 considering 1 him Required output: 4 the 2 fox 2 lazy 1 angry 1 bowl 1 brown 1 considering 1 dog 1 dogs etc.
has comment: http://stackoverflow.com/comment/84838623
linked to: http://stackoverflow.com/q/35446015
upvote count: 0
accepted answer: http://stackoverflow.com/a/48916260
answer count: 1

http://stackoverflow.com/comment/84840672
type: AnswerComment
score: 0
comment on: http://stackoverflow.com/a/48917042
type: Comment
has text: Yes! great almost there, is there a way to add another column with score differential for each pairing? Thank you

http://stackoverflow.com/q/48904448
tagged with: python
has title: How can I know which are the duplicated rows in a Pandas Data Frame?
has answer: http://stackoverflow.com/a/48904523
type: AnsweredQuestion
downvote count: 0
type: Question
score: 1
tagged with: dataframe
has body: I am working with Pandas and the function duplicated() to detect which rows are equal: import pandas as pd d = { 1: {'name': 'n1', 1: 10, 2: 20, 3: 30}, 2: {'name': 'n2', 1: 10, 2: 20, 3: 30}, 3: {'name': 'n3', 1: 11, 2: 21, 3: 30}, 4: {'name': 'n4', 1: 11, 2: 21, 3: 30}, 5: {'name': 'n5', 1: 12, 2: 22, 3: 30}, 6: {'name': 'n6', 1: 13, 2: 22, 3: 30}, 7: {'name': 'n7', 1: 14, 3: 35}, 8: {'name': 'n8', 2: 22, 3: 35}, } pd.DataFrame.from_dict(d).transpose().set_index('name') This gives me a nice data frame like this one: 1 2 3 name n1 10 20 30 # same as n2 n2 10 20 30 # same as n1 n3 11 21 30 # same as n4 n4 11 21 30 # same as n3 n5 12 22 30 n6 13 22 30 n7 14 NaN 35 n8 NaN 22 35 Now I want to group those lines whose columns are the same. That is, I want Pandas to tell me that the rows n1 and n2 are equal, and so n3 and n4 are. Using duplicated() I get some interesting results: df[df.duplicated(keep=False)] 1 2 3 name n1 10 20 30 n2 10 20 30 n3 11 21 30 n4 11 21 30 Which is correct, since it shows those rows that have duplicated. However, my aim is to get to know which are those columns, as well as knowing which are the tuples of duplicates. That is, I would need a result on the form of [(n1, n2), (n3,n4)], a list with the duplicates one to each other. List, dict, anything works to me as well as it has this info. I have been browsing through Pandas' documentation and cannot find something like this. I tried a bit with groupby(), but nothing reasonable comes up.
tagged with: pandas
upvote count: 1
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48904523

http://stackoverflow.com/q/48954257
upvote count: 3
score: 0
downvote count: 3
accepted answer: http://stackoverflow.com/a/48955115
has title: How to use custom function in apply method with H2O frame
has body: I am trying to use the following code to apply function to each of the rows in a particular column of H2O frame, but getting error. df["decision"] = df["resp_cd"].apply(lambda x:1 if x in ["00", 01", "11] else 0, axis=1) Is there some other way to use user defined functions in H2O? How should we use apply function in H2O? I expect it to be similar to apply function in Pandas but that doesn't seem to be true.
tagged with: h2o
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/91050688
favorite count: 0
has comment: http://stackoverflow.com/comment/84916718
type: Question
has comment: http://stackoverflow.com/comment/84915664
tagged with: python
has answer: http://stackoverflow.com/a/48955115
answer count: 1
has comment: http://stackoverflow.com/comment/84916941

http://stackoverflow.com/comment/84839922
type: AnswerComment
has text: @MarcoMiglionico that was just the way the dataframe looks. it was just a statement. Not import to the solution.
type: Comment
comment on: http://stackoverflow.com/a/48916339
score: 0

http://stackoverflow.com/a/48819163
has comment: http://stackoverflow.com/comment/84642269
upvote count: 2
type: AcceptedAnswer
type: Answer
answers question: http://stackoverflow.com/q/48819022
score: 2
accepted answer of: http://stackoverflow.com/q/48819022
downvote count: 0
has body: I could see a situtation in which this happens if you name a variable the same as your function (within the "....more stuff here" section) meaning it would work the first time you call it, but would fail the second time. Take the following simplified example: def test(x,y): global test test = x / 2 # random calculation return x + y model = test(5,5) model1 = test(10,10) This would produce an error very similar to the one in the question: Traceback (most recent call last): File "SO.py", line 43, in &lt;module&gt; mode2 = test(10,10) TypeError: 'float' object is not callable The solution would be to avoid naming variables the same as your functions.

http://stackoverflow.com/q/48899523
has comment: http://stackoverflow.com/comment/84804541
favorite count: 0
has comment: http://stackoverflow.com/comment/84804336
has body: Below is the snip of code I am using. &lt;ul class="article_list"&gt; {%for article in articles %} &lt;li&gt;&lt;a href=""&gt;{{article.title}}&lt;/a&gt;&lt;/li&gt; {%endfor%} &lt;/ul&gt; This is the exception I get. Invalid filter: 'replace' Request Method: GET Request URL: http://127.0.0.1:8000/Mathematics/ Django Version: 1.10.5 Exception Type: TemplateSyntaxError Exception Value: Invalid filter: 'replace' My intention is to redirect user to http://127.0.0.1:8000/mathematics/how-to-use-replace-in-jinga when they click on the article: How to use replace in jinga Please help.
has comment: http://stackoverflow.com/comment/84804663
tagged with: django
has comment: http://stackoverflow.com/comment/84805057
tagged with: python
has comment: http://stackoverflow.com/comment/84804502
answer count: 0
downvote count: 0
has comment: http://stackoverflow.com/comment/84804959
type: UnansweredQuestion
score: 1
tagged with: jinja2
has comment: http://stackoverflow.com/comment/84804911
type: Question
linked to: http://stackoverflow.com/q/30701631
tagged with: filter
upvote count: 1
has title: Getting TemplateSyntaxError when trying to use Jinja's replace filter
has comment: http://stackoverflow.com/comment/84804377
has comment: http://stackoverflow.com/comment/84804821

http://stackoverflow.com/comment/84676585
comment on: http://stackoverflow.com/q/48835765
has text: It fails in Python3 when the `i` exceeds 67 (the upper bound of `symbols`). In the few tests I have run, that is always 68.
score: 0
type: Comment
type: QuestionComment

cors
type: Tag
tag name: cors
tags question: http://stackoverflow.com/q/48811721

http://stackoverflow.com/comment/84844968
score: 0
type: AnswerComment
has text: The merge function does not show any matches. I want to find the matches between the two dataframe.
type: Comment
comment on: http://stackoverflow.com/a/48901755

http://stackoverflow.com/q/48936363
has comment: http://stackoverflow.com/comment/84879853
score: 1
has comment: http://stackoverflow.com/comment/84999251
upvote count: 1
type: Question
has title: vscode "Go to Symbol in Workspace" not working.
accepted answer: http://stackoverflow.com/a/49138149
tagged with: visual-studio-code
possible better answer: http://stackoverflow.com/a/75219495
has answer: http://stackoverflow.com/a/75219495
has comment: http://stackoverflow.com/comment/85083419
answer count: 2
has body: I'm using VSCode 1.20.1, and have ctags installed via brew install ctags; I'm using a virtualenv and my python.pythonPath is set correctly. My "Go to Symbol in File" works fine, but I recently noticed that some of my symbols could not be resolved via "Go to Symbol in Workspace". I realized that the ./vscode/tags file was not being updated. If I delete the file and force VSCode to rebuild it, the symbols resolve properly. This problem can be duplicated when I create a new project with 2 files. The first time I use "Go to Symbol in Workspace", the ./vscode/tags file is built, but adding any additional files does not force the tags file to get updated. Has anyone else run into this problem before? Environment: VSCode: 1.20.1 Python Extension: 2018.1.0 Python Version: 3.6.3 OS : Mac OSX 10.13.3 .
downvote count: 0
has comment: http://stackoverflow.com/comment/85281319
has comment: http://stackoverflow.com/comment/84879577
favorite count: 0
has answer: http://stackoverflow.com/a/49138149
has comment: http://stackoverflow.com/comment/84879625
tagged with: python
type: AnsweredQuestion

http://stackoverflow.com/comment/84801388
score: 0
type: Comment
has text: And `issubclass(bool,int)` returns `True` in Python 3.6.
comment on: http://stackoverflow.com/a/48897921
type: AnswerComment

sage
tags question: http://stackoverflow.com/q/48884821
tag name: sage
type: Tag

http://stackoverflow.com/q/48897494
tagged with: forms
has body: I am trying to use mechanical soup to automatically fill and submit a time sheet for me. This is what the form looks like: timesheet_form This is the relevant source code for that section of the page: &lt;FORM ACTION="bwpkteci.P_UpdateTimeInOut" METHOD="post"&gt; &lt;INPUT TYPE="hidden" NAME="JobsSeqNo" VALUE="208138"&gt; &lt;INPUT TYPE="hidden" NAME="LastDate" VALUE="0"&gt; &lt;INPUT TYPE="hidden" NAME="par_restart" VALUE="Y"&gt; &lt;INPUT TYPE="hidden" NAME="par_update" VALUE="Y"&gt; &lt;INPUT TYPE="hidden" NAME="par_submit" VALUE="Y"&gt; &lt;INPUT TYPE="hidden" NAME="par_recall" VALUE="N"&gt; &lt;INPUT TYPE="hidden" NAME="EarnCode" VALUE="RSA"&gt; &lt;INPUT TYPE="hidden" NAME="DateSelected" VALUE="20-FEB-2018"&gt; &lt;TABLE CLASS="dataentrytable" SUMMARY="This user enters the time of day for the hours worked into this table in order for the system to calculate the hours."&gt; &lt;TR&gt; &lt;TD CLASS="delabel" scope="row" &gt;Date:&lt;/TD&gt; &lt;TD CLASS="dedefault"&gt;Tuesday, Feb 20,2018&lt;/TD&gt; &lt;/TR&gt; &lt;TR&gt; &lt;TD CLASS="delabel" scope="row" &gt;Earnings Code:&lt;/TD&gt; &lt;TD CLASS="dedefault"&gt;Regular Student Aide&lt;/TD&gt; &lt;/TR&gt; &lt;/TABLE&gt; &lt;TABLE CLASS="dataentrytable" SUMMARY="This is the detail table where the user enters the time of the day for the hours worked in order for the system to calculate the hours."&gt; &lt;TR&gt; &lt;TD CLASS="deheader" scope="col" &gt;&lt;LABEL for=shift_input_id&gt;&lt;SPAN class="fieldlabeltext"&gt;Shift&lt;/SPAN&gt;&lt;/LABEL&gt;&lt;/TD&gt; &lt;TD COLSPAN="2" CLASS="deheader" scope="col" &gt;&lt;LABEL for=timein_input_id&gt;&lt;SPAN class="fieldlabeltext"&gt;Time In&lt;/SPAN&gt;&lt;/LABEL&gt;&lt;/TD&gt; &lt;TD COLSPAN="2" CLASS="deheader" scope="col" &gt;&lt;LABEL for=timeout_input_id&gt;&lt;SPAN class="fieldlabeltext"&gt;Time Out&lt;/SPAN&gt;&lt;/LABEL&gt;&lt;/TD&gt; &lt;TD CLASS="deheader" scope="col" &gt;Total Hours&lt;/TD&gt; &lt;/TR&gt; &lt;INPUT TYPE="hidden" NAME="LineNumber" VALUE="1"&…
answer count: 1
downvote count: 0
tagged with: mechanize
tagged with: python
has title: Mechanical soup - form filling, working with a tricky HTML table
favorite count: 0
tagged with: mechanicalsoup
score: 2
upvote count: 2
has answer: http://stackoverflow.com/a/48898181
type: Question
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48898181

http://stackoverflow.com/comment/84791178
score: 0
type: QuestionComment
type: Comment
has text: sorry, I'm not reporting a numpy bug but rather where is my code incorrect that means it differs from the built in function, i have added my post to reflect this
comment on: http://stackoverflow.com/q/48892547

http://stackoverflow.com/comment/84669543
type: QuestionComment
comment on: http://stackoverflow.com/q/48832320
has text: Sorry, is this depending on the actual data you have? Can you rather produce a [mcve] with just enought data hardcoded or generated within the code to reproduce the issue?
score: 0
type: Comment

http://stackoverflow.com/q/48927600
favorite count: 0
upvote count: 2
tagged with: python
type: AnsweredQuestion
score: 1
tagged with: http://stackoverflow.com/tag/json
accepted answer: http://stackoverflow.com/a/48963212
has title: python: jsonify show only one output
downvote count: 1
type: Question
tagged with: flask
has body: There are 10 outputs in json but it is only the first output is shown. How to show all 10 outputs? from collections import OrderedDict import requests from lxml import html @app.route('/saptop', methods=['GET']) def saptop(): page_indo = requests.get('http://www.waterfrontsekuritas.com/marketview') indo = html.fromstring(page_indo.content) indo = indo.xpath('//table[@id="top-gainer"]//td/text()') col = ['Stockcode','Lastprice','Prevprice','pc','Change','Tfreq','Vol','Value'] c1 = [OrderedDict(zip(col,indo))] return jsonify({'Stock': c1}) The current output only shown the first one { "Stock": [ { "Stockcode": "BOSS", "Lastprice": "1,400", "Prevprice": "1,120", "pc": "25.00", "Change": "280", "Tfreq": "3,640", "Vol": "23,087,100", "Value": "29,132,765,000" } ] } when change to c1 = [OrderedDict(zip(col,t)) for t in indo] , the output as below which is wrong also, all the string is seperated by letter and number: { "Stock": [ { "Stockcode": "B", "Lastprice": "O", "Prevprice": "S", "pc": "S" }, { "Stockcode": "1", "Lastprice": ",", "Prevprice": "4", "pc": "0", "Change": "0" }, { "Stockcode": "1", "Lastprice": ",", "Prevprice": "1", "pc": "2", "Change": "0" }, { "Stockcode": "2", "Lastprice": "5", "Prevprice": ".", "pc": "0", "Change": "0" }, how to shown all 10 results correctly in Flask? It is json format
answer count: 1
has answer: http://stackoverflow.com/a/48963212

http://stackoverflow.com/comment/84762017
type: QuestionComment
has text: @cᴏʟᴅsᴘᴇᴇᴅ I've read your bio and see how you works and realized - "This person is the real !"
type: Comment
comment on: http://stackoverflow.com/q/48878848
score: 0

http://stackoverflow.com/comment/84646816
type: QuestionComment
type: Comment
score: 0
has text: @RahulKP done with the output
comment on: http://stackoverflow.com/q/48821518

http://stackoverflow.com/q/48865066
tagged with: terminal
answer count: 0
has body: Inside of Python console, whenever I press the 'delete' key, a space gets printed on the screen. The buffer however, gets updated correctly it seems. &gt;&gt;&gt; in mport numpi y Here, I type: " inbackspacemport numpy ". And the interpreter has no issue doing its job. Any idea what could cause this behavior?
upvote count: 3
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/129384092
tagged with: python
tagged with: ansi-escape
score: 3
has comment: http://stackoverflow.com/comment/84735254
type: Question
has title: Python console delete key moves the carret like space key
downvote count: 0
favorite count: 0

cross-validation
tags question: http://stackoverflow.com/q/48932266
tag name: cross-validation
tags question: http://stackoverflow.com/q/48817949
tags question: http://stackoverflow.com/q/48956602
tags question: http://stackoverflow.com/q/48857864
type: Tag

http://stackoverflow.com/a/48813117
has comment: http://stackoverflow.com/comment/122403320
type: Answer
has body: Yes Python does have the elvis operator. It is the conditional or operator: x = f() or g() f() is evaluated. If truthy, then x is assigned the value of f(), else x is assigned the value of g(). Reference: https://en.wikipedia.org/wiki/Elvis_operator#Analogous_use_of_the_short-circuiting_OR_operator
upvote count: 54
has comment: http://stackoverflow.com/comment/93937103
has comment: http://stackoverflow.com/comment/133393015
has comment: http://stackoverflow.com/comment/84629774
downvote count: 3
has comment: http://stackoverflow.com/comment/122392786
accepted answer of: http://stackoverflow.com/q/48813097
has comment: http://stackoverflow.com/comment/84629758
has comment: http://stackoverflow.com/comment/133356698
answers question: http://stackoverflow.com/q/48813097
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/122378107
score: 51

http://stackoverflow.com/q/48847212
tagged with: nest-nested-object
favorite count: 0
has comment: http://stackoverflow.com/comment/84698525
possible better answer: http://stackoverflow.com/a/48847284
has comment: http://stackoverflow.com/comment/84698498
tagged with: python
has answer: http://stackoverflow.com/a/48847284
has body: I try to create a tree of objects / not classes. I mean i do not want to create relations between the objects in prototype level, but in instance level so the relations between the objects will be solved with the code. Here i wrote something class human : def __init__ (self,Name,Surname,Gender,Age,Father,Mother) : self.Name = Name self.Surname = Surname self.Gender = Gender self.Age = Age self.Father = Father self.Mother = Mother class family : def __init__ (self,Surname,Members) : self.Surname = Surname self.Members = Members def ListMembers (self) : for member in self.Members : print (self.Surname +' family member ' +member.Name + ' '+ member.Surname + ' is ' + member.Age + " years old ") human1 = human( 'Mary','Walter','Female','42','Jason White','Sally White') human2 = human('Charles', 'Walter', 'Male', '45', 'Samuel Ribbon', 'Angie Ribbon') human3 = human('Claire', 'White', 'Female', '16', 'Charles Walter', 'Mary Walter') WalterFamily = family('Walter',(human1,human2,human3)) WalterFamily.ListMembers When i run this code WalterFamily.ListMembers prints nothing. What is exact way of nesting objects in another object ? Like i tried to do here : Nesting 3 humans inside a family and also reach to the attributes of these objects..
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48847258
tagged with: oop
downvote count: 1
accepted answer: http://stackoverflow.com/a/48847258
type: Question
score: -1
answer count: 2
upvote count: 0
has title: Declare objects as an attribute of another object in python

http://stackoverflow.com/q/48866205
has comment: http://stackoverflow.com/comment/84736318
has comment: http://stackoverflow.com/comment/116677646
type: AnsweredQuestion
linked to: http://stackoverflow.com/q/62907802
downvote count: 0
has comment: http://stackoverflow.com/comment/111246010
has comment: http://stackoverflow.com/comment/84745046
has answer: http://stackoverflow.com/a/48880939
favorite count: 0
has comment: http://stackoverflow.com/comment/84739925
has comment: http://stackoverflow.com/comment/119098674
type: Question
has body: i am trying to find if a checkbox([ ])1 is checked or not. till now i tried using the method used in pyimagesearch.i am trying to see if there are any triangles in the image. if there is at least one triangle it means that the checkbox is checked. The problem i found is that, sometimes the outer rectangle is being detected instead of triangles. how should i ignore rectangle and detect only triangles
answer count: 2
score: 5
tagged with: python
tagged with: computer-vision
has comment: http://stackoverflow.com/comment/84763120
has title: detect whether the checkbox is checked using opencv
has answer: http://stackoverflow.com/a/52654834
accepted answer: http://stackoverflow.com/a/48880939
tagged with: opencv
possible better answer: http://stackoverflow.com/a/52654834
has comment: http://stackoverflow.com/comment/84764487
upvote count: 5
has comment: http://stackoverflow.com/comment/84736064

http://stackoverflow.com/q/48923682
upvote count: 28
tagged with: python
favorite count: 0
score: 28
has body: I use scarpy to crawl data and save it to cloud hosting mLab successfully with MongoDB. My collection name is recently and data's count is 5. I want to crawl data again and update my collection recently, so i try to drop the collection and then insert. Here is my code pipelines.py: from pymongo import MongoClient from scrapy.conf import settings class MongoDBPipeline(object): def __init__(self): connection = MongoClient( settings['MONGODB_SERVER'], settings['MONGODB_PORT']) db = connection[settings['MONGODB_DB']] # here is my collection name recently setting self.collection = db[settings['MONGODB_COLLECTION']] def process_item(self, item, spider): # try to drop my collection recently self.collection.drop() self.collection.insert(dict(item)) return item But when I run my spider, I see my collection recently count is 10 (It should be 5 that is what I want) I looking for some code that how to drop collection. It's just say db.[collection Name].drop() But its no working in my case when i try self.collection.drop() before self.collection.insert(dict(item)) Anyone can give me some suggestions what is wrong with my code ? That would be appreciated. Thanks in advance.
accepted answer: http://stackoverflow.com/a/48923771
tagged with: scrapy
has title: How to drop a collection with pymongo?
type: AnsweredQuestion
tagged with: pymongo
type: Question
has answer: http://stackoverflow.com/a/48923771
answer count: 1
downvote count: 0

http://stackoverflow.com/q/48859672
has body: In my windows machine, I have created 3 virtual machine and I want to get the CPU and RAM usage of each virtual machine using Python. How can I achieve this?
score: 0
duplicate of: http://stackoverflow.com/q/276052
tagged with: python-3.x
tagged with: cpu-usage
type: UnansweredQuestion
tagged with: windows
has comment: http://stackoverflow.com/comment/94693164
tagged with: python
has comment: http://stackoverflow.com/comment/94693169
linked to: http://stackoverflow.com/q/276052
answer count: 0
tagged with: virtual-machine
type: Question
has title: How to get CPU and RAM usage from windows machine using python?

http://stackoverflow.com/q/48957205
has comment: http://stackoverflow.com/comment/84921760
has comment: http://stackoverflow.com/comment/84922165
tagged with: floating-point
upvote count: 1
has title: Convert double number to float number
has comment: http://stackoverflow.com/comment/84921604
type: Question
downvote count: 0
has body: I need to do some elaborations on MATLAB data in Python. The data is stored as an array of doubles in Matlab. When I retrieve it, despite being stated here that double data types from Matlab are converted in float data types when handled by Python, I get this error: TypeError: unorderable types: double() &lt; float() What I'm trying to do is this import matlab.engine eng=matlab.engine.connect_matlab() x = eng.workspace['MyData'] x = x[len(x)-1] if x &lt; 0.01: #do stuff How can I convert the double number stored in the array to a float so that I can use it alongside my other Python variables?
tagged with: type-conversion
accepted answer: http://stackoverflow.com/a/48957390
has comment: http://stackoverflow.com/comment/84922208
has comment: http://stackoverflow.com/comment/84922246
answer count: 1
score: 1
favorite count: 0
tagged with: double
tagged with: python
tagged with: matlab
linked to: http://stackoverflow.com/q/13291539
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48957390

http://stackoverflow.com/q/48853919
score: 3
has comment: http://stackoverflow.com/comment/84711288
has answer: http://stackoverflow.com/a/56156296
type: Question
answer count: 2
has body: I have this code for reading from a bluetooth socket: socket.settimeout(timeout) try: data = socket.recv(1024) except bluetooth.btcommon.BluetoothError as e: if e.code == 11: self.connect() obviously, I want to make a difference between a 'normal' timeout and some other problems (for example the bluetooth device switching off). The code above does not work because there is no code in the BluetoothError object. In the exception, I do see a code though: Traceback (most recent call last): File "myscript.py", line 36, in scan data = socket.recv(1024) File "&lt;string&gt;", line 5, in recv bluetooth.btcommon.BluetoothError: (11, 'Resource temporarily unavailable') How can I get that code? I tried looking for reference documentation online, but couldn't find anything. From the code, I can see it is in fact an IOError, and there doesn't seem to be a way to get the errno, is that correct?
downvote count: 0
favorite count: 0
has title: How to get the error code from BluetoothError
tagged with: python
tagged with: python-3.x
has answer: http://stackoverflow.com/a/52747551
has comment: http://stackoverflow.com/comment/84711320
upvote count: 3
tagged with: pybluez
type: UnansweredQuestion

http://stackoverflow.com/a/48850759
has body: Is there some nice way to divide sparse matrices by vector? You can use multiply() method, the result is still a sparse matrix, but in coo format: &gt;&gt;&gt; a &lt;4x3 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 11 stored elements in LInked List format&gt; &gt;&gt;&gt; d array([[1.], [2.], [3.], [4.]]) &gt;&gt;&gt; a.multiply(1/d) &lt;4x3 sparse matrix of type '&lt;class 'numpy.float64'&gt;' with 11 stored elements in COOrdinate format&gt;
type: Answer
answers question: http://stackoverflow.com/q/48850394
upvote count: 4
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48850394
score: 4
type: AcceptedAnswer

http://stackoverflow.com/comment/84653983
comment on: http://stackoverflow.com/q/48810367
score: 0
type: Comment
type: QuestionComment
has text: Sorry for last comment, I miss readed. Well, maybe it does not works for non-English content, I don't know this library to be honest

http://stackoverflow.com/comment/84675209
comment on: http://stackoverflow.com/q/48832188
has text: Nathan exacly this I want:)
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84921467
type: QuestionComment
comment on: http://stackoverflow.com/q/48938988
has text: @Aphid Thanks for your answer. Actually the issue I have is that I have no idea what is the HTTP call done. I don't think I have a way to simply POST the form.
score: 0
type: Comment

http://stackoverflow.com/q/48828173
favorite count: 0
has comment: http://stackoverflow.com/comment/84660157
tagged with: pandas
tagged with: fuzzy-comparison
has answer: http://stackoverflow.com/a/48828273
has body: Given the pandas dataframes df1 and df2: df1: d v 0 2018-02-16 13:39:55.562506 1 1 2018-02-16 10:18:56.768246 4 and df2: d vx 0 2018-02-16 13:39:56.668377 100 1 2018-02-16 14:01:05.766319 200 how can I extend df1 with the vx values from df2, such that the timestamp are almost the same i.e. the values differ in no more than 2 seconds (and NaN where they do not match)? Example: d v vx 0 2018-02-16 10:18:56.768246 4 NaN 1 2018-02-16 13:39:55.562506 1 100.0 Below is the code: import pandas as pd import datetime as dt dt1 = dt.datetime(2018, 2, 16, 13, 39, 55, 562506) dt2 = dt.datetime(2018, 2, 16, 10, 18 , 56, 768246) df1 = pd.DataFrame({'v':[1,4], 'd':[dt1, dt2]}) dt3 = dt.datetime(2018, 2, 16, 13, 39 , 56, 668377) dt4 = dt.datetime(2018, 2, 16, 14, 1 , 5, 766319) df2 = pd.DataFrame({'vx':[100,200], 'd':[dt3, dt4]})
has comment: http://stackoverflow.com/comment/84660368
upvote count: 2
tagged with: python
has comment: http://stackoverflow.com/comment/84660517
score: 2
type: AnsweredQuestion
tagged with: python-datetime
tagged with: dataframe
has comment: http://stackoverflow.com/comment/84660174
has title: How to populate a column in dataframe under given datetime value restiriction?
type: Question
downvote count: 0
answer count: 1
accepted answer: http://stackoverflow.com/a/48828273

http://stackoverflow.com/a/48825130
upvote count: 1
has body: Try this: ', '.join(items_in_cart) Your list already has items split. You want to join them together again.
score: 1
downvote count: 0
answers question: http://stackoverflow.com/q/48825114
type: Answer

http://stackoverflow.com/a/48872890
downvote count: 0
has body: To expand on btilly's answer, suppose the number of ways to reach n steps is solution(n). At the first step, you can either take a step of length 1 and have solution(n-1) ways remaining, or take a step of length 2 and have solution(n-2) ways remaining. Since both are mutually exclusive, the total number of ways remaining is solution(n-1) + solution(n-2). Instead of the 'bottom-up' dynamic programming approach he described, I decided to use a simple recursive function and use memoization using the memoize class from https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize. Here is my solution: import collections import functools class memoized(object): '''Decorator. Caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned (not reevaluated). ''' def __init__(self, func): self.func = func self.cache = {} def __call__(self, *args): if not isinstance(args, collections.Hashable): # uncacheable. a list, for instance. # better to not cache than blow up. return self.func(*args) if args in self.cache: return self.cache[args] else: value = self.func(*args) self.cache[args] = value return value def __repr__(self): '''Return the function's docstring.''' return self.func.__doc__ def __get__(self, obj, objtype): '''Support instance methods.''' return functools.partial(self.__call__, obj) class Solution(object): @memoized def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 1: return 1 elif n == 2: return 2 else: return self.climbStairs(n-1) + self.climbStairs(n-2) This solution is accepted by LeetCode:
score: 1
upvote count: 1
answers question: http://stackoverflow.com/q/48872336
type: Answer
has comment: http://stackoverflow.com/comment/84750278

oauth-2.0
tags question: http://stackoverflow.com/q/48907773
tag name: oauth-2.0
tags question: http://stackoverflow.com/q/48911594
tags question: http://stackoverflow.com/q/48961622
type: Tag
tags question: http://stackoverflow.com/q/48954479
tags question: http://stackoverflow.com/q/48868904

http://stackoverflow.com/a/60940104
type: Answer
has body: Use this: from subprocess import Popen, PIPE hdfs_path = '/path/to/the/designated/folder' process = Popen(f'hdfs dfs -ls -h {hdfs_path}', shell=True, stdout=PIPE, stderr=PIPE) std_out, std_err = process.communicate() list_of_file_names = [fn.split(' ')[-1].split('/')[-1] for fn in std_out.decode().readlines()[1:]][:-1] list_of_file_names_with_full_address = [fn.split(' ')[-1] for fn in std_out.decode().readlines()[1:]][:-1]
score: 0
answers question: http://stackoverflow.com/q/48923946

http://stackoverflow.com/q/48924970
tagged with: python
type: AnsweredQuestion
score: 1
upvote count: 1
has title: Finding unusual phrases using a "bag of usual phrases"
type: Question
has answer: http://stackoverflow.com/a/48925205
tagged with: text-mining
answer count: 2
tagged with: pandas
downvote count: 0
has answer: http://stackoverflow.com/a/48925175
has body: My goal is to input an array of phrases as in array = ["Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.","At vero eos et accusam et justo duo dolores et ea rebum.","Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet."] and to present a new phrase to it, like "Felix qui potuit rerum cognoscere causas" and I want it to tell me whether this is likely part of the group in the aforementioned array or not. I found how to detect frequencies of words, but how do I find unsimilarity? After all, my goal is to find unusual phrases, not the frequency of certain words.
tagged with: scikit-learn
accepted answer: http://stackoverflow.com/a/48925205
favorite count: 0
tagged with: python-3.x
has comment: http://stackoverflow.com/comment/84857680
possible better answer: http://stackoverflow.com/a/48925175

http://stackoverflow.com/q/48942663
has title: Lists in django: show a certain tag after 3 items
type: Question
has body: I'm using Django and I'm trying to generate Bootstrap rows and columns to display records from a database. After every three records, a new row should be added. So if I have 9 records, this is the code that should display: item item item item item item item item item Right now I have this code: {% for info in list %} {{ info.title }}"> {% endfor %} This generates: item item item item item item item item item How do I make the extra row tags appear after every 3 records?
accepted answer: http://stackoverflow.com/a/48942868
tagged with: arrays
has comment: http://stackoverflow.com/comment/84894142
score: 0
answer count: 1
tagged with: twitter-bootstrap
has answer: http://stackoverflow.com/a/48942868
tagged with: django
tagged with: python
has comment: http://stackoverflow.com/comment/84892078
type: AnsweredQuestion

http://stackoverflow.com/comment/84668061
score: 0
type: Comment
type: QuestionComment
has text: Did you check all the proposed solutions [here](https://stackoverflow.com/questions/27802860/ipython-console-in-spyder-stuck-on-connecting-to-kernel)?
comment on: http://stackoverflow.com/q/48831091

http://stackoverflow.com/comment/84873816
score: 1
has text: You could do `for k in dict1: dict1[k].update(dict2[k])` but that would change `dict1` and it assumes that all of the keys in `dict1` are in `dict2`
type: QuestionComment
comment on: http://stackoverflow.com/q/48932694
type: Comment

http://stackoverflow.com/comment/84747390
type: Comment
comment on: http://stackoverflow.com/a/48846028
has text: I believe you can specify the method as `def get_json(self,request)` to get the request object. You'd have to do it on all the views - Base, Derived 1&2 and Combined.
type: AnswerComment
score: 0

http://stackoverflow.com/q/48827752
accepted answer: http://stackoverflow.com/a/48827822
tagged with: python
has answer: http://stackoverflow.com/a/48827871
type: AnsweredQuestion
score: 3
tagged with: list
upvote count: 3
possible better answer: http://stackoverflow.com/a/48827871
type: Question
has answer: http://stackoverflow.com/a/48827822
answer count: 2
has title: Error modifying one element in a Python list
downvote count: 0
has body: I am trying to change an element in a Python list. Following the tutorial on https://www.programiz.com/python-programming/matrix, I came up with the code below. matrix = [[0]*6]*3 print(matrix) matrix[0][0] = 2 print(matrix) Upon running the code, I received the following output: [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]] [[2, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0], [2, 0, 0, 0, 0, 0]] Notice the last line of output, how the first element of every sub-list is set to 2. How do I make it so that only the first element of the first list is changed.
duplicate of: http://stackoverflow.com/q/240178
favorite count: 0
linked to: http://stackoverflow.com/q/240178
tagged with: in-place

http://stackoverflow.com/a/48936818
score: 0
type: Answer
has body: From Official documentation: XlsxWriter doesn’t calculate the result of a formula and instead stores the value 0 as the formula result. It then sets a global flag in the XLSX file to say that all formulas and functions should be recalculated when the file is opened. This is the method recommended in the Excel documentation and in general it works fine with spreadsheet applications. However, applications that don’t have a facility to calculate formulas will only display the 0 results. Examples of such applications are Excel Viewer, PDF Converters, and some mobile device applications. If required, it is also possible to specify the calculated result of the formula using the optional value parameter for write_formula() So, one needs to take some action to perform the calculation, after writing the formula, if one is pressed to see the result (e.g., closing/reopoening, but it may be too "rude"). PS: Given that John McNamara gave a different answer, I guess his would be correct. From this I would guess my answer is perhaps also correct. I wouldn't know the reason for the difference 0 (in [1]) vs. #DIV/0! (in the OP). PS2: Other interesting question: How to make unoconv auto calculate formulae before converting into pdf?
answers question: http://stackoverflow.com/q/48933774

http://stackoverflow.com/comment/84695662
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48844563
has text: Yes correct, it does start with class Kettle: but I just removed that bit, and when it runs, it runs endlessly, without a stop and it's supposed to boil the kettle and say kettle boiled but doesn't say it
score: 0

http://stackoverflow.com/q/48883776
type: Question
has body: I have a nested dict, I want get a sorted list (A-Z) of the base keys according to one of the nested values, name. my_dict: { 'RED':{'name':'Pen', 'number':5}, 'YEL':{'name':'Dog', 'number':1}, 'BLU':{'name':'Ball', 'number':3} } The correct output for the example would be: my_list = ['BLU', 'YEL', 'RED'] At the moment, I have an ugly solution, it relies on the code always being 3 chars long. my_list = [] for code in my_dict: my_list.append(my_dict[code]['name'] + code) my_list = sorted(my_list) my_list = [x[-3:] for x in my_list]
upvote count: 1
has title: Sort list according to values in nested dict
answer count: 1
favorite count: 0
accepted answer: http://stackoverflow.com/a/48883901
tagged with: python
tagged with: dictionary
type: AnsweredQuestion
tagged with: list
downvote count: 0
score: 1
has answer: http://stackoverflow.com/a/48883901

http://stackoverflow.com/q/48880847
type: Question
has body: I am new to python and getting a syntax error with my first program. Can you please help correct the syntax? GET_CONTACT = "SELECT LINKEDIN_URL, CONTACT_ID from PERSON where LINKEDIN_URL=%s" def isContactExists(linkedinUrl): cur.execute(GET_CONTACT, (linkedinUrl, )) return cur.fetchone() if existing_contact is not None: storeInTempTable(record) return Throws syntax error - storeInTempTable(record) ^ TabError: inconsistent use of tabs and spaces in indentation
score: -2
has answer: http://stackoverflow.com/a/48880929
tagged with: if-none-match
upvote count: 1
tagged with: indentation
answer count: 1
favorite count: 0
tagged with: tabs
has comment: http://stackoverflow.com/comment/84765794
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84765791
tagged with: python
has title: If is None in python
downvote count: 3
duplicate of: http://stackoverflow.com/q/45621722
has comment: http://stackoverflow.com/comment/84765958

http://stackoverflow.com/q/48908772
has comment: http://stackoverflow.com/comment/84823569
has title: Read CSV with Pandas from subdirectory on Windows and UNIX
type: Question
downvote count: 0
answer count: 1
has body: I am writing a Python script that I need to run on Windows and UNIX systems. I have two folders, let's call them 'Main' and 'Data'. 'Main' contains 'Data' and my script, and 'Data' contains my data in the form of CSV files. 'Main' --> 'Data' ---> data1.csv, data2.csv.... Currently my code below works if I keep the CSV files in 'Main'. How can I get it to work on both Windows and UNIX, keeping the CSV files in 'Data', if the path naming conventions are different? Here is the code I am running import pandas as pd myfile = "data1.csv" df = pd.read_csv(myfile,sep=',')
tagged with: pandas
tagged with: http://stackoverflow.com/tag/csv
has answer: http://stackoverflow.com/a/48908902
accepted answer: http://stackoverflow.com/a/48908902
favorite count: 0
linked to: http://stackoverflow.com/q/35384358
upvote count: 2
tagged with: python
score: 2
type: AnsweredQuestion

http://stackoverflow.com/a/48832035
answers question: http://stackoverflow.com/q/48831585
type: Answer
has body: Obviously I was on the wrong track with this. I was confusing hidden units and hidden/cell state. Only the hidden units in the LSTM are trained during the training step. Cell state and hidden state are resetet at the beginning of every sequence. So it just makes sense that it is programmed this way. Sorry for this..
downvote count: 0
score: 11
type: AcceptedAnswer
upvote count: 11
accepted answer of: http://stackoverflow.com/q/48831585

modal-dialog
tag name: modal-dialog
tags question: http://stackoverflow.com/q/48943349
type: Tag

http://stackoverflow.com/a/48871834
downvote count: 3
type: Answer
has comment: http://stackoverflow.com/comment/137471466
has comment: http://stackoverflow.com/comment/137374263
upvote count: 38
answers question: http://stackoverflow.com/q/48871289
has comment: http://stackoverflow.com/comment/137470161
has body: I would shy away from sharing environments with other users, because if they don't know what they are doing, they could add packages that could conflict with other packages and/or even delete packages that another user might need. The preferred approach is that after you have created an environment, you export it as a yml file: conda env export &gt; environment.yml Then you send the users the yml file and have them build their own environment using the yml: conda env create -f environment.yml If you really want to use a shared environment where every user can access, then you have to use the -p or --prefix option in your create: conda create -p C:/full/public/path/to/py35 python=3.5 And then instruct your users to add the public path (C:/full/public/path/to) to their conda config file. Then, they should be able to see the environment when running conda env list.
score: 35

http://stackoverflow.com/a/52936631
type: Answer
upvote count: 5
downvote count: 0
has comment: http://stackoverflow.com/comment/92805089
has comment: http://stackoverflow.com/comment/96671601
accepted answer of: http://stackoverflow.com/q/48809689
score: 5
answers question: http://stackoverflow.com/q/48809689
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/136810345
has body: Let me break this question down into two parts. First, for a python lambda you have to create a zip file. For this I recommend using the Maven Assembly Plugin. Sample pom.xml: <?xml version="1.0" encoding="UTF-8"?> 4.0.0 com.mygroup parent-pom 0.1-SNAPSHOT ../pom.xml LambdaInstall Python Lambda Installation Package pom <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> maven-assembly-plugin install-assembly package single false assembly.xml Sample assembly.xml: lambda-zip zip false src/main/python If your lambda only uses the standard python libraries, then this is all you need. The complication comes in when you need boto3 or some other library which AWS does not pre-install on its lambda nodes. For this you have to add your libraries into your zip file. I wanted a way to do it in a way that would work on any developer's PC or even on a Jenkins node so I wrote a small python app which finds the location of the library (under site-packages directory) and copies it into the application target directory. In this example I needed jwt: import jwt import distutils from distutils import dir_util # This will copy the jwt package into the target directory so it is included in the zip file jwtPath = jwt.__path__[0] distutils.dir_util.copy_tree(jwtPath, "./target/jwt") This python program is invoked by adding the Maven Exec Plugin into my pom.xml: org.codehaus.mojo exec-maven-plugin python-build prepare-package exec python src/main/python/build/copyjwt.py Now in order to copy the code into my zip file, I need only add one more file set to the assembly.xml that I showed above: target/jwt jwt
has comment: http://stackoverflow.com/comment/96625226

http://stackoverflow.com/comment/84790819
comment on: http://stackoverflow.com/q/48892614
score: 0
type: Comment
type: QuestionComment
has text: `M` is minutes, and month is `1` by default, as you haven't specified it.

http://stackoverflow.com/comment/84840253
comment on: http://stackoverflow.com/q/48916745
score: 0
type: QuestionComment
has text: the execution is terminated here `new_request.url` because `new_request` is a string. Therefore, you are not reaching the point where you yield the new request.
type: Comment

http://stackoverflow.com/comment/84845750
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48919566
score: 0
has text: Ya test data and test labels are of the same size

http://stackoverflow.com/comment/137003006
score: 0
has text: @omni It's a [design decision](https://bugs.python.org/issue22239), yes. You can't spin up an asyncio loop _inside_ another asyncio loop, but nothing stops you from running two (or more) of them in different threads. That's what third-party libs that make use of asyncio in the background do, and it works just fine.
type: Comment
comment on: http://stackoverflow.com/a/48870542
type: AnswerComment

asynchronous
tags question: http://stackoverflow.com/q/48897183
type: Tag
tag name: asynchronous
tags question: http://stackoverflow.com/q/48880508
tags question: http://stackoverflow.com/q/48865279
tags question: http://stackoverflow.com/q/48806013
tags question: http://stackoverflow.com/q/48833644
tags question: http://stackoverflow.com/q/48963039
tags question: http://stackoverflow.com/q/48870383
tags question: http://stackoverflow.com/q/48861657
tags question: http://stackoverflow.com/q/48813438

http://stackoverflow.com/comment/84976652
type: Comment
has text: Sorry for the multiple edits. Your earlier comment was pretty useful. I would be glad if you can post it again. @0xtvarun
comment on: http://stackoverflow.com/a/48942911
type: AnswerComment
score: 0

http://stackoverflow.com/comment/84625072
score: 0
type: Comment
type: QuestionComment
has text: I think I found it. Will post in an answer below.
comment on: http://stackoverflow.com/q/48810444

http://stackoverflow.com/comment/130389925
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48828423
type: Comment
has text: Yes, surely. In that case it needs to be 2-stage release anyway, so 2 separate migrations.

http://stackoverflow.com/a/48812382
has comment: http://stackoverflow.com/comment/84748750
has comment: http://stackoverflow.com/comment/84662545
has comment: http://stackoverflow.com/comment/85066322
has comment: http://stackoverflow.com/comment/85066473
has comment: http://stackoverflow.com/comment/84963211
has comment: http://stackoverflow.com/comment/84996644
type: Answer
has comment: http://stackoverflow.com/comment/84663423
has comment: http://stackoverflow.com/comment/85066468
has comment: http://stackoverflow.com/comment/85066681
answers question: http://stackoverflow.com/q/48808420
has comment: http://stackoverflow.com/comment/85066458
has comment: http://stackoverflow.com/comment/84963353
has body: Please try this code (I have changed a few things as well as adding others to hopefully do the job). Its not the most efficient or the best structured code but it does the job (for me at least): from tkinter import * import datetime root = Tk () root.bind ("&lt;Return&gt;", lambda event: answer1 ()) f = Frame(root, bg='lightgray') f.grid (sticky = "nsew") Grid.columnconfigure (root, 0, weight = 1) Grid.rowconfigure (root, 0, weight = 1) root.title("Uganda Project") #This is the first Question Bar = Scrollbar (f) T = Listbox (f, fg='white', bg='blue', yscrollcommand = Bar.set, width = 50, height = 20) Bar.config (command = T.yview) T.grid (row = 0, column = 0, columnspan = 2, sticky = "nsew") Bar.grid (row = 0, column = 2, sticky = "ns") Grid.columnconfigure (f, 0, weight = 1) Grid.rowconfigure (f, 0, weight = 1) T.insert (END, "Support:") T.insert (END, " Did you take your medicine?") T.insert (END, " 1= Yes") T.insert (END, " 2= No") #Make an entry box to answer the question in e = Entry(f, fg='black', bg='lightgray') e.focus_force () e.grid (row = 1, column = 0, sticky = "ew") def answer1(): """ What to do with the answer in the entry box""" answer1 = e.get() T.insert (END, "You: " + answer1) e.delete (0, END) if answer1=="1": T.insert (END, "Support:") T.insert (END, " Good Job! Text 0 to end conversation") send.config (command = answer2) root.bind ("&lt;Return&gt;", lambda event: answer2 ()) elif answer1=="2": T.insert (END, "Support:") T.insert (END, " 1= Did you forget?") T.insert (END, " 2= Did you run out of medicine?") T.insert (END, " 3= Did it have bad side effects?") send.config (command = answer2) root.bind ("&lt;Return&gt;", lambda event: answer2 ()) else: T.insert (END, "Support:") T.insert (END, " I did not understand your response.") return answer1 #Make a Send button to send the answer from the entry box to the definition of answer1 send = Button(f, text="Send", command=answer1) send.grid(row = 1, column = 1, columnspan = 2) #This is the second que…
score: 0
has comment: http://stackoverflow.com/comment/84696844

http://stackoverflow.com/a/48874059
has body: There is an open bug with this issue: https://github.com/opencv/opencv/issues/7343 There are also similar questions without a good solution: opencv videocapture hangs/freeze when camera disconnected instead of returning "False" Try the solutions here: DestroyWindow does not close window on Mac using Python and OpenCV Calling several times waitKey seems to work for many people. You can try without the release() as well
type: AcceptedAnswer
downvote count: 0
score: 4
type: Answer
accepted answer of: http://stackoverflow.com/q/48868348
answers question: http://stackoverflow.com/q/48868348
has comment: http://stackoverflow.com/comment/84758922
upvote count: 4

http://stackoverflow.com/comment/84764019
score: 0
has text: If no capture groups are specified, the entire matched string is returned ... (and not just the parts inside the capture groups).
type: Comment
comment on: http://stackoverflow.com/a/48879038
type: AnswerComment

http://stackoverflow.com/q/48962827
has answer: http://stackoverflow.com/a/48962995
has body: I am a beginner in Python 3 and Arduino Uno. I am trying control on board LED from Python command line. Arduino code: const int led=13; int value=0; void setup() { Serial.begin(9600); pinMode(led, OUTPUT); digitalWrite (led, LOW); Serial.println("Connection established..."); } void loop() { while (Serial.available()) { value = Serial.read(); } if (value == '1') digitalWrite (led, HIGH); else if (value == '0') digitalWrite (led, LOW); } Python Code: import serial # add Serial library for Serial communication Arduino_Serial = serial.Serial('com3',9600) #Create Serial port object called arduinoSerialData print (Arduino_Serial.readline()) #read the serial data and print it as line print ("Enter 1 to ON LED and 0 to OFF LED") while 1: #infinite loop input_data = input() #waits until user enters data print ("you entered", input_data ) #prints the data for confirmation if (input_data == '1'): #if the entered data is 1 Arduino_Serial.write('1') #send 1 to arduino print ("LED ON") if (input_data == '0'): #if the entered data is 0 Arduino_Serial.write('0') #send 0 to arduino print ("LED OFF") I am getting the below error: TypeError: unicode strings are not supported, please encode to bytes: '1'
tagged with: python-3.x
upvote count: 1
answer count: 1
has comment: http://stackoverflow.com/comment/84931575
has title: Not able write 1 or 0 to Arduino serial port
has comment: http://stackoverflow.com/comment/84937369
downvote count: 0
type: UnansweredQuestion
score: 1
favorite count: 0
type: Question
tagged with: python

http://stackoverflow.com/comment/84654102
type: Comment
comment on: http://stackoverflow.com/q/48810367
has text: @Arount, The doc lists several languages for the module to work with, Bengali is not listed there, 'If you are certain that an entire news source is in one language, go ahead and use the same api :)' - https://pypi.python.org/pypi/newspaper3k/0.1.5
score: 0
type: QuestionComment

http://stackoverflow.com/comment/84659958
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48827620
has text: @NK_, glad i could help :)
type: Comment

http://stackoverflow.com/comment/84658124
score: 0
type: QuestionComment
type: Comment
has text: `requests` follows redirects; requesting `www.cnn.com` redirects you to `edition.cnn.com`; the response you get is for the last part of the redirects. Do a get for `www` and look at the response `.history` and `.url` attributes, and you'll see you end up on `edition`.
comment on: http://stackoverflow.com/q/48825587

http://stackoverflow.com/a/48860878
has body: If I am understanding correctly here, you are looking to encode the columns and have them back in a dataframe format. One way of doing this could be : Convert your df into a matrix. df_array = df.as_matrix(columns=['A','B','C']) Perform the encoding: from sklearn import preprocessing le = preprocessing.LabelEncoder() for i in range(len(df.columns)): df_array[:,i] = le.fit_transform(df_array[:,i]) For the OneHotEncoder : enc = OneHotEncoder() enc.fit(df_array) OHE_array=enc.transform(df_array).toarray() However, this OHE can increase the dimensionality in a big way. So you may want to perform PCA or some sort of dimensionality reduction techniques to apply computationally feasible algorithms. If you want it back in the dataframe format: newdf=pd.DataFrame(df_array, columns=['A','B','C'])
has comment: http://stackoverflow.com/comment/103323017
downvote count: 0
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84725296
type: Answer
score: 3
accepted answer of: http://stackoverflow.com/q/48856595
upvote count: 3
answers question: http://stackoverflow.com/q/48856595
has comment: http://stackoverflow.com/comment/84725480

http://stackoverflow.com/q/48934915
answer count: 0
score: 1
tagged with: selenium
has comment: http://stackoverflow.com/comment/84891061
upvote count: 1
type: Question
tagged with: firefox
has body: I am developing a system that runs 100+ headless Firefox instances through python Selenium. The number of live instances are launched gradually, 10-20 at a time, until the entire system is operational. This happens without problem for the first 50-60 instances. At any time above that new instances start to fail, seemingly randomly with the following error message being returned by selenium: Message: Service geckodriver unexpectedly exited. Status code was: 0 I'm using selenium v3.8.1, Firefox 57.0.1, geckodriver 0.19.1. This is all running on a Ubuntu instance on AWS. So far I've tried searching both selenium-, and Firefox forums without much luck. The error message or the status code from selenium has lead me nowhere. Here's the full stack trace: Traceback (most recent call last): File "[..]/utils.py", line 283, in launch_browser client = webdriver.Firefox(firefox_options=options, log_path=log_path) File "[..]/.virtualenvs/user/lib/python3.6/site-packages/selenium/webdriver/firefox/webdriver.py", line 148, in __init__ self.service.start() File "[..]/.virtualenvs/user/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 98, in start self.assert_process_still_running() File "[..]/.virtualenvs/user/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 111, in assert_process_still_running % (self.path, return_code) selenium.common.exceptions.WebDriverException: Message: Service geckodriver unexpectedly exited. Status code was: 0 I have also looked into the my geckodriver logs. They are quite verbose so I'm not sure which lines are relevant to the above problem. One that strikes me as a possible trouble spot is the following: 1518573330504 addons.xpi-utils WARN addMetadata: Add-on activity-stream@mozilla.org is invalid: [Exception... "Component returned failure code: 0x80520006 (NS_ERROR_FILE_TARGET_DOES_NOT_EXIST) [nsIFile.isFile]" nsresult: "0x80520006 (NS_ERROR_FILE_TARGET_DOES_NOT_EXIST)" location: "JS frame :: resource://gre/mod…
has title: Geckodriver unexpectedly exits when running multiple Firefox instances through Selenium
has comment: http://stackoverflow.com/comment/84918690
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: geckodriver
tagged with: python
tagged with: selenium-webdriver

http://stackoverflow.com/comment/84882983
comment on: http://stackoverflow.com/q/48938004
type: QuestionComment
type: Comment
has text: You didn't pass your dict to template
score: 1

http://stackoverflow.com/comment/84652744
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48824301
has text: @Guy - The input file only contain one word on each line.
score: 0

tabs
type: Tag
tags question: http://stackoverflow.com/q/48873097
tags question: http://stackoverflow.com/q/48880847
tags question: http://stackoverflow.com/q/48901854
tag name: tabs

linestyle
tags question: http://stackoverflow.com/q/48949192
tag name: linestyle
type: Tag

http://stackoverflow.com/q/48807953
linked to: http://stackoverflow.com/q/8056130
score: 0
has comment: http://stackoverflow.com/comment/84618834
has answer: http://stackoverflow.com/a/48808502
has body: Let's say I have: a = 1 b = 2 C = 'r' my_list = [a,b,c] Now let's say that a, b and c are unknown and I don't know their names. If I do: for x in my_list: del x it doesn't work. a, b, c have not been deleted. Can someone explain me why?
has comment: http://stackoverflow.com/comment/84618744
linked to: http://stackoverflow.com/q/986006
has comment: http://stackoverflow.com/comment/84619523
tagged with: python
has comment: http://stackoverflow.com/comment/84619819
has answer: http://stackoverflow.com/a/48808229
type: UnansweredQuestion
has title: delete element by deleting it from list
tagged with: list
type: Question
answer count: 2
tagged with: variables
linked to: http://stackoverflow.com/q/11520492
has comment: http://stackoverflow.com/comment/84618742

http://stackoverflow.com/a/48873822
has comment: http://stackoverflow.com/comment/84751795
downvote count: 0
has comment: http://stackoverflow.com/comment/84751834
has comment: http://stackoverflow.com/comment/84751858
has body: client.move_member takes two arguments: a Member and a Channel. We can use discord.utils.find to get the channel from the servers list of channels. channel = discord.utils.find(lambda x: x.name == 'afk', message.server.channels) await client.move_member(message.author, channel) Some further notes: The above is actually unnecessary for the afk channel, as servers have a Server.afk_channel attribute. You should also be using the discord.ext.commands extension to implement your commands, to keep your on_message from getting cluttered.
upvote count: 2
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48873638
type: Answer
answers question: http://stackoverflow.com/q/48873638
score: 2

arima
tag name: arima
type: Tag
tags question: http://stackoverflow.com/q/48863159
tags question: http://stackoverflow.com/q/48859634

http://stackoverflow.com/comment/84827625
has text: Possible duplicate of [Seaborn Bar Plot Ordering](https://stackoverflow.com/questions/43770507/seaborn-bar-plot-ordering)
score: 1
comment on: http://stackoverflow.com/q/48910557
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84844833
comment on: http://stackoverflow.com/a/48918892
score: 0
type: AnswerComment
type: Comment
has text: Almost. You forgot the first example. BTW, you can just use `print(..., file=f)` for stuff like this. It's a much cleaner interface in my opinion (and just wraps `f.write` under the hood).

http://stackoverflow.com/a/48872519
downvote count: 0
score: 1
has body: Your confusion is caused by the fact that tf.contrib.keras API is not exactly tensorflow and isn't meant to be used like core tensorflow1. If you look at the source code, the classes from tf.contrib.keras.optimizers are almost identical to ones from keras.optimizers. E.g., the first Optimizer and the second Optimizer, the first SGD and the second SGD, and so on. Keras is being gradually incorporated in tensorflow, but right now it's more like another project bundled together with tensorflow and can't be easily used with the arbitrary tensorflow graph. Instead, keras optimizers should be used with keras layers. So you can either stick to the all-tensorflow API and use tf.train.AdamOptimizer (like you do right now) or to all-keras API and use Adam (see Marcin's answer). I don't see any value in mixing the two. 1 At least in TF 1.x. Keras might be integrated more with TF in the future versions.
upvote count: 1
answers question: http://stackoverflow.com/q/48835999
type: Answer

http://stackoverflow.com/comment/84703783
comment on: http://stackoverflow.com/a/48828896
has text: @user1532587: Are you willing and able to use Numba? We could certainly make a faster solution using that...but only if you are able to install it.
type: Comment
score: 0
type: AnswerComment

http://stackoverflow.com/comment/116828434
score: 0
type: AnswerComment
has text: @PeDro: in that case you would need `struct.unpack_from(">HII", b)` (note that the 2 rightmost bytes **will be ignored**).
type: Comment
comment on: http://stackoverflow.com/a/48823932

http://stackoverflow.com/comment/84643893
type: AnswerComment
has text: Haha I just found that too! Thank you!
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48820127

http://stackoverflow.com/comment/84690493
comment on: http://stackoverflow.com/q/48841371
score: 0
has text: But its definitely a german word an everytime i expect an "ä" it comes exactly with these bytes.
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84748799
comment on: http://stackoverflow.com/q/48872336
score: 0
type: Comment
type: QuestionComment
has text: I'm trying not to go to the solution straight away, but to first understand what's wrong with this approach. I think I see the way forward, though: to solve the problem using dynamic programming.

http://stackoverflow.com/comment/84801179
score: 2
has text: What is three-sisters.html? Add the html in the code. Without the text, how do you expect us to help you? Also add your expected output.
comment on: http://stackoverflow.com/q/48897760
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84625243
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48810701
has text: @Alex I just had a brief look at pandas documentation, and it appears to me that a better solution is to make a dictionary of lists, convert it into a DataFrame, and export that to CSV. Thank you, I haven't considered looking outside the default Python box!
score: 0

checkbox
tag name: checkbox
tags question: http://stackoverflow.com/q/48889170
tags question: http://stackoverflow.com/q/48814291
type: Tag

http://stackoverflow.com/q/48810273
answer count: 3
tagged with: python
has answer: http://stackoverflow.com/a/48810659
favorite count: 0
has title: python - sum the numbers if the previous variable was the same as exiting elements in alist
type: UnansweredQuestion
score: 0
upvote count: 1
has answer: http://stackoverflow.com/a/48810555
downvote count: 1
type: Question
has answer: http://stackoverflow.com/a/48810581
has body: i have alist within alist that looks like that: sub_count = [[['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium'], 2], [['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Standard'], 2], [['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium'], 1]] what i need to get anew dictionary with farm as akey ,and lists of subscription name i.e Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium/standard ,and the summary of subscriptions per subscriptions example: dic = {Farm:[Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium,3][Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Standard,2]} Note: i have tried to create a new list and try the below method to get my result as alist but not getting the correct result and i actually prefer adict: ['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium', 2, 'Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Standard', 2, 'Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium', 1] list2 = [] for i in list1: if i not in list2: if not isinstance(i, (int, long)): list2.append(i) if isinstance(i, (int, long)): count = 0 count = count + i: list2.append(count) getting: ['Farm', u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Premium', 2, u'Red Hat Enterprise Linux for Virtual Datacenters with Smart Management, Standard', 1] Please provide a way to get the dic as the example above
has comment: http://stackoverflow.com/comment/84623910

http://stackoverflow.com/comment/87125559
type: Comment
has text: I know this is a good long while after the fact, but I got my code working with a URL update, then a month or so later, it stopped working again without any changes being made. I've since started using the Morningstar API instead, and haven't had any issues with it. Anyways, thanks for taking the time to reply.
score: 0
type: AnswerComment
comment on: http://stackoverflow.com/a/48898614

http://stackoverflow.com/a/58745572
answers question: http://stackoverflow.com/q/48880228
downvote count: 1
type: Answer
upvote count: 0
has body: import pdftext with open("lorem_ipsum.pdf", "rb") as f: pdf = pdftotext.PDF(f) # Iterate over all the pages for page in pdf: print(page) # Just read the second page print(pdf[2])
score: -1

http://stackoverflow.com/a/48842406
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48842143
upvote count: 1
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48842143
has body: Saving the current plot using matplotlib.pyplot, (which could be imported as plt) is done as plt.savefig("filename.png") If you want to save the specific figure which is created by a function returning a numpy array of axes, axes = func(...) axes.flatten()[0].figure.savefig("filename.png")
type: Answer

http://stackoverflow.com/q/48834036
has title: Getting a pandas DataFrame from a subprocess
tagged with: pickle
has comment: http://stackoverflow.com/comment/84672549
has body: I have a python 3 script that calls a sub process. Below is line of code I use in my script: Note: Path is my python exe file (the sub process is ran in 2.7 where as the main script is in python 3. The rest are some parameters passed to the sub process. Proc = subprocess.check_output([path,'ListProcessing_V8.py',Table_Names,features,output_file], shell=True) In the script 'LP.py' is a main function. That main function returns a pandas data frame (lets call is Data). My question is if there is a way to get retrieve Data from 'LP.py' once the sub process is completed. I've looked into using subprocess.check_output() but the only thing returned were some of the print statements used in 'LP.py', not an actual data frame. Pickle was another idea but I was getting byte errors. I know I can just output the data frame to some file then read it from the parent file, however I would like to avoid this if at all possible. Thanks for the help!
score: 3
has comment: http://stackoverflow.com/comment/84672693
has comment: http://stackoverflow.com/comment/84674318
upvote count: 3
has comment: http://stackoverflow.com/comment/84672629
type: Question
has comment: http://stackoverflow.com/comment/84673028
has comment: http://stackoverflow.com/comment/84672783
downvote count: 0
favorite count: 0
tagged with: python
answer count: 0
tagged with: subprocess
has comment: http://stackoverflow.com/comment/84672858
type: UnansweredQuestion

http://stackoverflow.com/comment/84624201
type: Comment
type: AnswerComment
has text: Awesome! Thanks for the solution and reply :)
score: 0
comment on: http://stackoverflow.com/a/48810027

http://stackoverflow.com/a/48839471
upvote count: 6
accepted answer of: http://stackoverflow.com/q/48827687
has body: Sequential model is not very flexible. You should look into the functional API. I would try something like this: from keras.layers import (Conv1D, MaxPool1D, Dropout, Flatten, Dense, Input, concatenate) from keras.models import Model, Sequential timesteps = 50 n = 5 def network(): sequence = Input(shape=(timesteps, 1), name='Sequence') features = Input(shape=(n,), name='Features') conv = Sequential() conv.add(Conv1D(10, 5, activation='relu', input_shape=(timesteps, 1))) conv.add(Conv1D(10, 5, activation='relu')) conv.add(MaxPool1D(2)) conv.add(Dropout(0.5, seed=789)) conv.add(Conv1D(5, 6, activation='relu')) conv.add(Conv1D(5, 6, activation='relu')) conv.add(MaxPool1D(2)) conv.add(Dropout(0.5, seed=789)) conv.add(Flatten()) part1 = conv(sequence) merged = concatenate([part1, features]) final = Dense(512, activation='relu')(merged) final = Dropout(0.5, seed=789)(final) final = Dense(2, activation='softmax')(final) model = Model(inputs=[sequence, features], outputs=[final]) model.compile(loss='logcosh', optimizer='adam', metrics=['accuracy']) return model m = network()
type: AcceptedAnswer
downvote count: 0
score: 6
answers question: http://stackoverflow.com/q/48827687
type: Answer

http://stackoverflow.com/comment/84719690
comment on: http://stackoverflow.com/q/48858104
type: Comment
type: QuestionComment
has text: Split that long return expression into multiple statements. Print the result of each line after it executes. Then share the output here if you still need help.
score: 0

http://stackoverflow.com/comment/84868267
type: Comment
has text: Thanks, that clears things up a lot. When you say use a buffered writer, I believe the standard Python `with open("path", "wb")` approach provides a buffered writer with no extra cost. However I can't find any way to check if the class `TFRecordWriter` is also buffering the stream before writing to disk...
comment on: http://stackoverflow.com/a/48913749
type: AnswerComment
score: 0

http://stackoverflow.com/q/48806528
favorite count: 0
tagged with: pandas
tagged with: seaborn
has comment: http://stackoverflow.com/comment/84619762
has answer: http://stackoverflow.com/a/48808481
has title: Python Seaborn - FacetGrid dynamic mean axhline
tagged with: python
upvote count: 2
accepted answer: http://stackoverflow.com/a/48808481
type: AnsweredQuestion
tagged with: matplotlib
has body: Each Facet has its own mean. How can I plot the according mymean values for each different Facet ? mymean is a list of 3 average values. from random import randint import pandas as pd names = ["Jack", "Ernest", "Wilde"] a = pd.DataFrame({"Value": [randint(0, 100) for i in range(len(names)*5)], "Year": [y for i in range(len(names)) for y in range(2014,2019)], "Name": [name for name in names for i in range(5)]}) mymean = a.groupby(["Name"])["Value"].mean() sns.set(style="white", context="talk") grid = sns.FacetGrid(a, col="Name", hue="Name", col_wrap=3, size=3, sharey=False) grid.map(plt.axhline, y=60, ls=":", c=".5") grid.map(plt.plot, "Year", "Value", marker="o", ms=5) grid.fig.tight_layout(w_pad=1)
type: Question
score: 2
answer count: 1
downvote count: 0

http://stackoverflow.com/comment/84684875
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48840158
has text: How do i roll them back to a list?

http://stackoverflow.com/q/48917810
tagged with: gunicorn
has body: I'm trying to run my Django app with the Gunicorn web server. But I'm having difficulty doing so. My directory structure looks like this: $ pwd /Users/my_user/my_django_project $ ls -R ./MySite: __init__.py migration_settings.py urls.py local_settings.py settings.py wsgi.py ./app1: &lt;blah&gt; &lt;blah&gt; &lt;blah&gt; ./app2: &lt;blah&gt; &lt;blah&gt; &lt;blah&gt; ./app3: &lt;blah&gt; &lt;blah&gt; &lt;blah&gt; This is how I run the Django test server, it works: $ ./manage.py runserver --settings=MySite.local_settings 0.0.0.0:8000 How do I run the same server with gunicorn instead of ./manage.py? Everything I have seen indicates I should do the following. But as you can see, it gives me an error: $ pwd /Users/my_user/my_django_project $ gunicorn -v gunicorn (version 19.7.1) $ DJANGO_SETTINGS_MODULE=MySite.local_settings gunicorn MySite.wsgi:application --log-file=- [2018-02-21 19:26:01 -0500] [9038] [INFO] Starting gunicorn 19.7.1 [2018-02-21 19:26:01 -0500] [9038] [INFO] Listening at: http://127.0.0.1:8000 (9038) [2018-02-21 19:26:01 -0500] [9038] [INFO] Using worker: sync [2018-02-21 19:26:01 -0500] [9041] [INFO] Booting worker with pid: 9041 [2018-02-21 19:26:01 -0500] [9041] [ERROR] Exception in worker process Traceback (most recent call last): File "/Library/Python/2.7/site-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/Library/Python/2.7/site-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/Library/Python/2.7/site-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/Library/Python/2.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/Library/Python/2.7/site-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/Library/Python/2.7/site-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/Library/Python/2.7/site-packages/gunico…
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84846612
tagged with: python
answer count: 0
tagged with: django
type: Question
has comment: http://stackoverflow.com/comment/84843467
score: 0
has comment: http://stackoverflow.com/comment/84843634
tagged with: wsgi
has title: How can I run this Django Server with gunicorn?

http://stackoverflow.com/a/71989492
has body: There are ways of digging into these _Call objects, but only to some extent. What if, for example, a parameter in a called mocked method is itself a Mock? Consider this: def test_create_and_show_main_window_should_make_main_window_vis(qtbot): with mock.patch('PyQt5.QtWidgets.QApplication'): with mock.patch.object(MainWindow.the(), 'show') as mock_show: with mock.patch('sys.exit') as mock_exit: main_window_class.create_and_show_main_window() mock_show.assert_called_once() mock_exit.assert_called_once() call = mock_exit.call_args_list[0] call_arg = call.args[0] assert call_arg._extract_mock_name() == 'QApplication().exec()' In the above I want to test the following lines in my app code: app_instance = QtWidgets.QApplication(sys.argv) MainWindow.the().show() sys.exit(app_instance.exec()) ... it turns out that, in the above, call_arg is of type unittest.mock.MagicMock and that repr(call_arg) is &quot;&lt;MagicMock name='QApplication().exec()' id='139817836711216'&gt;&quot;. A MagicMock has a name attribute, but if you try to use it directly it will create a new MagicMock automatically rather than returning it: MagicMocks are slippery, powerful objects. Fortunately, as illustrated above, the method _extract_mock_name has been provided to obtain it.
score: 0
answers question: http://stackoverflow.com/q/48936730
type: Answer

http://stackoverflow.com/comment/84837100
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48914936
score: 0
has text: Okay, I will add my code and output , thanks!

http://stackoverflow.com/comment/84708244
comment on: http://stackoverflow.com/q/48851971
score: 0
type: Comment
type: QuestionComment
has text: @lu.koerfer how can I check that? If you teach me how to do it, will never forget later

http://stackoverflow.com/a/48916534
type: Answer
has body: This happens because while NumPy indexes arrays based on a row-first principle (i.e. your shape is (rows, columns)), OpenCV indexes based on (x, y) co-ordinates, meaning the axes are flipped. This can be annoying to deal with, but this should fix your issue: Try changing: cv2.line(image_1, (0,0), image_1.shape, 255, 1, 16) to cv2.line(image_1, (0,0), image_1.shape[::-1], 255, 1, 16) The [::-1] flips the tuple to become (248, 203), and your line should look fine now.
answers question: http://stackoverflow.com/q/48916296
score: 1
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48916296
type: AcceptedAnswer
downvote count: 0

http://stackoverflow.com/q/48958174
tagged with: soundcloud
tagged with: api
score: 0
has body: I'm helping out someone who needs to pull metadata from their soundcloud account (track title, description, date published, size, duration, media URL, etc). Unfortunately, they have over 1500+ tracks, so it is not sufficient to use the rss feed, which is limited to 200 or 250 tracks. soundcloud no longer gives out client ID for their API. I found a client ID used in a github project. Then using soundcloud python wrapper found here https://github.com/soundcloud/soundcloud-python, I tried to get track meta data with this import soundcloud client = soundcloud.Client(client_id=CLIENT_ID_REDACTED) tracks = client.get('/users/9999999/tracks/', limit=5000) print(len(tracks)) Alas, it will only return max 200 tracks, so that doesn't help. Does this 200 track limit exist if I have an actual client ID registered to the account? Is there any hope of getting this data? thanks in advance
has title: Pull metadata from a soundcloud account with over 1500 tracks
has answer: http://stackoverflow.com/a/48968389
has answer: http://stackoverflow.com/a/48966067
type: UnansweredQuestion
tagged with: python
has comment: http://stackoverflow.com/comment/84923329
type: Question
has comment: http://stackoverflow.com/comment/84938806
answer count: 2

http://stackoverflow.com/a/48824525
accepted answer of: http://stackoverflow.com/q/48824396
type: Answer
has comment: http://stackoverflow.com/comment/84661462
upvote count: 2
has comment: http://stackoverflow.com/comment/84652680
downvote count: 1
has comment: http://stackoverflow.com/comment/84668748
score: 1
answers question: http://stackoverflow.com/q/48824396
has comment: http://stackoverflow.com/comment/84652637
type: AcceptedAnswer
has body: The problem is that you are trying to reassign mages. That is wrong in python since variables are not containers but you must think of them as labels: magicians=['feka','kuka','szuka'] #puts 'the Great' after every list element name def make_great(mages): greatlist=[] while mages: uj=mages.pop() greatlist.append(uj + ", the Great") return greatlist # return the resulting list magicians = make_great(magicians) #reassign magicians labelling to the new list from function Notice the scope, greatlist live inside the function, so once the function finished everything not global on it nor returned will be disscarded.

http://stackoverflow.com/a/48938674
score: 0
has body: Would you consider something like this def a(): return 'abc' def b(): return 'help' def c(): return 'please' def save_output(file_name, *args): with open(file_name, 'w') as f: for x in args: f.write('Function {0}() returned: {1}{2}'.format(x.__name__,x(),'\n')) To test: save_output('example.txt',a,b,c) Output: Function a() returned: abc Function b() returned: help Function c() returned: please
type: Answer
answers question: http://stackoverflow.com/q/48938522

http://stackoverflow.com/a/48888264
upvote count: 3
score: 3
answers question: http://stackoverflow.com/q/48887912
has comment: http://stackoverflow.com/comment/84783127
downvote count: 0
has body: Brute force is really the main way. You might be able to get squeeze some performance out using a KDTree since your data is low dimensional. scipy.spatial.KDTree kdtree = scipy.spatial.KDTree(s2) neighbours = kdtree.query(s1)
type: Answer

http://stackoverflow.com/comment/85169105
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/49046114
has text: I am glad to hear it helped, Best luck :)

http://stackoverflow.com/comment/84708995
type: Comment
score: 0
has text: thanks for your reply.For the point 1 you mentioned , I realized it later and with the modification the result is the same. About second point VGG16() also provides the parameters you mentioned (weights and pooling) and their default values are just fine , so no problems here.And as you mentioned VGG16 downloads loads weights from github initially (From (DIRECT LINK TO FILE!!) https://github.com/fchollet/deep-learning-models/releases/download/v0.1/vgg16_weights_tf_dim_ordering_tf_kernels.h5)
type: AnswerComment
comment on: http://stackoverflow.com/a/48852735

text-extraction
tags question: http://stackoverflow.com/q/48848408
tags question: http://stackoverflow.com/q/48913352
type: Tag
tag name: text-extraction
tags question: http://stackoverflow.com/q/48954454

http://stackoverflow.com/comment/84670116
comment on: http://stackoverflow.com/q/48832294
type: Comment
type: QuestionComment
has text: are you saving the item instance after updating price ? `item.save()` ?
score: 0

http://stackoverflow.com/a/67144959
type: Answer
has body: i used the concept of reverse connection, like(reverse shells), i shamelessly copied the above answer(answer 1),and converted it. Attacker import socket from zlib import decompress import pygame WIDTH = 1900 HEIGHT = 1000 def recvall(conn, length): """ Retreive all pixels. """ buf = b'' while len(buf) < length: data = conn.recv(length - len(buf)) if not data: return data buf += data return buf def main(host='192.168.1.208', port=6969): ''' machine lhost''' sock = socket.socket() sock.bind((host, port)) print("Listening ....") sock.listen(5) conn, addr = sock.accept() print("Accepted ....", addr) pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) clock = pygame.time.Clock() watching = True try: while watching: for event in pygame.event.get(): if event.type == pygame.QUIT: watching = False break # Retreive the size of the pixels length, the pixels length and pixels size_len = int.from_bytes(conn.recv(1), byteorder='big') size = int.from_bytes(conn.recv(size_len), byteorder='big') pixels = decompress(recvall(conn, size)) # Create the Surface from raw pixels img = pygame.image.fromstring(pixels, (WIDTH, HEIGHT), 'RGB') # Display the picture screen.blit(img, (0, 0)) pygame.display.flip() clock.tick(60) finally: print("PIXELS: ", pixels) sock.close() if __name__ == "__main__": main() client code import socket from threading import Thread from zlib import compress from mss import mss import pygame WIDTH = 1900 HEIGHT = 1000 def retreive_screenshot(conn): with mss() as sct: # The region to capture rect = {'top': 0, 'left': 0, 'width': WIDTH, 'height': HEIGHT} while True: # Capture the screen img = sct.grab(rect) # Tweak the compression level here (0-9) pixels = compress(img.rgb, 6) # Send the size of the pixels length size = len(pixels) size_len = (size.bit_length() + 7) // 8 conn.send(bytes([size_len])) # Send the actual pixels length size_bytes = size.to_bytes(size_len, 'big') conn.send(size_bytes) # Send pixels conn.sendall(pixels) def main(host='192.168.1.2…
answers question: http://stackoverflow.com/q/48950962
score: 0

http://stackoverflow.com/comment/84872068
type: Comment
type: QuestionComment
has text: Please, add data for `data` so your example can be reproducible.
comment on: http://stackoverflow.com/q/48932345
score: 0

http://stackoverflow.com/a/48812113
has body: $req = $http({method: 'get',url: "https://**.pythonanywhere.com/123",params: {mytext: "test"}); now the mytext became string, you were not passing it as a string.
type: Answer
has comment: http://stackoverflow.com/comment/84627918
answers question: http://stackoverflow.com/q/48811905
score: 0

http://stackoverflow.com/q/48871043
type: Question
has comment: http://stackoverflow.com/comment/84746492
tagged with: python
has comment: http://stackoverflow.com/comment/84747637
has answer: http://stackoverflow.com/a/48872246
upvote count: 1
has title: How to update row by row of dataframe using python pandas
answer count: 1
has comment: http://stackoverflow.com/comment/84746271
tagged with: dataframe
accepted answer: http://stackoverflow.com/a/48872246
has comment: http://stackoverflow.com/comment/84746272
tagged with: pandas
type: AnsweredQuestion
downvote count: 0
score: 1
favorite count: 0
has comment: http://stackoverflow.com/comment/84747239
has body: I don't know whether it can be achieved or not using python pandas. Here is the scenario I'm trying to do I created a databases connection to MSSQL using python (pyodbc, sqlalchemy) I read one table and saved it as dataframe like this data = pd.read_sql_table('ENCOUNTERP1', conn) and the dataframe looks like this ENCOUNTERID DIAGCODE DIAGSEQNO POA DIAGVERFLAG 0 78841 3GRNFC 3 P 1 89960 6 2 86479 N18BZON 9 K 3 69135 MPPY3 9 9 0 4 32422 DS6SBT 2 P 5 69135 4 D H 6 92019 PP0 1 7 42105 2 L 8 99256 U 1 J 9 33940 II9ZODF 3 2 10 33940 OH 1 11 65108 CI6COE 8 U 12 77871 Y3ZHN1 7 S 13 65108 73BJBZV 8 7 14 99256 7 1 T Now I have one more dataframe (dp = pd.read_sql_table('tblDiagnosis', conn))which has DIAGCODE column in it and they all are unique I want to get those DIAGCODE from dataframe dp and update it to dataframe data['DIAGCODE'] I tried to do like this iterate over each row and update another dataframe row by row but here in this code the second for loop will start from 0 index every time so, finally the entire row is filled with one value. for index, row in dp.iterrows(): for i, r in data.iterrows(): r['DIAGCODE'] = row['Code'] First of all the two dataframe's are not equal in size this is dataframe for data Code Description Category IcdSet 0 001 001 - CHOLERA CHOLERA 9 1 0010 0010 - CHOLERA D/T V. CHOLERAE CHOLERA 9 2 0011 0011 - CHOLERA D/T V. EL TOR CHOLERA 9 3 0019 0019 - CHOLERA NOS CHOLERA 10 4 002 002 - TYPHOID/PARATYPHOID FEV TYPHOID AND PARATYPHOID FEVERS 9 5 0020 0020 - TYPHOID FEVER TYPHOID AND PARATYPHOID FEVERS 9 and the output should be something like this ENCOUNTERID DIAGCODE DIAGSEQNO POA DIAGVERFLAG 0 78841 001 3 P 1 89960 0010 6 2 86479 0011 9 K 3 69135 0019 9 9 0 4 32422 002 2 P 5 69135 0020 4 D H I would like to add one condition from dataframe dp like this for index, row in dp.iterrows(): for i, r in data.iterrows(): if row['Code'] == 10: r['DIAGCODE'] = row['Code']

http://stackoverflow.com/comment/84925259
comment on: http://stackoverflow.com/q/48919331
has text: nltk and textblob both have feature of sentece tokenization. I think in near future, they will have upgrade some function call readsentence() to feed file sentence by sentence. I think it would be very useful.
type: Comment
type: QuestionComment
score: 0

alexa-skills-kit
tag name: alexa-skills-kit
type: Tag
tags question: http://stackoverflow.com/q/48865970

http://stackoverflow.com/comment/84881408
score: 1
type: Comment
type: QuestionComment
has text: My first two hits for Google `read .wav with python` are https://docs.python.org/2/library/wave.html and https://stackoverflow.com/q/2060628/7010554. Maybe this could be a starting point?
comment on: http://stackoverflow.com/q/48937077

http://stackoverflow.com/q/48947116
tagged with: python
has title: Show Message Box After Button Click
tagged with: pyqt5
type: Question
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48948513
answer count: 1
has body: I want to show a QMessage.information box after a button has been clicked. I have tried to implement it but It does not seem to be working. Here is a copy of my code and the stack trace. What am I doing wrong, what is the correct way to do this in order to display a message box after the button has been clicked. # Main Class that holds User Interface Objects class Ui_MainWindow(object): # Function for Opening Report Viewer Window From Main Window by clicking View Reports button def openReportViewer(self): self.window = QtWidgets.QMainWindow() self.ui = Ui_reportViewerWindow() self.ui.setupUi(self.window) self.window.show() def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.setFixedSize(834, 428) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth()) MainWindow.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(12) font.setBold(True) font.setWeight(75) MainWindow.setFont(font) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") # Sim Card Button self.simCardButton = QtWidgets.QPushButton(self.centralwidget) self.simCardButton.setGeometry(QtCore.QRect(30, 200, 211, 30)) self.simCardButton.setToolTip("Select to parse sim card data") font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(14) self.simCardButton.setFont(font) self.simCardButton.setObjectName("simCardButton") # Call Logs Button self.callLogButton = QtWidgets.QPushButton(self.centralwidget) self.callLogButton.setGeometry(QtCore.QRect(30, 300, 211, 30)) self.callLogButton.setToolTip("Select to parse call log data") font = QtGui.QFont() font.setFamily("Arial") font.setPointSize(14) self.callLogButton.setFont(font) self.callLogButton.setObjectName("callLogButton") # SMS Button self.smsButton = Qt…
accepted answer: http://stackoverflow.com/a/48948513
score: 0

http://stackoverflow.com/comment/84772530
comment on: http://stackoverflow.com/a/48881761
score: 0
type: AnswerComment
has text: After changing that too `arr[fi+i], arr[si+i] = arr[si+i], arr[fi+i]` I'm still getting the same error on that particular line of code
type: Comment

http://stackoverflow.com/a/48915453
type: AcceptedAnswer
has body: There's nothing built into Bokeh to accomplish this kind of offsetting of categorical ticks, but you can write a custom extension to do it: CS_CODE = """ import {CategoricalTicker} from "models/tickers/categorical_ticker" export class MyTicker extends CategoricalTicker type: "MyTicker" get_ticks: (start, end, range, cross_loc) -&gt; ticks = super(start, end, range, cross_loc) # shift the default tick locations by half a categorical bin width ticks.major = ([x, 0.5] for x in ticks.major) return ticks """ class MyTicker(CategoricalTicker): __implementation__ = CS_CODE p.xgrid.ticker = MyTicker() p.ygrid.ticker = MyTicker() Note that Bokeh assumes CoffeeScript by default when the code is just a string, but it's possible to use pure JS or TypeScript as well. Adding this to your code yields: Please note the comment about output_notebook you must call it (possibly again, if you have called it previously) after the custom model is defined, due to #6107
type: Answer
upvote count: 5
has comment: http://stackoverflow.com/comment/84837923
downvote count: 0
answers question: http://stackoverflow.com/q/48912710
score: 5
accepted answer of: http://stackoverflow.com/q/48912710

django-filebrowser
type: Tag
tag name: django-filebrowser
tags question: http://stackoverflow.com/q/48909885

http://stackoverflow.com/q/48854567
upvote count: 5
has comment: http://stackoverflow.com/comment/84713786
score: 4
has answer: http://stackoverflow.com/a/48854730
has comment: http://stackoverflow.com/comment/84712652
tagged with: progress
favorite count: 0
linked to: http://stackoverflow.com/q/4995733
has body: This is the code for the progress spinner: import sys import time def spinning_cursor(): while True: for cursor in '|/-\\': yield cursor spinner = spinning_cursor() for _ in range(50): sys.stdout.write(spinner.next()) sys.stdout.flush() time.sleep(10) sys.stdout.write('\b') Output python2.7 test.py | It is spinning very slowly since the loop sleeps for 10 seconds... How do I keep rotating the spinner while the process is sleeping?
tagged with: python
answer count: 4
has comment: http://stackoverflow.com/comment/84713009
has answer: http://stackoverflow.com/a/78432641
has comment: http://stackoverflow.com/comment/84712755
has comment: http://stackoverflow.com/comment/84712934
type: UnansweredQuestion
has answer: http://stackoverflow.com/a/48855384
has title: How do I make an asynchronous progress spinner in Python?
downvote count: 1
has answer: http://stackoverflow.com/a/48855345
type: Question

http://stackoverflow.com/comment/84676988
type: Comment
score: 0
comment on: http://stackoverflow.com/a/48835901
type: AnswerComment
has text: Since JSON is the *serialized representation*, it's not strictly a "requirement" that implementations map to Unicode for in-program values.. but such is an edge-case and it would be even more odd to have Unicode and "clean" ASCII string types coming back.. many languages (including Python 3) have dropped the notion of non-Unicode string (fsvo Unicode).

http://stackoverflow.com/comment/84760513
comment on: http://stackoverflow.com/q/48878219
score: 0
type: Comment
type: QuestionComment
has text: `.append(item)` is more straightforward than `.extend([item])`.

http://stackoverflow.com/a/48875774
type: AcceptedAnswer
downvote count: 0
has body: There are at least three problems with your code. First, as juanpa.arrivillaga mentions in the comment, you are printing business_amount in every case, but only assigning when customer == 'B' Second, you're not assigning if the kwh is equal to 500 for 'R' customers and 800 for 'B' customers. Finally, it looks like the elif kwh > 500 is meant to be on the same level as kwh &lt; 500. You probably want your code to look something like this: if customer == 'R' : if kwh &lt; 500: normal_amount = kwh * .12 print ("Please pay this amount: ", normal_amount) elif kwh &gt;= 500: over_amount = kwh * .15 print("Please pay this amount",over_amount)
upvote count: 2
accepted answer of: http://stackoverflow.com/q/48875678
type: Answer
score: 2
has comment: http://stackoverflow.com/comment/84755956
answers question: http://stackoverflow.com/q/48875678

http://stackoverflow.com/comment/84666203
comment on: http://stackoverflow.com/q/48830989
type: Comment
type: QuestionComment
has text: Some of your y-values, e.g. df['A'], are negative. Perhaps try to normalize your data, e.g. with sklearn's [MinMaxScaler](http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.MinMaxScaler.html)?
score: 0

http://stackoverflow.com/a/48893905
downvote count: 0
answers question: http://stackoverflow.com/q/48893529
score: 1
has comment: http://stackoverflow.com/comment/84794566
has comment: http://stackoverflow.com/comment/84794869
has body: If I understand you correctly, then you're looking for a logical AND between the arrays, where "yes" is 1 and "" is 0. So if we first convert your data to binary: (of course, you can skip this paragraph and assume we have binary data in the first place...) import numpy as np def convert_to_binary(arr): return 1 * (np.array(arr) == 'yes') needle = convert_to_binary(needle) # array([0, 1, 1, 0, 0, 0, 1, 1, 1, 0]) haystack = np.array([convert_to_binary(h_arr) for h_arr in haystack]) # array([[0, 0, 1, 1, 0, 0, 1, 1, 0, 1], # [0, 0, 0, 1, 1, 0, 0, 0, 1, 1]]) Their logical AND: their_logical_and = needle &amp; haystack # array([[0, 0, 1, 0, 0, 0, 1, 1, 0, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]) To achieve the non-zero indices, can use numpy.nonzero: indices = [list(np.nonzero(arr)[0]) for arr in their_logical_and] # [[2, 6, 7], [8]]
upvote count: 1
has comment: http://stackoverflow.com/comment/84794736
type: Answer

http://stackoverflow.com/a/48863215
type: Answer
has comment: http://stackoverflow.com/comment/84864497
score: 3
has body: I'm using following dockerfile to connect my Raspberry Pi 3 to a remote SQL Express database. It should document all steps needed. My Pi is running HypriotOS which is based on Raspian. FROM arm32v7/python:3 RUN apt-get update #1. Install dependencies for PyODBC and tds RUN apt-get install -y tdsodbc unixodbc-dev RUN apt install unixodbc-bin -y RUN apt-get clean -y #2. Edit /etc/odbcinst.ini RUN echo "[FreeTDS]\n\ Description = FreeTDS unixODBC Driver\n\ Driver = /usr/lib/arm-linux-gnueabi/odbc/libtdsodbc.so\n\ Setup = /usr/lib/arm-linux-gnueabi/odbc/libtdsS.so" &gt;&gt; /etc/odbcinst.ini #3. Install requirements (contains pyodbc) COPY ./requirements.txt /usr/src/app/requirements.txt RUN pip install --no-cache-dir -r requirements.txt #Copy and run my app COPY . . CMD [ "python", "app.py"] So it's basically three steps: Install dependencies for PyODBC and tds Edit /etc/odbcinst.ini Install PyODBC, eg.: pip install pyodbc In my code I'm able to connect to the db like this: connection = pyodbc.connect(driver='{FreeTDS}', server='111.66.111.66\SQLEXPRESS', uid='sa', pwd='notmyactualpw')
has comment: http://stackoverflow.com/comment/84851826
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48813238
has comment: http://stackoverflow.com/comment/84859577
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84850971
answers question: http://stackoverflow.com/q/48813238
has comment: http://stackoverflow.com/comment/84852928
has comment: http://stackoverflow.com/comment/84859380

http://stackoverflow.com/comment/84868494
has text: Can you post a link to your whole html file?
type: Comment
comment on: http://stackoverflow.com/a/48916686
score: 0
type: AnswerComment

http://stackoverflow.com/a/48951650
upvote count: 14
has comment: http://stackoverflow.com/comment/84985584
answers question: http://stackoverflow.com/q/48951591
has comment: http://stackoverflow.com/comment/86280859
accepted answer of: http://stackoverflow.com/q/48951591
has comment: http://stackoverflow.com/comment/85016619
has body: Your implementation converts the integer to a base two string then visits each character in the string. Instead, you could just visit each bit in the integer using &lt;&lt; and &amp;. Doing so will avoid visiting each bit twice (first to convert it to a string, then to check if if it's a "1" or not in the resulting string). It will also avoid allocating memory for the string and then for each substring you inspect. You can inspect each bit of the integer by visiting 1 &lt;&lt; 0, 1 &lt;&lt; 1, ..., 1 &lt;&lt; (x.bit_length). For example: def max_gap(x): max_gap_length = 0 current_gap_length = 0 for i in range(x.bit_length()): if x &amp; (1 &lt;&lt; i): # Set, any gap is over. if current_gap_length &gt; max_gap_length: max_gap_length = current_gap_length current_gap_length = 0 else: # Not set, the gap widens. current_gap_length += 1 # Gap might end at the end. if current_gap_length &gt; max_gap_length: max_gap_length = current_gap_length return max_gap_length
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84910728
has comment: http://stackoverflow.com/comment/84973456
has comment: http://stackoverflow.com/comment/84913604
has comment: http://stackoverflow.com/comment/86290377
type: Answer
has comment: http://stackoverflow.com/comment/84910156
has comment: http://stackoverflow.com/comment/84988024
score: 14

http://stackoverflow.com/comment/84715678
score: 0
has text: not quite sure how this will recreate my function. Where do I put this code?
type: Comment
comment on: http://stackoverflow.com/a/48848600
type: AnswerComment

http://stackoverflow.com/comment/84903627
type: QuestionComment
has text: Another name for "sum of the squared difference from the mean" is `variance`. Perhaps there are some relevant optimized functions?
score: 1
comment on: http://stackoverflow.com/q/48948534
type: Comment

http://stackoverflow.com/q/48956125
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84919161
tagged with: python
has answer: http://stackoverflow.com/a/48956231
has comment: http://stackoverflow.com/comment/84919711
has comment: http://stackoverflow.com/comment/84922951
type: Question
answer count: 2
has comment: http://stackoverflow.com/comment/84922887
has answer: http://stackoverflow.com/a/48956247
has comment: http://stackoverflow.com/comment/84919183
has comment: http://stackoverflow.com/comment/84922899
has body: I am learning about class structure in python. Would like to know if it's possible to pass one argument through more than one method. class Example(object): def __init__(self, x): self.x = x def square(self): return self.x**2 def cube(self): return self.x**3 def squarethencube(y): sq = Example.square(y) cu = Example.cube(sq) return cu two = Example(2) print(two.squarethencube()) Error is on line 10; AttributeError: 'int' object has no attribute 'x' The goal is to use the 'squarethencube' method to pass '2' to square(), which is 4. Then pass '4' to cube(). The desired output is '64'. Obviously, you can write a function to do the math in a very simple way; the question here is how to use multiple methods. I understand the error in that .x is getting assigned as an attribute onto the output of cube(sq). I was getting the same error, but on line 7, before I changed the argument to y (from self.x). I've found some similar answers here but I need a simpler explanation.
has title: python; how to pass one argument through multiple methods in a class
score: 0
has comment: http://stackoverflow.com/comment/84920460

http://stackoverflow.com/q/48848919
score: 0
tagged with: data-analysis
linked to: http://stackoverflow.com/q/15109665
has comment: http://stackoverflow.com/comment/84701684
has answer: http://stackoverflow.com/a/48849025
duplicate of: http://stackoverflow.com/q/15109665
tagged with: python
accepted answer: http://stackoverflow.com/a/48849025
type: AnsweredQuestion
has title: file cannot be executed in command line using Python
type: Question
has body: I am a beginner to python and I have a txt file which contains list of URLs, and when I want to scan the txt file, I got error in the last which says KeyboardInterrupt. This is my code if name == "main": # Directory that contains panafapi.py SCRIPT_DIRECTORY = "/Users/kiya/Downloads/panpython/bin" RES_DIRECTORY = "/Users/kiya/Desktop/result/" TODAY = datetime.date.today().strftime("%Y%m%d") CHECK_DATE, NOW_DATE = "2018-01-01", "2018-01-31" try: url_file = sys.argv[1] except Exception: print("Usage: python3 {} [url file]".format(sys.argv[0])) sys.exit() url_file = str(url_file) df=open(url_file,"r",encoding="utf-8", errors='replace') data=df.readlines();df.close() urlPattern = re.compile(r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&amp;+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+') url_list = [] for url in data: dt = url.strip() dt = re.findall(urlPattern,dt)# get URLs if dt: url_list.append(dt[0]) print("Read {} Url(s)".format(len(url_list))) group_i = 0
answer count: 1

http://stackoverflow.com/comment/84676479
has text: Well, a NUL in the middle is not left nor right is it? But I am unsure about your comment "white space". Your own attempt correctly (!) lists `\t`, `\r`, `\n`, and `\0` but leaves out the space itself. Should it also be removed? Would you not rather *replace* these characters with a correct single space?
type: Comment
type: QuestionComment
score: 1
comment on: http://stackoverflow.com/q/48835731

http://stackoverflow.com/q/48855343
has body: #x_train.shape = 7x5x5 numpy array #y_train.shape = 3x5x5 numpy array #x_test.shape = (7,) numpy array #y_test.shape = (3,) numpy array I have binary output as 0 or 1. timeteps = 5 data_dim = 5 model = Sequential() model.add(LSTM(32, return_sequences=True, input_shape=`(timesteps,data_dim))) model.add(LSTM(32, return_sequences=True)) model.add(LSTM(32)) model.add(Dense(1,activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, epochs=5, batch_size=1) score = model.evaluate(X_test,y_test,batch_size=1) ValueError: Error when checking target: expected dense_1 to have 2 dimensions, but got array with shape (3, 5, 5) I am trying to model LSTM using random data and this error occurs. I have tried many things but I could not succeed. Thanks in advance.
tagged with: python
has comment: http://stackoverflow.com/comment/84719245
accepted answer: http://stackoverflow.com/a/48857888
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84716998
score: 1
upvote count: 1
type: Question
tagged with: lstm
has answer: http://stackoverflow.com/a/48857888
has title: LSTM Keras target size error
answer count: 1
downvote count: 0
tagged with: keras
favorite count: 0

http://stackoverflow.com/q/48953127
has comment: http://stackoverflow.com/comment/84916078
has comment: http://stackoverflow.com/comment/84918930
has comment: http://stackoverflow.com/comment/84914223
has comment: http://stackoverflow.com/comment/84913614
has comment: http://stackoverflow.com/comment/84916447
has comment: http://stackoverflow.com/comment/84917133
type: UnansweredQuestion
has title: Python -- Unable to find element by Xpath, ID and Name
answer count: 0
has comment: http://stackoverflow.com/comment/84913069
has body: I just recently start to use Python, and I'm trying to input something into a search bar as shown in the picture. I have tried Xpath, Name and ID, but none of those works. It looks pretty straight forward, but I keep receiving error messages. I have tried: driver.find_element_by_xpath('//*[@id="PRCSRUNCNTL_RUN_CNTL_ID"]') driver.find_element_by_name("PRCSRUNCNTL_RUN_CNTL_ID") driver.find_element_by_id("win0divPRCSRUNCNTL_RUN_CNTL_ID") Error Messages for Xpath:
has comment: http://stackoverflow.com/comment/84913416
has comment: http://stackoverflow.com/comment/84916505
type: Question
has comment: http://stackoverflow.com/comment/84913514
has comment: http://stackoverflow.com/comment/84913086
tagged with: python
has comment: http://stackoverflow.com/comment/84917759
has comment: http://stackoverflow.com/comment/84916953
has comment: http://stackoverflow.com/comment/84915687
has comment: http://stackoverflow.com/comment/84913716
favorite count: 0
tagged with: xpath
upvote count: 2
score: 0
downvote count: 2
tagged with: selenium
has comment: http://stackoverflow.com/comment/84916986

http://stackoverflow.com/q/48951591
type: Question
score: 12
has answer: http://stackoverflow.com/a/65963437
has answer: http://stackoverflow.com/a/65200381
has answer: http://stackoverflow.com/a/67869768
has answer: http://stackoverflow.com/a/56940643
has answer: http://stackoverflow.com/a/62112683
has answer: http://stackoverflow.com/a/49611289
has answer: http://stackoverflow.com/a/57921053
favorite count: 0
has answer: http://stackoverflow.com/a/48951650
accepted answer: http://stackoverflow.com/a/48951650
has body: I would like to know if my implementation is efficient. I have tried to find the simplest and low complex solution to that problem using python. def count_gap(x): """ Perform Find the longest sequence of zeros between ones "gap" in binary representation of an integer Parameters ---------- x : int input integer value Returns ---------- max_gap : int the maximum gap length """ try: # Convert int to binary b = "{0:b}".format(x) # Iterate from right to lift # Start detecting gaps after fist "one" for i,j in enumerate(b[::-1]): if int(j) == 1: max_gap = max([len(i) for i in b[::-1][i:].split('1') if i]) break except ValueError: print("Oops! no gap found") max_gap = 0 return max_gap let me know your opinion.
has title: Python: Find longest binary gap in binary representation of an integer number
possible better answer: http://stackoverflow.com/a/49611289
has answer: http://stackoverflow.com/a/52713086
has answer: http://stackoverflow.com/a/63675074
answer count: 27
upvote count: 12
tagged with: python-3.x
tagged with: binary
has answer: http://stackoverflow.com/a/69065130
has answer: http://stackoverflow.com/a/59276807
has answer: http://stackoverflow.com/a/52660479
has answer: http://stackoverflow.com/a/70385441
linked to: http://stackoverflow.com/q/699866
downvote count: 0
has answer: http://stackoverflow.com/a/53255119
has answer: http://stackoverflow.com/a/70795667
tagged with: python
has answer: http://stackoverflow.com/a/65939585
has answer: http://stackoverflow.com/a/52971223
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/49598506
has answer: http://stackoverflow.com/a/64603268
has answer: http://stackoverflow.com/a/61967905
has answer: http://stackoverflow.com/a/55008605
has answer: http://stackoverflow.com/a/63124847
has answer: http://stackoverflow.com/a/48951927
has comment: http://stackoverflow.com/comment/125348911
has answer: http://stackoverflow.com/a/60026564
has answer: http://stackoverflow.com/a/59809865
has answer: http://stackoverflow.com/a/53338459

http://stackoverflow.com/comment/84867036
type: AnswerComment
score: 1
type: Comment
has text: Yes, this is the right answer. I stumbled upon this error before and you can also do:`pd.Series(list1, index=list2).to_frame().T`. I like your first answer though.
comment on: http://stackoverflow.com/a/48930121

http://stackoverflow.com/q/48950806
has answer: http://stackoverflow.com/a/48951101
answer count: 6
has body: Trying to split the string at number 7 and I want 7 to be included in the second part of the split string. Code: a = 'cats can jump up to 7 times their tail length' words = a.split("7") print(words) Output: ['cats can jump up to ', ' times their tail length'] String got split but second part doesn't include 7. I want to know how I can include 7. note: not a duplicate of Python split() without removing the delimiter because the separator has to be part of the second string.
has title: Using split function in python3.5
has answer: http://stackoverflow.com/a/66889190
favorite count: 0
tagged with: python-3.x
accepted answer: http://stackoverflow.com/a/48951101
has answer: http://stackoverflow.com/a/48950924
linked to: http://stackoverflow.com/q/7866128
tagged with: python
has answer: http://stackoverflow.com/a/66889478
has answer: http://stackoverflow.com/a/48952850
type: AnsweredQuestion
possible better answer: http://stackoverflow.com/a/48950866
upvote count: 5
has answer: http://stackoverflow.com/a/48950866
type: Question
score: 5
downvote count: 0

http://stackoverflow.com/q/48875365
type: UnansweredQuestion
has body: I'm trying to do a proof of concept for accessing files from an NFS v4.1 server via a lambda function. Of the supported languages, I personally prefer Python... but I have been looking at the other languages as well and have yet to find a library to support this. I'd rather not build an NFS client from scratch and since this is Lambda, I have limited OS access so it's not as simple as mounting it on the OS and using os.system (or the more politically correct newer shell command functions) to run the OS equivalent. Anyone have experience with doing this sort of thing or can link me to a completely native python nfs client for v4.1 (or really a native client for any lambda supported language: python, nodejs, go, c#, java)?
score: 4
type: Question
upvote count: 4
downvote count: 0
favorite count: 0
tagged with: aws-lambda
has title: NFS Client for use in AWS Lambda Function
tagged with: python
answer count: 0

http://stackoverflow.com/a/48843171
score: 0
has body: The one thing that stands out is this line: nameList[1] = nameList[1] + 1 nameList[1] is the second inner list in your main list. I think you probably meant nameList[x][1]: nameList[x][1] = nameList[x][1] + 1
has comment: http://stackoverflow.com/comment/84690625
answers question: http://stackoverflow.com/q/48843120
type: Answer
has comment: http://stackoverflow.com/comment/84691126

http://stackoverflow.com/a/48847175
type: AcceptedAnswer
downvote count: 0
accepted answer of: http://stackoverflow.com/q/48835308
has body: Just include the portions you want from foo.h in the foo.i file instead of %include "foo.h" that processes everything: foo.i %module foo %{ #include "foo.h" %} typedef enum fooEnumType { CAT, DOG, HORSE } fooEnum; foo.h typedef enum fooEnumType { CAT, DOG, HORSE } fooEnum; typedef enum otherEnumType { A, B, C } otherEnum; Output: &gt;&gt;&gt; import foo &gt;&gt;&gt; dir(foo) ['CAT', 'DOG', 'HORSE', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '_ _spec__', '__warningregistry__', '_foo', '_newclass', '_object', '_swig_getattr', '_swig_property', '_swig_repr', '_swig _setattr', '_swig_setattr_nondynamic'] Note that CAT/DOG/HORSE are defined but A/B/C are not. swig -python foo.i generated the wrapper with no errors.
answers question: http://stackoverflow.com/q/48835308
has comment: http://stackoverflow.com/comment/84744599
type: Answer
upvote count: 1
has comment: http://stackoverflow.com/comment/84752695
score: 1

http://stackoverflow.com/comment/84790242
score: 1
type: Comment
comment on: http://stackoverflow.com/q/48892348
type: QuestionComment
has text: writer.writerow(val)

http://stackoverflow.com/comment/84736947
has text: does this mean my code is okay or what is the advantage to your method (srry just wondering why start bottom left to right)?
type: Comment
comment on: http://stackoverflow.com/a/48866817
score: 0
type: AnswerComment

http://stackoverflow.com/comment/84657171
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48826740
has text: I hope you realise that `i<5, j>0` is effectively just `j>0`.
score: 2

http://stackoverflow.com/a/48914468
downvote count: 0
score: 1
has body: By using encoding='ansi' as in f = open('test', 'w', encoding = 'ansi')
has comment: http://stackoverflow.com/comment/84835467
answers question: http://stackoverflow.com/q/48914221
upvote count: 1
type: Answer
has comment: http://stackoverflow.com/comment/84835344
has comment: http://stackoverflow.com/comment/84835269
has comment: http://stackoverflow.com/comment/84835500
has comment: http://stackoverflow.com/comment/84835577

http://stackoverflow.com/a/48836001
score: 0
has comment: http://stackoverflow.com/comment/84676937
has comment: http://stackoverflow.com/comment/84677177
type: Answer
has comment: http://stackoverflow.com/comment/84677032
answers question: http://stackoverflow.com/q/48835809
has body: In Python3, you can use unpacking in a list comprehension: s = [(('5', 'Generous', '&lt;=X'), 0.33333333333333)] final_results = [((*b, c), a) for (*b, c), a in s if len(b)+1 &gt;=3 and c == '&lt;=X']

http://stackoverflow.com/q/48842037
tagged with: variable-assignment
tagged with: python
has answer: http://stackoverflow.com/a/48842146
answer count: 4
type: AnsweredQuestion
accepted answer: http://stackoverflow.com/a/48842141
tagged with: machine-learning
has body: I'm beginner with tensorflow. I created this tensor z = tf.zeros([20,2], tf.float32) and I want to change the value of index z[2,1] and z[2,2] to 1.0 instead of zeros. How can I do that?
has title: Fill a specific index in tensor with a value
tagged with: tensorflow
type: Question
possible better answer: http://stackoverflow.com/a/55796211
tagged with: arrays
has answer: http://stackoverflow.com/a/55796211
score: 4
upvote count: 4
has answer: http://stackoverflow.com/a/70211757
downvote count: 0
has answer: http://stackoverflow.com/a/48842141
favorite count: 0

http://stackoverflow.com/a/48837039
score: 1
answers question: http://stackoverflow.com/q/48836860
has comment: http://stackoverflow.com/comment/84679130
has comment: http://stackoverflow.com/comment/84678987
has comment: http://stackoverflow.com/comment/84680829
upvote count: 1
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84679090
has comment: http://stackoverflow.com/comment/84679277
type: Answer
downvote count: 0
has comment: http://stackoverflow.com/comment/84679158
has comment: http://stackoverflow.com/comment/84679071
accepted answer of: http://stackoverflow.com/q/48836860
has body: You need to use the boto3 library to talk to S3 from your python app. This link might be a good start for you - http://boto3.readthedocs.io/en/latest/guide/s3-examples.html import json import boto3 data = {} data['name'] = "foo" data['description'] = "bar" json_data = json.dumps(data, ensure_ascii=False) s3 = boto3.client('s3') s3.put_object(Bucket='my-bucket', Key='key-name', Body=json_data) put_object() - https://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.put_object

http://stackoverflow.com/a/48945900
has comment: http://stackoverflow.com/comment/84966524
score: 79
has comment: http://stackoverflow.com/comment/135098976
type: Answer
has comment: http://stackoverflow.com/comment/94224220
has comment: http://stackoverflow.com/comment/98975930
has body: I've had success streaming data to S3, it has to be encoded to do this: import boto3 def lambda_handler(event, context): string = "dfghj" encoded_string = string.encode("utf-8") bucket_name = "s3bucket" file_name = "hello.txt" s3_path = "100001/20180223/" + file_name s3 = boto3.resource("s3") s3.Bucket(bucket_name).put_object(Key=s3_path, Body=encoded_string) If the data is in a file, you can read this file and send it up: with open(filename) as f: string = f.read() encoded_string = string.encode("utf-8")
upvote count: 79
downvote count: 0
has comment: http://stackoverflow.com/comment/101648475
has comment: http://stackoverflow.com/comment/116155737
accepted answer of: http://stackoverflow.com/q/48945389
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/118849413
answers question: http://stackoverflow.com/q/48945389

python-datetime
tag name: python-datetime
tags question: http://stackoverflow.com/q/48828173
type: Tag

http://stackoverflow.com/q/48956575
downvote count: 0
score: 10
tagged with: pandas
has body: I have a "single-liner" dataframe like this: Value 1 Value 2 Value 3 code 123 0 3 231 I want to turn the zero values into empty, so it gets to look like this: Value 1 Value 2 Value 3 code 123 3 231 How could I do that?
favorite count: 0
has comment: http://stackoverflow.com/comment/84920101
has answer: http://stackoverflow.com/a/48956650
tagged with: python
possible better answer: http://stackoverflow.com/a/48956635
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48956635
has title: Turn zero values to empty cells in Pandas
has comment: http://stackoverflow.com/comment/84921679
upvote count: 10
type: Question
answer count: 2
accepted answer: http://stackoverflow.com/a/48956650

http://stackoverflow.com/a/52273303
type: Answer
has body: As I can't comment on Jay's answer because of lack of reputation, just adding code part on how to do date conversion from string. from dateutil.parser import parse from datetime import datetime try: dt = parse(row[4]); if(isinstance(dt,datetime.date)): task.logtime = EntityProperty(EdmType.DATETIME, dt) except ValueError as err: task.logtime=row[4] The try/except block can be used in case you are dynamically reading a json where you are not aware of the datatype of each field.
answers question: http://stackoverflow.com/q/48919195
score: 0

http://stackoverflow.com/a/48838691
score: 1
upvote count: 1
has body: Try adding sudo before easy_install sudo easy_install Pillow
downvote count: 0
type: Answer
answers question: http://stackoverflow.com/q/48838533

http://stackoverflow.com/q/48962130
has title: Infinite interprocess communication between java program and a python script
score: 0
tagged with: python
has body: I want to achieve interprocess communication between my java app and the python script that it calls through its code. The idea is that the python script runs in an infinite while loop, accepts input, processes the input and prints the result in the console. Meanwhile, the java app sends the input, waits for the python script to process it, and reads it from the console (using InputStream from the python process, omitted for brevity) when the python script is done processing. How would one go about achieving this type of communication? Java program import java.io.*; public class JavaProgram { public static void main(String[] args) throws IOException{ Process p = Runtime.getRuntime().exec("python pythonScript.py"); OutputStream os = p.getOutputStream(); os.write("Hello".getBytes()); os.close(); os = p.getOutputStream(); os.write("World".getBytes()); os.close(); os = p.getOutputStream(); os.write("quit".getBytes()); os.close(); } } Python script def transformString(string): return "Java said: " + string file = open("writingFile.txt", "w+") while True: user_input = input('\n&gt; ') message = transformString(user_input) if message == "quit": break file.write(message + "\n") print(message + "\n") file.write("closing file...\n") file.close() The problem with the above code is that the java app can only send the input once (only "Hello" is sent) and then closes the output stream (tried without closing it). I know this because the python script never finished. Here is the contents of the file writingFile.txt: Java said: Hello *Note: It's really important that the python script is started once, because the original script's init methods are time-consuming. *Second note: The python's processing method also takes a bit of time, so how I don't know how to tell the java program when it's should start reading the output.
answer count: 0
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84930367
has comment: http://stackoverflow.com/comment/84930404
type: Question
tagged with: java
has comment: http://stackoverflow.com/comment/84930335

http://stackoverflow.com/comment/84934501
score: 0
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48952228
has text: Formatting is done

http://stackoverflow.com/comment/84813283
type: Comment
score: 2
comment on: http://stackoverflow.com/q/48903934
has text: Yes the function is returning a value. How are you running this code? Note that you're not *printing* the result.
type: QuestionComment

http://stackoverflow.com/comment/84913653
score: 0
type: Comment
type: QuestionComment
has text: I can't see rebound percentage column in the table. What do you mean by that?
comment on: http://stackoverflow.com/q/48953042

http://stackoverflow.com/comment/84776593
type: QuestionComment
has text: @VikasDamodar I want `"Thursday"` to parse to the date of the last Thursday (with respect to some reference), `"Dec 10"` to be the last day with that date (regardless if it was this or last year) and so on.
comment on: http://stackoverflow.com/q/48884480
score: 0
type: Comment

http://stackoverflow.com/comment/84711621
type: QuestionComment
has text: Use: `fi = ti if isinstance(ti, float) else sum(ti)`.
comment on: http://stackoverflow.com/q/48854040
score: 0
type: Comment

http://stackoverflow.com/a/63043513
score: 1
answers question: http://stackoverflow.com/q/48879920
downvote count: 0
has body: Yes, dags must be present on all airflow nodes - worker, webserver, scheduler. You can have a cron that runs git pull in your dags folder on all nodes to keep it in sync. Airflow will move all dags to database instead of file system - this feature might come in 2.0.
type: Answer
upvote count: 1

http://stackoverflow.com/q/48953557
favorite count: 0
has answer: http://stackoverflow.com/a/48954145
type: UnansweredQuestion
has title: Mapping keys to multiple keys and associated values with python
tagged with: python
tagged with: dictionary
has comment: http://stackoverflow.com/comment/84913934
tagged with: list
downvote count: 2
has answer: http://stackoverflow.com/a/48953701
has answer: http://stackoverflow.com/a/48953918
type: Question
has body: Here is the following test code: dict1 = {'k1': '{v1}', 'k2':'{v2}', 'k3':'{v3}' , 'k3':'{v4}'} list1 = ['k1_1', 'k2_2', 'k3_3', 'k3_4'] newdict = {} for items in list1: val = items.split('_')[0] if val in dict1.keys(): newdict[items] = dict1[val] This yields: {'k1_1': '{v1}', 'k2_2': '{v2}', 'k3_3': '{v4}', 'k3_4': '{v4}'} What I really want is: {'k1_1': '{v1}', 'k2_2': '{v2}', 'k3_3': '{v3}', 'k3_4': '{v4}'} The above code works like a charm when there is only one-one mapping from the list and keys in dictionary. What modification can I make to ensure that the values are preserved after the exchange in keys takes place?
has comment: http://stackoverflow.com/comment/84914021
upvote count: 0
score: -2
has comment: http://stackoverflow.com/comment/84913909
has comment: http://stackoverflow.com/comment/84913942
has comment: http://stackoverflow.com/comment/84913993
answer count: 3
has comment: http://stackoverflow.com/comment/84914020

http://stackoverflow.com/q/48837086
has answer: http://stackoverflow.com/a/70868419
downvote count: 0
answer count: 1
favorite count: 0
type: UnansweredQuestion
tagged with: python
has body: I use pyautogui to search an image on Desktop window for click automation. pyautogui.locateOnScreen(image) If the image is captured on the same screen as screenshot, it can be matched. However, if the image is a bit different, it cannot. e.g. captured as the low resolution image. Can I set some likelihood in pyautogui or use other library?
upvote count: 3
type: Question
score: 3
tagged with: automation
has title: How to search not same images but similar images by pyautogui
tagged with: pyautogui

http://stackoverflow.com/comment/84795582
type: Comment
type: QuestionComment
has text: The other thing to consider is instead of lists use generators. I don't know what your particular use case is, so I cant suggest anything concrete.
comment on: http://stackoverflow.com/q/48872239
score: 0

http://stackoverflow.com/comment/84775057
type: QuestionComment
score: 0
comment on: http://stackoverflow.com/q/48874610
has text: I appreciate the latest feedback from you all, I'll experiment with the advice you've given and post back here in a few days or so!
type: Comment

http://stackoverflow.com/comment/84908119
comment on: http://stackoverflow.com/q/48950800
has text: If you try to hit the site with your browser do you get a 403?
type: QuestionComment
type: Comment
score: 1

http://stackoverflow.com/comment/84716570
comment on: http://stackoverflow.com/q/48856504
type: Comment
type: QuestionComment
has text: I need to find words in a list, and occur reversed and occur in the list
score: 0

http://stackoverflow.com/a/63945516
downvote count: 0
has body: How do order of operations go on Python? I don't know what a PE(MD)(AS) is, but Python order of operations (order of precedence) rules go as the "Operator Precedence" table from the official documentation says they go. :) Keep in mind, many of these operator precedence rules are opposite in Python how they are in C or in C++, but here are the "Operator precedence" rules in Python 3: To read all the footnotes in the table, click on the link just above. Reading I Still Need to Do PEMDAS: https://en.wikipedia.org/wiki/Order_of_operations#Mnemonics
score: 6
upvote count: 6
type: Answer
answers question: http://stackoverflow.com/q/48937457

linked-list
tags question: http://stackoverflow.com/q/48960087
tag name: linked-list
tags question: http://stackoverflow.com/q/48935441
tags question: http://stackoverflow.com/q/48875458
type: Tag
tags question: http://stackoverflow.com/q/48875290
tags question: http://stackoverflow.com/q/48932940
tags question: http://stackoverflow.com/q/48941381

http://stackoverflow.com/a/48903056
upvote count: 0
type: Answer
has body: One way would be to setup the user with higher privileges and eliminate the need of entering into enable mode. If the AAA is setup for local authentication on the Cisco device, adding privilege 15 in the username command will do the trick.
score: -1
answers question: http://stackoverflow.com/q/48868464
downvote count: 1

http://stackoverflow.com/comment/84855333
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48924090
has text: That is because there are no folder tree like `E:\ram\4'.
score: 0

http://stackoverflow.com/q/48850089
has comment: http://stackoverflow.com/comment/84704635
type: UnansweredQuestion
has comment: http://stackoverflow.com/comment/84703762
tagged with: python
has title: How to deal with Selenium Sendkey UTF-8 Error
answer count: 0
tagged with: selenium
type: Question
tagged with: python-2.7
score: 0
has comment: http://stackoverflow.com/comment/84704040
has body: My python environment are able to print UTF-8 characters. Add " u " in front of UTF-8 characters CAN PASS selenium argument but it turns wrong UTF -8 characters in browser search result . from selenium import webdriver dr = webdriver.Firefox(executable_path='C:/Python27/Lib/selenium/geckodriver.exe') dr.get('http://google.com/') search_bx = dr.find_element_by_name('q') search_bx.send_keys('ﾀｶｾﾌﾞｯｻﾝ 広島\n') *Without "executable_path=" command , selenium don't even involve browser *Don't know how to search(element name) directly in "Firefox" URL address bar, so i put dr.get('http://google.com/') script.

http://stackoverflow.com/a/48871291
upvote count: 2
answers question: http://stackoverflow.com/q/48871018
score: 2
downvote count: 0
has body: Here is one way which takes advantage of numpy array performance: import pandas as pd df = pd.DataFrame([[[111240.0, 110530.0, 108540.0, 108540.0]], [[117240.0, 119160.0, 120160.0, 121950.0]], [[180420.0, 180420.0, 183840.0, 183840.0]], [[160260.0, 159430.0, 159430.0, 157720.0]]], columns=['Counts']) df['mean'] = np.mean(np.vstack(df['Counts'].values), axis=1) # Counts mean # 0 [111240.0, 110530.0, 108540.0, 108540.0] 109712.5 # 1 [117240.0, 119160.0, 120160.0, 121950.0] 119627.5 # 2 [180420.0, 180420.0, 183840.0, 183840.0] 182130.0 # 3 [160260.0, 159430.0, 159430.0, 157720.0] 159210.0
has comment: http://stackoverflow.com/comment/84747584
has comment: http://stackoverflow.com/comment/84747084
type: Answer

http://stackoverflow.com/q/48875871
favorite count: 0
has body: I have a list of authors of papers that benefits from identity resolution! As an example, it should match these names: Peter J. Smith Peter Smith P.J. Smith P. J. Smith (works with space or without it) p.j. smith I'm new to RegEx. I'd like to write a RegEx in R/Python that match the initial of the first name and the whole last name and ignore the middle name. (Although, this method will have some issues, for example there are occurrences of names such as Peter L. Smith but I think considering the middle name will complicate things.) Thanks for your help.
accepted answer: http://stackoverflow.com/a/48876006
tagged with: python
tagged with: regex
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/48876006
type: Question
score: -2
has comment: http://stackoverflow.com/comment/84755951
has comment: http://stackoverflow.com/comment/84755762
has title: Identity resolution with RegEx
tagged with: http://stackoverflow.com/tag/r
downvote count: 3
upvote count: 1
answer count: 1

http://stackoverflow.com/a/48963463
type: Answer
answers question: http://stackoverflow.com/q/48962019
accepted answer of: http://stackoverflow.com/q/48962019
score: 2
has body: See this answer (and others on that question) for inspiration. For your case, you should not be using communicate, instead use stdin.write and stdout.readline. Your main script might look like below - while True: line = cmd.stdout.readline() print(line) if line.strip() == b'Loading...': print("sending data...") cmd.stdin.write(b"test\n") cmd.stdin.close() print("done") elif line.strip() == b'Done': break The outputs - b'Loading...\n' sending data... 5 done b'&gt; test\n' b'Done\n'
has comment: http://stackoverflow.com/comment/84934206
upvote count: 2
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84940482
has comment: http://stackoverflow.com/comment/84940837

http://stackoverflow.com/comment/84793147
type: QuestionComment
comment on: http://stackoverflow.com/q/48876631
has text: @juanpa.arrivillaga I kind of confused myself going through the code, but I think it's more clear now. Please let me know if this is not the case
score: 0
type: Comment

http://stackoverflow.com/comment/84929588
score: 2
type: QuestionComment
comment on: http://stackoverflow.com/q/48961749
type: Comment
has text: You forgot to check if `course_title` can actually be found in that HTML file, and you are assuming it will always be there.

http://stackoverflow.com/comment/101558064
score: 0
type: Comment
comment on: http://stackoverflow.com/a/50629425
type: AnswerComment
has text: @akki Thank you for authoring this addition with [#5489](https://github.com/apache/airflow/pull/5489/files) — it looks pretty cool. Is the problem it solves (vs DockerOperator) running Docker containers representing Airflow task instances on a remote Docker daemon that exists outside of your Airflow worker nodes?

http://stackoverflow.com/comment/84663649
has text: Why not just change the list using the index? list[0] += 1
type: QuestionComment
comment on: http://stackoverflow.com/q/48829853
type: Comment
score: 3

http://stackoverflow.com/comment/84723519
comment on: http://stackoverflow.com/a/48860143
type: AnswerComment
has text: i want empty values of 'Score' column to be replaced by mean of that particular gender. Rest value of 'Score' should be as it is.
score: 0
type: Comment

http://stackoverflow.com/a/48861992
upvote count: 0
score: -1
type: Answer
has body: The error says it all : ImportError: No module named org.openqa.selenium.JavascriptExecutor Which essentially means the module org.openqa.selenium.JavascriptExecutor wasn't found in it's intended location. Reason The issue can arise if the Selenium Client encounters an error while transmission or storage. Selenium Team is currently working on the issue SeleniumHQ/selenium/5378 to generate the binary checksum of the Downloaded Selenium Client which will help you to avoid encountering errors which may have been introduced during its transmission or storage. Solution Till then a solution will be to : Remove the references of the error-prone JARs from your Project. Clean the Project Workspace from your IDE &amp; Rebuild All. Download a frest set of JARs from Selenium Release Storage. Run CCleaner tool to wipe off all the OS chores. If your Web Browser (i.e. Chrome/Firefox/IE) base version is too old, uninstall the Web Browser through Revo Uninstaller and install a recent GA Release version of Web Browser. Add the required JARs only. Take a System Reboot. Execute your Tests.
downvote count: 1
answers question: http://stackoverflow.com/q/48857871

http://stackoverflow.com/a/49738183
answers question: http://stackoverflow.com/q/48832836
type: Answer
has body: If you're just looking for a subset to run through for development you can just insert a line early on that's cov = cov[:5000] If you're past that and want to evaluate your model's performance, I suggest sklearn test_train_split
score: 0

http://stackoverflow.com/comment/84865035
type: Comment
has text: As I understand Django, your website will start apps to get their functionallity.
type: QuestionComment
comment on: http://stackoverflow.com/q/48929153
score: 0

http://stackoverflow.com/comment/84927167
score: 0
type: Comment
has text: @ronaldo check out this question and answers: https://stackoverflow.com/questions/17949508/python-read-all-text-file-lines-in-loop
comment on: http://stackoverflow.com/a/48960261
type: AnswerComment

http://stackoverflow.com/a/76089245
type: Answer
downvote count: 0
score: 1
answers question: http://stackoverflow.com/q/48855400
upvote count: 1
has body: Offsets can be either offset (strings) or pd.Timedelta objects. Internally, both of them get converted into an offset using pd.tseries.frequencies.to_offset() method. The basic implementation of a rolling window computation with an offset is that for any given index, the offset is subtracted from it creating a slice of the column, i.e. a window, and the function (e.g. max() below) is called on this window. By default, first point in the window edge is excluded from the computation. df = pd.DataFrame({'A': [1,4,3,2]}, index=pd.to_datetime(['2020-01-01', '2020-01-02', '2020-01-02', '2020-01-04'])) df['A'].rolling('2D').max() 2020-01-01 1.0 2020-01-02 4.0 2020-01-02 4.0 2020-01-04 2.0 Name: A, dtype: float64 In the example above, the calculations are made in the following windows: 2020-01-01 = max(1) # `min_periods=1` on time-series [2020-01-01, 2020-01-02] = max(1, 4) # only the first value on 2020-01-02 is considered because the second is not seen yet [2020-01-01, 2020-01-02] = max(1, 4, 3) [2020-01-03, 2020-01-04] = max(2) # there is no data on 2020-01-03 All possible offsets are in the pd.offsets module. Among those, only the ones with fixed frequency are valid offsets.1 They are: Day (D) Hour (H) Minute (T) Second (S) Milli (L) Micro (U) Nano (N) Also the index can be DatetimeIndex, TimedeltaIndex or PeriodIndex. In fact, the rolling window don't even have to be on the index; it can be on a column of datetime, timedelta or period dtype. So for example, to use a rolling window of 3 microseconds, use 3U. df = pd.DataFrame({ 'time': pd.date_range('2020-01-01 12:00:00', '2020-01-01 12:00:01', 10**6), 'value': 1}).head() # check that each step is indeed 1 microsecond df['time'].diff().dropna().dt.microseconds.eq(1).all() # True df.rolling('3U', on='time')['value'].sum() 0 1.0 1 2.0 2 3.0 3 3.0 4 3.0 Name: value, dtype: float64 1 The following code returns these offsets. offsets = { name: obj().name for name in dir(pd.offsets) if hasattr((obj:=getattr(pd.offsets, name))…

http://stackoverflow.com/a/48898268
answers question: http://stackoverflow.com/q/48898196
type: AcceptedAnswer
has body: Solved it.The problem is the return statement inside the if statements.Due to this the code never returns the response.i put the whole code inside a while loop and use break to break out of the loop and return the response.Now it's working fine The changes: while True: s.send(cmd) response=s.recv(1024) print "The response received is:::" print response if RESP_OK in response: break elif RESP_SUCCESS in response: break elif RESP_FAILURE in response: break return response
type: Answer
accepted answer of: http://stackoverflow.com/q/48898196
score: 0

http://stackoverflow.com/a/48843926
accepted answer of: http://stackoverflow.com/q/48843162
upvote count: 1
has comment: http://stackoverflow.com/comment/84705081
answers question: http://stackoverflow.com/q/48843162
type: Answer
downvote count: 0
score: 1
has body: BFS tries to build a spanning tree. If you want to get the shortest path in the process, you can stop when you find the goal node for the first time - this is a typical use case for BFS. However if you want to find all paths, I think the stop condition is that you have visited all nodes, so the spanning tree is complete there are no further nodes you can access from the nodes you have visited already. You can not stop sooner, since even the very last node you are going to visit, may have an unidirectional edge leading to the goal node, revealing a new path (though the least optimal one). When writing the answer above I probably just partially understood the question. If you are asking about generating the paths at the end, and given a configuration like A---------&gt;B--------&gt;C \ / \ / \-&gt;D-&gt;/ \-&gt;E-&gt;/ you want to find all of ABC,ADBC,ABEC and ADBEC, I think you will need to do a full traversal on this valid-paths-graph in a recursive way, a DFS (just on this sub-graph, all possible attempts will generate a valid path). So the BFS-pass could be used to reduce the original graph into a graph containing actual (and possibly redundant) paths only, but then a DFS is needed to actually generate all of them separately.
type: AcceptedAnswer

http://stackoverflow.com/a/48895698
has body: One way would be to add a 1 in the range, then subtract a 1 from the index elements_list=['a','b','c','d'] lenght_list=len(elements_list) for i in range(1, lenght_list+1): print (str(i) + str(')') + elements_list[i-1]) Edit: TheoretiCAL's approach is even more straight forward, simply adding 1 to the print statement achieves the same thing.
type: Answer
answers question: http://stackoverflow.com/q/48895676
score: 1
has comment: http://stackoverflow.com/comment/84797342
downvote count: 0
upvote count: 1

http://stackoverflow.com/a/48932435
has comment: http://stackoverflow.com/comment/84873605
answers question: http://stackoverflow.com/q/48932201
type: Answer
has comment: http://stackoverflow.com/comment/84872892
has comment: http://stackoverflow.com/comment/84873778
has comment: http://stackoverflow.com/comment/84873953
score: 1
has comment: http://stackoverflow.com/comment/84872263
has comment: http://stackoverflow.com/comment/84873199
upvote count: 1
accepted answer of: http://stackoverflow.com/q/48932201
has comment: http://stackoverflow.com/comment/84874313
has body: To fix the error you need to pass lecture object to file before saving it to DB: if form1.is_valid() and form2.is_valid(): lecture = form1.save() file = form2.save(commit=False) file.lecture = lecture file.save() To create multiple related object at the same time you can use formsets. In your case you need to do something like this: from django.forms.models import inlineformset_factory FileFormset = inlineformset_factory(Lecture, FileUpload, fields=('files',)) if request.method == 'POST': form1 = LectureForm(request.POST) if form1.is_valid(): lecture = form1.save() formset = FileFormset(request.POST, request.FILES, instance=lecture) if formset.is_valid(): formset.save() return redirect('courses/courses.html') else: form1 = LectureForm() formset = FileFormset() context = {'teacher_data': TeacherData.objects.all(), 'teachers': Teacher.objects.all(), 'courses': Course.objects.all(), 'form1': form1, 'formset': formset, } In template add inside &lt;form&gt; tag: {{ formset.management_form }} {% for form in formset %} {{ form }} {% endfor %}
type: AcceptedAnswer
has comment: http://stackoverflow.com/comment/84871924
downvote count: 0
has comment: http://stackoverflow.com/comment/84873421

http://stackoverflow.com/q/48827884
type: Question
linked to: http://stackoverflow.com/q/7204805
has comment: http://stackoverflow.com/comment/84659561
duplicate of: http://stackoverflow.com/q/7204805
has answer: http://stackoverflow.com/a/48828727
has title: Incorrect result after merge two dictionary in case when {str: dict}
tagged with: python-2.7
answer count: 1
downvote count: 0
score: 1
favorite count: 0
tagged with: python
tagged with: merge
tagged with: dictionary
accepted answer: http://stackoverflow.com/a/48828727
type: AnsweredQuestion
has body: I trying to merge 2 dictionaries which have the ability to create nested dictionaries and had an incorrect result. Code example. def merge_two_dicts(x, y): z = x.copy() z.update(y) return z def create_dict(l, val): d = {} for a in reversed(l): if d == {}: d = {a: val} else: d = {a: d} return d test = "a.b.t.q" test2 = "a.b.t.w" list1 = test.split(".") list2 = test2.split(".") val1 = "test" val2 = "test2" dict1 = create_dict(list1, val1) dict2 = create_dict(list2, val2) merged_dict = merge_two_dicts(dict1, dict2) print "Dict #1" print dict1 print "========================" print "Dict #2" print dict2 print "========================" print "Merged dict" print merged_dict And the actual result is. Dict #1 {'a': {'b': {'t': {'q': 'test'}}}} ======================== Dict #2 {'a': {'b': {'t': {'w': 'test2'}}}} ======================== Merged dict {'a': {'b': {'t': {'w': 'test2'}}}} Expected: {'a': {'b': {'t': {'q': 'test', 'w': 'test2'}}}} How can I merge dictionaries like with without losing some items?
upvote count: 1
has comment: http://stackoverflow.com/comment/84659598

http://stackoverflow.com/comment/84713432
score: 0
type: AnswerComment
type: Comment
comment on: http://stackoverflow.com/a/48853233
has text: Yes, exactly. Then in python, you just need to read serial port.

http://stackoverflow.com/comment/84850610
type: Comment
comment on: http://stackoverflow.com/a/48922107
type: AnswerComment
has text: @AntoineM. That's the first line of the demo `py -m pdb test.py`
score: 0

http://stackoverflow.com/q/48862235
has body: I'm trying to get the average price of products containing any substrings from a wordlist from a dataframe. I've been able to do so with the following code on multiple spreadsheets - dframe['Product'].fillna('', inplace=True) dframe['Price'].fillna(0, inplace=True) total_count = 0 total_price = 0 for word in ransomware_wordlist: mask = dframe.Product.str.contains(word, case=False) total_count += mask.sum() total_price += dframe.loc[mask, 'Price'].sum() average_price = total_price / total_count print(average_price) However, one of the spreadsheets throws an error at line - dframe['Product'].fillna('', inplace=True) with ValueError: cannot index with vector containing NA / NaN values I fail to understand why dframe['Product'].fillna('', inplace=True) isn't handling this problem. In desperate need of some help! Thanks!
has title: Python - ValueError: Cannot index with vector containing NA / NaN values
score: 16
upvote count: 16
has answer: http://stackoverflow.com/a/48862333
accepted answer: http://stackoverflow.com/a/48862333
has comment: http://stackoverflow.com/comment/84727672
type: AnsweredQuestion
has answer: http://stackoverflow.com/a/63358810
tagged with: dataframe
type: Question
answer count: 2
downvote count: 0
has comment: http://stackoverflow.com/comment/84727546
tagged with: pandas
tagged with: python
tagged with: valueerror
has comment: http://stackoverflow.com/comment/84727489
has comment: http://stackoverflow.com/comment/84727586
favorite count: 0
tagged with: python-3.x
possible better answer: http://stackoverflow.com/a/63358810

http://stackoverflow.com/q/48868313
tagged with: python-3.x
duplicate of: http://stackoverflow.com/q/9152958
type: UnansweredQuestion
tagged with: python
has title: 3d Figures giving some error in python
score: 2
answer count: 0
upvote count: 2
tagged with: matplotlib
has body: So, a python newbie here. What I'm trying to do is to plot point onto 3d plane. Although some errors occur at execution. from mpl_toolkits.mplot3d import axes3d import matplotlib.pyplot as plt fig = plt.figure() chart = fig.add_subplot(1,1,1,projection='3d') X,Y,Z=[1,2,3,4,5,6,7,8],[2,5,3,8,9,5,6,1],[3,6,2,7,5,4,5,6] chart.plot_wireframe(X,Y,Z) plt.show() Output: Traceback (most recent call last): File "/home/nishantsikri/3d objects.py", line 10, in &lt;module&gt; chart.plot_wireframe(X,Y,Z) File "/home/nishantsikri/.local/lib/python3.6/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 1834, in plot_wireframe if Z.ndim != 2: AttributeError: 'list' object has no attribute 'ndim'
type: Question
has comment: http://stackoverflow.com/comment/84740385
linked to: http://stackoverflow.com/q/9152958
downvote count: 0
favorite count: 0

wagtail
tag name: wagtail
tags question: http://stackoverflow.com/q/48861186
tags question: http://stackoverflow.com/q/48856357
type: Tag

http://stackoverflow.com/q/48904348
type: Question
accepted answer: http://stackoverflow.com/a/48906067
upvote count: 0
answer count: 1
score: -1
tagged with: python-2.7
has comment: http://stackoverflow.com/comment/84814294
favorite count: 0
tagged with: jenkins
has answer: http://stackoverflow.com/a/48906067
tagged with: python
has title: python pattern matching joined with a string
downvote count: 1
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84815072
has body: I want to download a build file from jenkins job > last successful build. The filename is like: DevPackage-123.pkg where 123 is the last successful build number. In my python script using urllib, how can I pass this file name as a general variable. I mean filename = "DevPackage-" + &lt;3 digits> + ".pkg" These 3 digits which represent the build number are unknown to me while running the script.I am looking forwards to adda pattern of 3 digts in the file name.Please help! if jenkins == "branch" and build == "lastsuccessful": baselink = "http://" + credentials + "XXX.XXX.XXX.XXX/job/My_Build_Job/lastSuccessfulBuild/artifact/results/" filelist = ["DevPackage-XXX.pkg","MIBS.zip","udpServer.sh"] for index in range(len(filelist)): urllib.urlretrieve(baselink+filelist[index],newdir+filelist[index]) print filelist[index]+" Copied!"

http://stackoverflow.com/q/48932531
tagged with: python
tagged with: vim
answer count: 0
downvote count: 0
score: 1
type: Question
tagged with: python-mode
upvote count: 1
favorite count: 0
has body: I was wondering if there is any way to have errors always appear before PEP-8 warnings in the lint output? Either of re-ordering the output or having PEP-8 and other style warnings only reported if there are no errors would work for my needs.
type: UnansweredQuestion
has title: vim pymode - sort lint errors and warnings by significance

http://stackoverflow.com/a/59431137
downvote count: 0
answers question: http://stackoverflow.com/q/48835178
type: Answer
has body: According matplotlib document (matplotlib) the handles is optional, but for some reason most people get that error message. What I did was handles, labels = ax.get_leggend_handles_labels() ax.legend(handles, labels). It seems to work for me.
upvote count: 1
score: 1

http://stackoverflow.com/q/48828586
has answer: http://stackoverflow.com/a/48828669
upvote count: 4
has comment: http://stackoverflow.com/comment/84660963
answer count: 3
possible better answer: http://stackoverflow.com/a/48828669
tagged with: string
has comment: http://stackoverflow.com/comment/84660949
has comment: http://stackoverflow.com/comment/84661031
favorite count: 0
linked to: http://stackoverflow.com/q/988228
has answer: http://stackoverflow.com/a/48828621
tagged with: python
tagged with: dictionary
has title: Create dict from string in Python
type: AnsweredQuestion
score: 2
accepted answer: http://stackoverflow.com/a/48828621
has answer: http://stackoverflow.com/a/48828649
downvote count: 2
type: Question
has body: In my Python program, I have a string of format: 'name': 'Salman','age': '25', 'access': 'R', 'id': '00125' I want to convert it to type dict so that I can query like dict["name"] to get "Salman" printed.

http://stackoverflow.com/comment/84783137
has text: Another question is... how likely is it that you will query all (or most) values for a certain feature at the same time? If you do query them at the same time than solution 2 could still be a good idea.
comment on: http://stackoverflow.com/q/48887491
score: 0
type: Comment
type: QuestionComment

http://stackoverflow.com/comment/84778762
type: QuestionComment
has text: Is `regex=True` necessary?
score: 3
comment on: http://stackoverflow.com/q/48886886
type: Comment

http://stackoverflow.com/a/48819995
has comment: http://stackoverflow.com/comment/95746325
has body: import bpy from mathutils import Vector; n = "cube"; bpy.ops.mesh.primitive_cube_add(radius=1); orig_cube = bpy.context.active_object; for i in range(10000): m = orig_cube.data.copy(); o = bpy.data.objects.new(n, m); o.location = Vector((i, i, i)); bpy.context.scene.objects.link(o); bpy.ops.object.delete(); Takes about 15 seconds on my machine. If you don't need to have unique cubes (i.e. don't intend to modify their geometry separately) then you can attach the same mesh to multiple objects. There are probably faster ways like creating single mesh and point cloud and using dupliverts (duplicating child object on each vertex of point cloud). Example with just points and dupliverts (which, as expected, completes in a moment, but of course is not the same thing): import bpy; import bmesh; from mathutils import Vector; bpy.ops.mesh.primitive_cube_add(radius=1); orig_cube = bpy.context.active_object; bpy.ops.mesh.primitive_plane_add(); o = bpy.context.active_object; me = o.data; bm = bmesh.new(); for i in range(10000): bm.verts.new().co=Vector((i, i, i)); bm.to_mesh(me); o.dupli_type = 'VERTS'; orig_cube.parent = o;
type: AcceptedAnswer
downvote count: 0
has comment: http://stackoverflow.com/comment/84680075
type: Answer
answers question: http://stackoverflow.com/q/48818274
has comment: http://stackoverflow.com/comment/84680755
upvote count: 3
accepted answer of: http://stackoverflow.com/q/48818274
score: 3

http://stackoverflow.com/q/48951557
score: 1
upvote count: 1
has body: pysparkling 2.1 I run the following code: hc = H2OContext.getOrCreate(spark) h2o_frame = h2o.import_file('hdfs:path/to/my/file.csv') spark_frame = hc.as_spark_frame(h2o_frame) and it works just fine, just like in the documentation. But then when I try the following code: hc = H2OContext.getOrCreate(spark) h2o_frame = h2o.H2OFrame(some_list) spark_frame = hc.as_spark_frame(h2o_frame) #error at this line I get the following error: File "/my_path/my_file.py", line 530, in _convert_and_append spark_frame = hc.as_spark_frame(h2o_frame) File "/my_path/.virtualenv/lib/python2.7/site-packages/pysparkling/context.py", line 196, in as_spark_frame j_h2o_frame = h2o_frame.get_java_h2o_frame() File "/my_path/.virtualenv/lib/python2.7/site-packages/pysparkling/context.py", line 38, in get_java_h2o_frame self._java_frame = hc._jhc.asH2OFrame(self.frame_id) File "/usr/hdp/current/spark2-client/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py", line 1133, in __call__ File "/usr/hdp/current/spark2-client/python/lib/pyspark.zip/pyspark/sql/utils.py", line 63, in deco File "/usr/hdp/current/spark2-client/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py", line 319, in get_return_value py4j.protocol.Py4JJavaError: An error occurred while calling o67.asH2OFrame. : java.lang.NullPointerException at water.fvec.H2OFrame.&lt;init&gt;(H2OFrame.scala:38) at water.fvec.H2OFrame.&lt;init&gt;(H2OFrame.scala:46) at org.apache.spark.h2o.H2OContext.asH2OFrame(H2OContext.scala:234) at org.apache.spark.h2o.JavaH2OContext.asH2OFrame(JavaH2OContext.java:111) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.ja…
type: Question
has title: NullPointerException PySparkling H2OFrame to Spark DataFrame
tagged with: sparkling-water
tagged with: pyspark
has comment: http://stackoverflow.com/comment/84910293
tagged with: apache-spark
has comment: http://stackoverflow.com/comment/84909875
tagged with: h2o
downvote count: 0
favorite count: 0
type: UnansweredQuestion
tagged with: python
answer count: 0

http://stackoverflow.com/q/48953171
answer count: 0
type: Question
has comment: http://stackoverflow.com/comment/84913475
has title: Output pyowm weather as normal weather?
tagged with: openweathermap
duplicate of: http://stackoverflow.com/q/44121468
score: 0
tagged with: string
has comment: http://stackoverflow.com/comment/84913112
duplicate of: http://stackoverflow.com/q/33398806
type: UnansweredQuestion
linked to: http://stackoverflow.com/q/33398806
has body: Couldn't find any info whether on the pyowm git nor else While using pyowm, I use print(weather.get_weather()) and so on. Sadly the output looks like this, but I'm not surprised: &lt;pyowm.webapi25.weather.Weather - reference time=2018-02-23 16:55:00+00, status=Rain&gt; Pretty ugly. I was looking for a way of deleting all that useless stuff and keep the word after status= which now appears to be Rain. I know that something like fileNameOnly = start[:start.find(ext) + len(ext)] keeps everything 'till the specified character declared in ext,so I'd need a way to do the opposite.
tagged with: python
tagged with: text
has comment: http://stackoverflow.com/comment/84913404

http://stackoverflow.com/q/48924735
has body: I'm trying to copy file via Python's shutil. From Python interpreter, started from Powershell, execute: &gt;&gt;&gt; shutil.copy("C:\\Program Files\\1C\\AgentQMC\\1.0.10.2\\file.lock", "C:\\file.lock") (file.lock is a file, created by service, which is currently running ) but it gives me an error: Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "C:\Development\Python\Python36\lib\shutil.py", line 257, in copy2 copyfile(src, dst, follow_symlinks=follow_symlinks) File "C:\Development\Python\Python36\lib\shutil.py", line 122, in copyfile copyfileobj(fsrc, fdst) File "C:\Development\Python\Python36\lib\shutil.py", line 79, in copyfileobj buf = fsrc.read(length) PermissionError: [Errno 13] Permission denied I'm sure that I have all necessary permissions, because if i exit Python interpreter and try to copy file via Powershell, it works.
tagged with: shutil
has title: Cannot copy file via Python's shutil
accepted answer: http://stackoverflow.com/a/48927274
tagged with: python
has comment: http://stackoverflow.com/comment/84856498
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84857714
possible better answer: http://stackoverflow.com/a/58439839
has answer: http://stackoverflow.com/a/58439839
type: Question
answer count: 2
has answer: http://stackoverflow.com/a/48927274
has comment: http://stackoverflow.com/comment/84855736
score: 0

http://stackoverflow.com/a/65920608
answers question: http://stackoverflow.com/q/48959183
score: 0
type: Answer
has body: Try arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) print(arr[:, (0,1,3,4)]) Output [[ 1 2 4 5] [ 6 7 9 10]]

http://stackoverflow.com/comment/84926984
type: QuestionComment
comment on: http://stackoverflow.com/q/48960059
has text: Anything else I should try ?
score: 0
type: Comment

http://stackoverflow.com/q/48898318
score: 2
has title: How to run second random vector through tensorflow to compare output distributions?
tagged with: tensorflow
type: Question
has answer: http://stackoverflow.com/a/48917199
downvote count: 0
answer count: 1
has body: I am trying to implement a variational autoencoder design in tensorflow. This particular approach alters the KL divergence part of the loss to remove any dependence on x, (the input data that is). Instead they want to compare (q_phi(z) || p(z)) rather than (q_phi(z|x) || p(z)). I am taking it that I need to run a random normal or uniform vector of the right shape through the trained network, but am having a hard time figuring out how to input it. Here is what I have so far: class EncoderRNN(object): def __init__(self, x, n_steps, input_size, output_size, cell_size, num_layers, default_batch_size): # ### Data Input ### self.x = x # self.init_state = init_state self.n_steps = n_steps self.input_size = input_size self.output_size = output_size self.cell_size = cell_size self.num_layers = num_layers self.default_batch_size = default_batch_size ... class VAE(object): def __init__(self, time_steps, features, latent_dim, encoder_hidden, decoder_hidden, num_layers, default_batch_size, learning_rate): self.time_steps = time_steps self.features = features self.latent_dim = latent_dim self.encoder_hidden = encoder_hidden self.decoder_hidden = decoder_hidden self.num_layers = num_layers self.default_batch_size = default_batch_size self.LR = learning_rate with tf.name_scope('train_inputs'): # ### Multi-D timeseries input ### self.x = tf.placeholder("float", [None, self.time_steps, self.features]) ### 1 D timeseries output ### self.x_target = tf.placeholder("float", [None, self.time_steps, 1]) self.batch_size = tf.placeholder(dtype=tf.int32) ... Here is what I am trying to figure out: def build_codec(self): self.encoder = EncoderRNN(self.x, self.time_steps, self.features, self.latent_dim, self.encoder_hidden, self.num_layers, self.default_batch_size) # ### Output tensors from encoder ### self.mu = self.encoder.mu self.logvar = self.encoder.logvar epsilon = tf.random_normal(tf.shape(self.logvar), name='epsilon') std_encoder = tf.exp(0.5 * self.logvar) self.z = self.mu + tf.multipl…
favorite count: 0
upvote count: 2
type: UnansweredQuestion
tagged with: python

websocket
tags question: http://stackoverflow.com/q/48884922
tags question: http://stackoverflow.com/q/48818716
tags question: http://stackoverflow.com/q/48836493
type: Tag
tags question: http://stackoverflow.com/q/48825332
tag name: websocket
tags question: http://stackoverflow.com/q/48920230
tags question: http://stackoverflow.com/q/48931032
tags question: http://stackoverflow.com/q/48861657

http://stackoverflow.com/q/48857769
accepted answer: http://stackoverflow.com/a/48858099
has body: I am trying to write to a OpenSSL C extension for Python. The shared library(*.so file) is generated but I am running into undefined symbol errors when importing the module. It throws the following error (undefined symbol: AES_set_encrypt_key): &gt;&gt;&gt; import openssl_python Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: /home/rohith/python_c_extension/aes/openssl_python.cpython-35m-x86_64-linux-gnu.so: undefined symbol: AES_set_encrypt_key The following is my source code setup.py from distutils.core import setup, Extension openssl_module = Extension('openssl_python', sources = ['openssl_python.c']) setup(name = 'openssl', version = '1.0', description = 'Python Package with OpenSSL C Extension', ext_modules = [openssl_module]) openssl_python.c #include &lt;Python.h&gt; #include &lt;stdio.h&gt; #include &lt;openssl/des.h&gt; #include &lt;openssl/aes.h&gt; static PyObject* openssl_module_aes_encrypt(PyObject *self, PyObject *args){ char* sn; if (!PyArg_ParseTuple(args, "s", &amp;sn)) return NULL; AES_KEY key; unsigned char ivec[AES_BLOCK_SIZE]; unsigned char outBuf[16]; memcpy(ivec, sqlcFirmwareIvec, sizeof(sqlcFirmwareIvec)); AES_set_encrypt_key(sqlcFirmwareKey, sizeof(sqlcFirmwareKey) * 8, &amp;key); int dataLen = 16; int requiredLen = (dataLen / AES_BLOCK_SIZE) * AES_BLOCK_SIZE; if (dataLen % AES_BLOCK_SIZE) { requiredLen += AES_BLOCK_SIZE; } AES_cbc_encrypt(sn, outBuf, requiredLen, &amp;key, ivec, AES_ENCRYPT); return 1; } static PyMethodDef openssl_module_methods[] = { //Can add more functions here { "aes_encrypt", openssl_module_aes_encrypt, METH_VARARGS, "Method to encrypt data using Openssl's AES algorithm" }, {NULL, NULL, 0, NULL} }; static struct PyModuleDef openssl_module_definition = { PyModuleDef_HEAD_INIT, "hello_module", "A Python module that prints 'hello world' from C code.", -1, openssl_module_methods }; PyMODINIT_FUNC PyInit_openssl_python(void) { Py_Initialize(); return PyModule_Create(&amp;opens…
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84719189
tagged with: http://stackoverflow.com/tag/c
type: Question
score: 0
answer count: 2
has answer: http://stackoverflow.com/a/48858099
has comment: http://stackoverflow.com/comment/84719518
possible better answer: http://stackoverflow.com/a/48860447
tagged with: cpython
has answer: http://stackoverflow.com/a/48860447
has title: Python OpenSSL C extension: undefined symbol: AES_set_encrypt_key
tagged with: python
has comment: http://stackoverflow.com/comment/84719149

http://stackoverflow.com/comment/84739731
comment on: http://stackoverflow.com/a/48865245
score: 1
type: AnswerComment
type: Comment
has text: @Rockbar Could you edit the expected result as well?

scrapy-splash
tag name: scrapy-splash
tags question: http://stackoverflow.com/q/48834080
type: Tag

http://stackoverflow.com/comment/84818757
type: AnswerComment
score: 0
type: Comment
comment on: http://stackoverflow.com/a/48906154
has text: This will not work - the first list expression (which should actually be a generator expression - no need to build a list here) will consume all the file, so the second one will always yield an empty list. You'd have to reset the file pointer between the two statements, butand parsing the whole file twice is very inefficient anyway. Also, feeding strings to `min` and `max` may not yield the expected result (try `min(str(x) for x in range(5, 15))` to find out why).

newtons-method
tag name: newtons-method
type: Tag
tags question: http://stackoverflow.com/q/48867508

http://stackoverflow.com/comment/84680500
type: QuestionComment
has text: Thank you, tripleee, for your suggestion.
type: Comment
comment on: http://stackoverflow.com/q/48821347
score: 0

http://stackoverflow.com/a/48848006
has comment: http://stackoverflow.com/comment/84700082
has body: This is how I'd rearrange that v = [] # create a list where you can store all the values for i in range(5): print("Scout {} &gt; ".format(i + 1), end="") v.append(int(input())) # read it and append it to the end of the list print(max(v)) # your 'max' variable print(sum(v)) # your 'sold' variable Note that naming variable max is usually a bad idea, because it overrides the built-in function I've just used.
score: 0
answers question: http://stackoverflow.com/q/48847939
has comment: http://stackoverflow.com/comment/84700171
type: Answer

http://stackoverflow.com/a/48875921
answers question: http://stackoverflow.com/q/48837365
type: Answer
has body: Turns out the problem was my PYTHONPATH. ~/anaconda2/lib/python2.7 needs to be first. I had ~/lib/python before it, so it was using the wrong platform.py file.
score: 0
type: AcceptedAnswer
accepted answer of: http://stackoverflow.com/q/48837365

http://stackoverflow.com/comment/84715544
score: 0
has text: what is `pd.crosstab` what library
type: Comment
comment on: http://stackoverflow.com/q/48855998
type: QuestionComment

http://stackoverflow.com/comment/84844285
has text: It's referring to [slots](http://book.pythontips.com/en/latest/__slots__magic.html#slots-magic). There is some API that evidently optimizes slots differently than non-slots. Further, if you subclass that optimizer and access that named interface, your code will be broken, according to the notes. Not sure if that helps you.
score: 1
type: Comment
type: QuestionComment
comment on: http://stackoverflow.com/q/48918896

http://stackoverflow.com/q/48847450
has comment: http://stackoverflow.com/comment/84699005
has comment: http://stackoverflow.com/comment/84699168
favorite count: 0
has body: Currently doing HackerRank and one of the levels has this code: grade_book = {} n = int(input()) student_marks = {} for _ in range(n): name, *line = input().split() scores = list(map(float, line)) student_marks[name] = scores query_name = input() I'm not sure what the *line does in this example. The program is supposed to take a number of students, a name, and a list of scores which it then stores in a dictionary. The final input is the name that will return that students average scores.
tagged with: python-3.x
type: UnansweredQuestion
upvote count: 1
tagged with: python
duplicate of: http://stackoverflow.com/q/2921847
answer count: 0
has title: what does *line mean in this code?
downvote count: 1
type: Question
linked to: http://stackoverflow.com/q/2921847
score: 0

http://stackoverflow.com/comment/84746881
type: QuestionComment
comment on: http://stackoverflow.com/q/48871537
score: 0
has text: Possible duplicate of [How can I read inputs as integers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-integers)
type: Comment

http://stackoverflow.com/comment/84802606
comment on: http://stackoverflow.com/q/48898481
score: 0
type: Comment
type: QuestionComment
has text: Please [edit] your code into the question. As you've found out, it's unreadable in a comment.

http://stackoverflow.com/q/48805457
score: 0
has body: I have a rather peculiar problem, that I may know the cause, but not the solution. First I have the following file structure. ../../ ├── Folder1 │ ├── Folder2 │ │ ├── File3.py │ │ ├── __init__.py │ │ ├── import_test.py │ │ ├── File2.py │ │ ├── File1.py │ │ └── util.pyc │ ├── __init__.py │ └── main.py ├── tests │ ├── func │ │ └── __init__.py │ ├── unit │ │ ├── __init__.py │ │ ├── test_File2.py │ │ └── test_File1.py │ ├── conftest.py │ ├── pytest.ini ├── __init__.py └── setup.py The contents of test_File1.py is similar to the following (although sanitized). import pytest, signal, json import Folder1.Folder2.File1 as file1 from Folder1.Folder2.File1 import ClassA from Folder1.Folder2.File1 import ClassB @pytest.fixture() def sample_data1(): data = "yyyyy" return data @pytest.fixture() def sample_data2(): data = 'xxxxx' return data def test_func1(sample_data1): def test_func2(sample_data1): class TestClassB(): def test_func1(self, sample_data2): When the above test is being loaded collected into pytest, the following error occurs. =========================================================== ERRORS =========================================================== __________________________________________ ERROR collecting tests/unit/test_File1.py _________________________________________ ImportError while importing test module '/home/procyclinsur/Documents/Projects/xxxxxx/xxxxxx/xxxxxx/tests/unit/test_File1.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: ../../tests/unit/test_File1.py:4: in &lt;module&gt; from Folder1.Folder2.File1 import ClassB E ImportError: cannot import name ClassB !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ================================================== 1 error in 0.20 seconds =================================================== That being said, I have a feeling that the problem lies in ClassB's implementation. I had problems before get…
tagged with: unit-testing
type: Question
has comment: http://stackoverflow.com/comment/84625549
tagged with: testing
has title: pytest can import ClassA from File1 but not ClassB from the same file
has comment: http://stackoverflow.com/comment/84640698
answer count: 1
has answer: http://stackoverflow.com/a/48818701
accepted answer: http://stackoverflow.com/a/48818701
has comment: http://stackoverflow.com/comment/84641150
has comment: http://stackoverflow.com/comment/84640588
has comment: http://stackoverflow.com/comment/84640142
has comment: http://stackoverflow.com/comment/84640562
tagged with: python
type: AnsweredQuestion
tagged with: pytest

http://stackoverflow.com/comment/84678450
type: AnswerComment
score: 0
type: Comment
has text: Smart. One issue: if no City found, this defaults to 0 index [i.e. Phoenix].
comment on: http://stackoverflow.com/a/48836783

http://stackoverflow.com/comment/84726843
type: Comment
has text: ok, thanks. i'll see if I can apply that to my exact use case.
comment on: http://stackoverflow.com/a/48830004
type: AnswerComment
score: 0

http://stackoverflow.com/a/67021086
type: Answer
upvote count: 3
answers question: http://stackoverflow.com/q/48915810
score: 3
downvote count: 0
has body: A tensor whose values are laid out in the storage starting from the rightmost dimension onward (that is, moving along rows for a 2D tensor) is defined as contiguous. Contiguous tensors are convenient because we can visit them efficiently in order without jumping around in the storage (improving data locality improves performance because of the way memory access works on modern CPUs). This advantage of course depends on the way algorithms visit. Some tensor operations in PyTorch only work on contiguous tensors, such as view, [...]. In that case, PyTorch will throw an informative exception and require us to call contiguous explicitly. It’s worth noting that calling contiguous will do nothing (and will not hurt performance) if the tensor is already contiguous. Deep Learning with PyTorch Note this is a more specific meaning than the general use of the word "contiguous" in computer science (i.e. contiguous and ordered). e.g given a tensor: [[1, 2] [3, 4]] Storage in memory PyTorch contiguous? Generally "contiguous" in memory-space? 1 2 3 4 0 0 0 ✅ ✅ 1 3 2 4 0 0 0 ❌ ✅ 1 0 2 0 3 0 4 ❌ ❌

http://stackoverflow.com/q/48832630
has body: I am trying to execute Python code inside Scala program passing RDD as data to the Python script. The Spark cluster is initialized successfully, the data conversion to RDD is fine and running the Python script separately(outside Scala code) works. However, the execution of the same Python script inside Scala fails with: java.lang.IllegalStateException: Subprocess exited with status 2. Command ran: /{filePath}/{File}.py Looking deeper, it shows import: command not found when trying to execute the Python file. I believe the built-in Scala executor cannot understand that this is a Python script. Note: My environment variables are set correctly and I can access and execute Python scripts from everywhere else. In place of filePath and File I have the actual path to that file and the file name. Environment: Spark 2.2.1 Scala 2.11.11 Python 2.7.10 Code: val conf=new SparkConf().setAppName("Test").setMaster("local[*]") val sparkContext = new SparkContext(conf) val distScript = "/{filePath}/{File}.py" val distScriptName = "{File}.py" sparkContext.addFile(distScript) val ipData = sparkContext.parallelize(List("asd","xyz","zxcz","sdfsfd","Ssdfd","Sdfsf")) val pipeRDD = ipData.pipe(SparkFiles.get(distScriptName)) pipeRDD.foreach(println) Have someone tried this before and is able to help resolving the issue I am getting? Is this the best way to integrate Scala and Python scripts? I am open for some other verified recommendations and suggestions to try.
tagged with: python-2.7
score: 0
tagged with: apache-spark
has title: Piping Scala RDD to Python code fails
answer count: 1
tagged with: scala
tagged with: python
has comment: http://stackoverflow.com/comment/84670266
tagged with: rdd
has comment: http://stackoverflow.com/comment/84670164
type: AnsweredQuestion
has comment: http://stackoverflow.com/comment/84670339
type: Question
has answer: http://stackoverflow.com/a/48833268
accepted answer: http://stackoverflow.com/a/48833268

http://stackoverflow.com/a/48805830
upvote count: 4
answers question: http://stackoverflow.com/q/48805277
downvote count: 0
score: 4
has body: If both your lists have the same amount of names, you could store the indices of each element in a collections.defaultdict, then pop off each index and use it as the sort key when an item is found during sorting. Demo: from collections import defaultdict, deque lst_1 = [[1, 'John'], [2, 'Mcquin'], [4, 'Paul'], [7, 'Jimmy'], [9, 'Coco'], [11, 'Coco']] lst_2 = [[3, 'Mcquin', 1], [6, 'Paul', 6], [5, 'John', 15], [12, 'Coco', 18], [8, 'Jimmy', 24], [10, 'Coco', 24]] sort_map = defaultdict(deque) for i, x in enumerate(lst_2): sort_map[x[1]].append(i) result = sorted(lst_1, key=lambda x: sort_map[x[1]].popleft()) print(result) Output: [[2, 'Mcquin'], [4, 'Paul'], [1, 'John'], [9, 'Coco'], [7, 'Jimmy'], [11, 'Coco']]. Note: You can use collections.deque to pop off elements from the beginning in constant time, as shown above. This minor improvement allows the above solution to remain at overall O(NlogN), which is the cost of sorting.
type: Answer

macos-sierra
tag name: macos-sierra
tags question: http://stackoverflow.com/q/48960039
type: Tag